aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/remotelinux/tarpackagecreationstep.cpp
blob: 0d53d36ff55bb057d29b03a21698b7138a368afd (plain)
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "tarpackagecreationstep.h"

#include "deploymenttimeinfo.h"
#include "remotelinux_constants.h"
#include "remotelinuxtr.h"

#include <projectexplorer/buildmanager.h>
#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>

#include <utils/futuresynchronizer.h>
#include <utils/runextensions.h>

#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFutureWatcher>

#include <cstring>

using namespace ProjectExplorer;
using namespace Utils;

namespace RemoteLinux::Internal {

const char IgnoreMissingFilesKey[] = "RemoteLinux.TarPackageCreationStep.IgnoreMissingFiles";
const char IncrementalDeploymentKey[] = "RemoteLinux.TarPackageCreationStep.IncrementalDeployment";

const int TarBlockSize = 512;

struct TarFileHeader {
    char fileName[100];
    char fileMode[8];
    char uid[8];
    char gid[8];
    char length[12];
    char mtime[12];
    char chksum[8];
    char typeflag;
    char linkname[100];
    char magic[6];
    char version[2];
    char uname[32];
    char gname[32];
    char devmajor[8];
    char devminor[8];
    char fileNamePrefix[155];
    char padding[12];
};

class TarPackageCreationStep : public BuildStep
{
public:
    TarPackageCreationStep(BuildStepList *bsl, Id id);

    FilePath packageFilePath() const;

private:
    bool init() final;
    void doRun() final;
    void doCancel() final;
    bool fromMap(const QVariantMap &map) final;
    QVariantMap toMap() const final;
    QVariant data(Id id) const final;

    void raiseError(const QString &errorMessage);
    void raiseWarning(const QString &warningMessage);
    bool isPackagingNeeded() const;
    void deployFinished(bool success);
    void addNeededDeploymentFiles(const DeployableFile &deployable, const Kit *kit);
    void doPackage(QFutureInterface<bool> &fi, const Utils::FilePath &tarFilePath,
                   bool ignoreMissingFiles);
    bool appendFile(QFutureInterface<bool> &fi, QFile &tarFile, const QFileInfo &fileInfo,
                    const QString &remoteFilePath, const Utils::FilePath &tarFilePath,
                    bool ignoreMissingFiles);

    FilePath m_tarFilePath;
    bool m_deploymentDataModified = false;
    DeploymentTimeInfo m_deployTimes;
    BoolAspect *m_incrementalDeploymentAspect = nullptr;
    BoolAspect *m_ignoreMissingFilesAspect = nullptr;
    bool m_packagingNeeded = false;
    QList<DeployableFile> m_files;

    FutureSynchronizer m_synchronizer;
};

TarPackageCreationStep::TarPackageCreationStep(BuildStepList *bsl, Id id)
    : BuildStep(bsl, id)
{
    m_synchronizer.setCancelOnWait(true);
    connect(target(), &Target::deploymentDataChanged, this, [this] {
        m_deploymentDataModified = true;
    });
    m_deploymentDataModified = true;

    m_ignoreMissingFilesAspect = addAspect<BoolAspect>();
    m_ignoreMissingFilesAspect->setLabel(Tr::tr("Ignore missing files"),
                                         BoolAspect::LabelPlacement::AtCheckBox);
    m_ignoreMissingFilesAspect->setSettingsKey(IgnoreMissingFilesKey);

    m_incrementalDeploymentAspect = addAspect<BoolAspect>();
    m_incrementalDeploymentAspect->setLabel(Tr::tr("Package modified files only"),
                                         BoolAspect::LabelPlacement::AtCheckBox);
    m_incrementalDeploymentAspect->setSettingsKey(IncrementalDeploymentKey);

    setSummaryUpdater([this] {
        FilePath path = packageFilePath();
        if (path.isEmpty())
            return QString("<font color=\"red\">" + Tr::tr("Tarball creation not possible.")
                           + "</font>");
        return QString("<b>" + Tr::tr("Create tarball:") + "</b> " + path.toUserOutput());
    });
}

FilePath TarPackageCreationStep::packageFilePath() const
{
    if (buildDirectory().isEmpty())
        return {};
    const QString packageFileName = project()->displayName() + ".tar";
    return buildDirectory().pathAppended(packageFileName);
}

bool TarPackageCreationStep::init()
{
    m_tarFilePath = packageFilePath();
    m_packagingNeeded = isPackagingNeeded();
    return true;
}

void TarPackageCreationStep::doRun()
{
    const QList<DeployableFile> &files = target()->deploymentData().allFiles();

    if (m_incrementalDeploymentAspect->value()) {
        m_files.clear();
        for (const DeployableFile &file : files)
            addNeededDeploymentFiles(file, kit());
    } else {
        m_files = files;
    }

    emit addOutput(Tr::tr("Creating tarball..."), OutputFormat::NormalMessage);
    if (!m_packagingNeeded) {
        emit addOutput(Tr::tr("Tarball up to date, skipping packaging."), OutputFormat::NormalMessage);
        emit finished(true);
        return;
    }

    auto * const watcher = new QFutureWatcher<bool>(this);
    connect(watcher, &QFutureWatcher<bool>::finished, this, [this, watcher] {
        const bool success = !watcher->isCanceled() && watcher->result();
        if (success) {
            m_deploymentDataModified = false;
            emit addOutput(Tr::tr("Packaging finished successfully."), OutputFormat::NormalMessage);
        } else {
            emit addOutput(Tr::tr("Packaging failed."), OutputFormat::ErrorMessage);
        }
        emit finished(success);
        watcher->deleteLater();
        connect(BuildManager::instance(), &BuildManager::buildQueueFinished,
                this, &TarPackageCreationStep::deployFinished);
    });
    auto future = Utils::runAsync(&TarPackageCreationStep::doPackage, this,
                                  m_tarFilePath, m_ignoreMissingFilesAspect->value());
    watcher->setFuture(future);
    m_synchronizer.addFuture(future);
}

void TarPackageCreationStep::doCancel()
{
    m_synchronizer.cancelAllFutures();
}

bool TarPackageCreationStep::fromMap(const QVariantMap &map)
{
    if (!BuildStep::fromMap(map))
        return false;
    m_deployTimes.importDeployTimes(map);
    return true;
}

QVariantMap TarPackageCreationStep::toMap() const
{
    QVariantMap map = BuildStep::toMap();
    map.insert(m_deployTimes.exportDeployTimes());
    return map;
}

QVariant TarPackageCreationStep::data(Id id) const
{
    if (id == Constants::TarPackageFilePathId)
        return packageFilePath().toVariant();
    return {};
}

void TarPackageCreationStep::raiseError(const QString &errorMessage)
{
    emit addTask(DeploymentTask(Task::Error, errorMessage));
    emit addOutput(errorMessage, OutputFormat::Stderr);
}

void TarPackageCreationStep::raiseWarning(const QString &warningMessage)
{
    emit addTask(DeploymentTask(Task::Warning, warningMessage));
    emit addOutput(warningMessage, OutputFormat::ErrorMessage);
}

bool TarPackageCreationStep::isPackagingNeeded() const
{
    const FilePath packagePath = packageFilePath();
    if (!packagePath.exists() || m_deploymentDataModified)
        return true;

    const DeploymentData &dd = target()->deploymentData();
    for (int i = 0; i < dd.fileCount(); ++i) {
        if (dd.fileAt(i).localFilePath().isNewerThan(packagePath.lastModified()))
            return true;
    }

    return false;
}

void TarPackageCreationStep::deployFinished(bool success)
{
    disconnect(BuildManager::instance(), &BuildManager::buildQueueFinished,
               this, &TarPackageCreationStep::deployFinished);

    if (!success)
        return;

    const Kit *kit = target()->kit();

    // Store files that have been tar'd and successfully deployed
    for (const DeployableFile &file : std::as_const(m_files))
        m_deployTimes.saveDeploymentTimeStamp(file, kit, QDateTime());
}

void TarPackageCreationStep::addNeededDeploymentFiles(
        const DeployableFile &deployable,
        const Kit *kit)
{
    const QFileInfo fileInfo = deployable.localFilePath().toFileInfo();
    if (!fileInfo.isDir()) {
        if (m_deployTimes.hasLocalFileChanged(deployable, kit))
            m_files << deployable;
        return;
    }

    const QStringList files = QDir(deployable.localFilePath().toString())
            .entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

    if (files.isEmpty()) {
        m_files << deployable;
        return;
    }

    for (const QString &fileName : files) {
        const FilePath localFilePath = deployable.localFilePath().pathAppended(fileName);

        const QString remoteDir = deployable.remoteDirectory() + '/' + fileInfo.fileName();

        // Recurse through the subdirectories
        addNeededDeploymentFiles(DeployableFile(localFilePath, remoteDir), kit);
    }
}

void TarPackageCreationStep::doPackage(QFutureInterface<bool> &fi, const FilePath &tarFilePath,
                                       bool ignoreMissingFiles)
{
    // TODO: Optimization: Only package changed files
    QFile tarFile(tarFilePath.toFSPathString());

    if (!tarFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        raiseError(Tr::tr("Error: tar file %1 cannot be opened (%2).")
                   .arg(tarFilePath.toUserOutput(), tarFile.errorString()));
        fi.reportResult(false);
        return;
    }

    for (const DeployableFile &d : std::as_const(m_files)) {
        if (d.remoteDirectory().isEmpty()) {
            emit addOutput(Tr::tr("No remote path specified for file \"%1\", skipping.")
                .arg(d.localFilePath().toUserOutput()), OutputFormat::ErrorMessage);
            continue;
        }
        QFileInfo fileInfo = d.localFilePath().toFileInfo();
        if (!appendFile(fi, tarFile, fileInfo,
                        d.remoteDirectory() + QLatin1Char('/') + fileInfo.fileName(),
                        tarFilePath, ignoreMissingFiles)) {
            fi.reportResult(false);
            return;
        }
    }

    const QByteArray eofIndicator(2*sizeof(TarFileHeader), 0);
    if (tarFile.write(eofIndicator) != eofIndicator.length()) {
        raiseError(Tr::tr("Error writing tar file \"%1\": %2.")
            .arg(QDir::toNativeSeparators(tarFile.fileName()), tarFile.errorString()));
        fi.reportResult(false);
        return;
    }
    fi.reportResult(true);
}

static bool setFilePath(TarFileHeader &header, const QByteArray &filePath)
{
    if (filePath.length() <= int(sizeof header.fileName)) {
        std::memcpy(&header.fileName, filePath.data(), filePath.length());
        return true;
    }
    int sepIndex = filePath.indexOf('/');
    while (sepIndex != -1) {
        const int fileNamePart = filePath.length() - sepIndex;
        if (sepIndex <= int(sizeof header.fileNamePrefix)
                &&  fileNamePart <= int(sizeof header.fileName)) {
            std::memcpy(&header.fileNamePrefix, filePath.data(), sepIndex);
            std::memcpy(&header.fileName, filePath.data() + sepIndex + 1, fileNamePart);
            return true;
        }
        sepIndex = filePath.indexOf('/', sepIndex + 1);
    }
    return false;
}

static bool writeHeader(QFile &tarFile, const QFileInfo &fileInfo, const QString &remoteFilePath,
                        const FilePath &tarFilePath, QString *errorMessage)
{
    TarFileHeader header;
    std::memset(&header, '\0', sizeof header);
    if (!setFilePath(header, remoteFilePath.toUtf8())) {
        *errorMessage = Tr::tr("Cannot add file \"%1\" to tar-archive: path too long.")
            .arg(remoteFilePath);
        return false;
    }
    int permissions = (0400 * fileInfo.permission(QFile::ReadOwner))
        | (0200 * fileInfo.permission(QFile::WriteOwner))
        | (0100 * fileInfo.permission(QFile::ExeOwner))
        | (040 * fileInfo.permission(QFile::ReadGroup))
        | (020 * fileInfo.permission(QFile::WriteGroup))
        | (010 * fileInfo.permission(QFile::ExeGroup))
        | (04 * fileInfo.permission(QFile::ReadOther))
        | (02 * fileInfo.permission(QFile::WriteOther))
        | (01 * fileInfo.permission(QFile::ExeOther));
    const QByteArray permissionString = QString::fromLatin1("%1").arg(permissions,
        sizeof header.fileMode - 1, 8, QLatin1Char('0')).toLatin1();
    std::memcpy(&header.fileMode, permissionString.data(), permissionString.length());
    const QByteArray uidString = QString::fromLatin1("%1").arg(fileInfo.ownerId(),
        sizeof header.uid - 1, 8, QLatin1Char('0')).toLatin1();
    std::memcpy(&header.uid, uidString.data(), uidString.length());
    const QByteArray gidString = QString::fromLatin1("%1").arg(fileInfo.groupId(),
        sizeof header.gid - 1, 8, QLatin1Char('0')).toLatin1();
    std::memcpy(&header.gid, gidString.data(), gidString.length());
    const QByteArray sizeString = QString::fromLatin1("%1").arg(fileInfo.size(),
        sizeof header.length - 1, 8, QLatin1Char('0')).toLatin1();
    std::memcpy(&header.length, sizeString.data(), sizeString.length());
    const QByteArray mtimeString = QString::fromLatin1("%1").arg(
                fileInfo.lastModified().toSecsSinceEpoch(),
                sizeof header.mtime - 1, 8, QLatin1Char('0')).toLatin1();
    std::memcpy(&header.mtime, mtimeString.data(), mtimeString.length());
    if (fileInfo.isDir())
        header.typeflag = '5';
    std::memcpy(&header.magic, "ustar", sizeof "ustar");
    std::memcpy(&header.version, "00", 2);
    const QByteArray &owner = fileInfo.owner().toUtf8();
    std::memcpy(&header.uname, owner.data(), qMin<int>(owner.length(), sizeof header.uname - 1));
    const QByteArray &group = fileInfo.group().toUtf8();
    std::memcpy(&header.gname, group.data(), qMin<int>(group.length(), sizeof header.gname - 1));
    std::memset(&header.chksum, ' ', sizeof header.chksum);
    quint64 checksum = 0;
    for (size_t i = 0; i < sizeof header; ++i)
        checksum += reinterpret_cast<char *>(&header)[i];
    const QByteArray checksumString = QString::fromLatin1("%1").arg(checksum,
        sizeof header.chksum - 1, 8, QLatin1Char('0')).toLatin1();
    std::memcpy(&header.chksum, checksumString.data(), checksumString.length());
    header.chksum[sizeof header.chksum-1] = 0;
    if (!tarFile.write(reinterpret_cast<char *>(&header), sizeof header)) {
        *errorMessage = Tr::tr("Error writing tar file \"%1\": %2")
            .arg(tarFilePath.toUserOutput(), tarFile.errorString());
        return false;
    }
    return true;
}

bool TarPackageCreationStep::appendFile(QFutureInterface<bool> &fi,
                                        QFile &tarFile,
                                        const QFileInfo &fileInfo,
                                        const QString &remoteFilePath,
                                        const FilePath &tarFilePath,
                                        bool ignoreMissingFiles)
{
    QString errorMessage;
    if (!writeHeader(tarFile, fileInfo, remoteFilePath, tarFilePath, &errorMessage)) {
        raiseError(errorMessage);
        return false;
    }
    if (fileInfo.isDir()) {
        const QDir dir(fileInfo.absoluteFilePath());
        const QStringList files = dir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
        for (const QString &fileName : files) {
            const QString thisLocalFilePath = dir.path() + QLatin1Char('/') + fileName;
            const QString thisRemoteFilePath  = remoteFilePath + QLatin1Char('/') + fileName;
            if (!appendFile(fi, tarFile, QFileInfo(thisLocalFilePath), thisRemoteFilePath,
                            tarFilePath, ignoreMissingFiles)) {
                return false;
            }
        }
        return true;
    }

    const QString nativePath = QDir::toNativeSeparators(fileInfo.filePath());
    QFile file(fileInfo.filePath());
    if (!file.open(QIODevice::ReadOnly)) {
        const QString message = Tr::tr("Error reading file \"%1\": %2.")
                                .arg(nativePath, file.errorString());
        if (ignoreMissingFiles) {
            raiseWarning(message);
            return true;
        } else {
            raiseError(message);
            return false;
        }
    }

    const int chunkSize = 1024 * 1024;

    emit addOutput(Tr::tr("Adding file \"%1\" to tarball...").arg(nativePath),
                   OutputFormat::NormalMessage);

    // TODO: Wasteful. Work with fixed-size buffer.
    while (!file.atEnd() && file.error() == QFile::NoError && tarFile.error() == QFile::NoError) {
        const QByteArray data = file.read(chunkSize);
        tarFile.write(data);
        if (fi.isCanceled())
            return false;
    }
    if (file.error() != QFile::NoError) {
        raiseError(Tr::tr("Error reading file \"%1\": %2.").arg(nativePath, file.errorString()));
        return false;
    }

    const int blockModulo = file.size() % TarBlockSize;
    if (blockModulo != 0)
        tarFile.write(QByteArray(TarBlockSize - blockModulo, 0));

    if (tarFile.error() != QFile::NoError) {
        raiseError(Tr::tr("Error writing tar file \"%1\": %2.")
            .arg(QDir::toNativeSeparators(tarFile.fileName()), tarFile.errorString()));
        return false;
    }
    return true;
}

TarPackageCreationStepFactory::TarPackageCreationStepFactory()
{
    registerStep<TarPackageCreationStep>(Constants::TarPackageCreationStepId);
    setDisplayName(Tr::tr("Create tarball"));

    setSupportedConfiguration(RemoteLinux::Constants::DeployToGenericLinux);
    setSupportedStepList(ProjectExplorer::Constants::BUILDSTEPS_DEPLOY);
}

} // RemoteLinux::Internal