summaryrefslogtreecommitdiffstats
path: root/src/libs/installer/genericdatacache.cpp
blob: 7f21a5365a05c8c8c365bf7024c21380604aa89a (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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/**************************************************************************
**
** Copyright (C) 2022 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Installer Framework.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
**************************************************************************/

#include "genericdatacache.h"

#include "errors.h"
#include "fileutils.h"
#include "globals.h"
#include "metadata.h"
#include "updater.h"

#include <QDir>
#include <QDirIterator>
#include <QtConcurrent>

namespace QInstaller {

static const QLatin1String scManifestFile("manifest.json");

/*!
    \inmodule QtInstallerFramework
    \class QInstaller::CacheableItem
    \brief The CacheableItem is a pure virtual class that defines an interface for
           a type suited for storage with the \l{GenericDataCache} class.
*/

/*!
    \fn QInstaller::CacheableItem::path() const

    Returns the path of this item. A subclass may override this method.
*/

/*!
    \fn QInstaller::CacheableItem::setPath(const QString &path)

    Sets the path of the item to \a path. A subclass may override this method.
*/

/*!
    \fn QInstaller::CacheableItem::checksum() const

    Returns the checksum of this item. A subclass must implement this method.
*/

/*!
    \fn QInstaller::CacheableItem::isValid() const

    Returns \c true if this item is valid, \c false otherwise.
    A subclass must implement this method.
*/

/*!
    \fn QInstaller::CacheableItem::isActive const

    Returns \c true if this item is an actively used cache item, \c false otherwise.
    This information is used as a hint for filtering obsolete entries, an active item
    can never be obsolete.

    A subclass must implement this method.
*/

/*!
    \fn QInstaller::CacheableItem::obsoletes(CacheableItem *other)

    Returns \c true if the calling item obsoletes \a other item, \c false otherwise.
    This method is used for filtering obsolete entries from the cache.

    A subclass must implement this method.
*/

/*!
    Virtual destructor for \c CacheableItem.
*/
CacheableItem::~CacheableItem()
{
}


/*!
    \inmodule QtInstallerFramework
    \class QInstaller::GenericDataCache
    \brief The GenericDataCache is a template class for a checksum based storage
           of items on disk.

    GenericDataCache\<T\> manages a cache storage for a set \l{path()}, which contains
    a subdirectory for each registered item. An item of type \c T should implement
    methods declared in the \l{CacheableItem} interface. The GenericDataCache\<T\> class can
    still be explicitly specialized to use the derived type as a template argument, to
    allow retrieving items as the derived type without casting.
*/

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::GenericDataCache()

    Constructs a new empty cache. The cache is invalid until set with a
    path and initialized.
*/
template <typename T>
GenericDataCache<T>::GenericDataCache()
    : m_version(QLatin1String("1.0.0"))
    , m_invalidated(true)
{
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::GenericDataCache(const QString &path, const QString &type, const QString &version)

    Constructs a cache to \a path with the given \a type and \a version.
    The cache is initialized automatically.
*/
template <typename T>
GenericDataCache<T>::GenericDataCache(const QString &path, const QString &type,
                                      const QString &version)
    : m_path(path)
    , m_type(type)
    , m_version(version)
    , m_invalidated(true)
{
    initialize();
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::~GenericDataCache()

    Deletes the cache object. Item contents on disk are kept.
*/
template <typename T>
GenericDataCache<T>::~GenericDataCache()
{
    if (m_invalidated)
        return;

    toDisk();
    invalidate();
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::setType(const QString &type)

    Sets the name of the wrapped type to \a type. This is used for determining if an
    existing cache holds items of the same type. Trying to load cached items with mismatching
    type results in discarding the old items. Optional.
*/
template<typename T>
void GenericDataCache<T>::setType(const QString &type)
{
    m_type = type;
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::setVersion(const QString &version)

    Sets the version of the cache to \a version. Loading from a cache with different
    expected version discards the old items. The version property defaults to \c{1.0.0}.
*/
template<typename T>
void GenericDataCache<T>::setVersion(const QString &version)
{
    m_version = version;
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::initialize()

    Initializes a cache. Creates a new directory for the path configured for
    this cache if it does not exist, and loads any previously cached items from
    the directory. The cache directory is locked for access by this process only.
    Returns \c true on success, \c false otherwise.
*/
template <typename T>
bool GenericDataCache<T>::initialize()
{
    Q_ASSERT(m_items.isEmpty());

    if (m_path.isEmpty()) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot initialize cache with empty path."));
        return false;
    }

    QDir directory(m_path);
    if (!directory.exists() && !directory.mkpath(m_path)) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot create directory \"%1\" for cache.").arg(m_path));
        return false;
    }

    if (m_lock && !m_lock->unlock()) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot initialize cache: %1").arg(m_lock->errorString()));
        return false;
    }

    m_lock.reset(new KDUpdater::LockFile(m_path + QLatin1String("/cache.lock")));
    if (!m_lock->lock()) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot initialize cache: %1").arg(m_lock->errorString()));
        return false;
    }

    if (!fromDisk())
        return false;

    m_invalidated = false;
    return true;
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::clear()

    Removes all items from the cache and deletes their contents on disk. If
    the cache directory becomes empty, it is also deleted. The cache becomes
    invalid after this action, even in case of error while clearing. In that
    case already deleted items will be lost. Returns \c true on success,
    \c false otherwise.
*/
template <typename T>
bool GenericDataCache<T>::clear()
{
    if (m_invalidated) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot clear invalidated cache."));
        return false;
    }

    QFile manifestFile(m_path + QDir::separator() + scManifestFile);
    if (manifestFile.exists() && !manifestFile.remove()) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot remove manifest file: %1").arg(manifestFile.errorString()));
        invalidate();
        return false;
    }

    bool success = true;
    for (T *item : qAsConst(m_items)) {
        try {
            QInstaller::removeDirectory(item->path());
        } catch (const Error &e) {
            setErrorString(QCoreApplication::translate("GenericDataCache",
                "Error while clearing cache: %1").arg(e.message()));
            success = false;
        }
    }

    invalidate();
    QDir().rmdir(m_path);
    return success;
}

/*!
   \fn template <typename T> QInstaller::GenericDataCache<T>::isValid() const

   Returns \c true if the cache is valid, \c false otherwise. A cache is considered
   valid when it is initialized to a set path.
*/
template<typename T>
bool GenericDataCache<T>::isValid() const
{
    return !m_invalidated;
}

/*!
   \fn template <typename T> QInstaller::GenericDataCache<T>::errorString() const

   Returns a string representing the last error with the cache.
*/
template<typename T>
QString GenericDataCache<T>::errorString() const
{
    return m_error;
}

/*!
   \fn template <typename T> QInstaller::GenericDataCache<T>::path() const

    Returns the path of the cache on disk.
*/
template <typename T>
QString GenericDataCache<T>::path() const
{
    return m_path;
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::setPath(const QString &path)

    Sets a new \a path for the cache and invalidates current items. Saves the information
    of the old cache to its manifest file.
*/
template <typename T>
void GenericDataCache<T>::setPath(const QString &path)
{
    if (!m_invalidated)
        toDisk();

    m_path = path;
    invalidate();
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::items() const

    Returns a list of cached items.
*/
template <typename T>
QList<T *> GenericDataCache<T>::items() const
{
    if (m_invalidated) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot retrieve items from invalidated cache."));
        return QList<T *>();
    }
    return m_items.values();
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::itemByChecksum(const QByteArray &checksum) const

    Returns an item that matches the \a checksum or \c nullptr in case
    no such item is cached.
*/
template <typename T>
T *GenericDataCache<T>::itemByChecksum(const QByteArray &checksum) const
{
    if (m_invalidated) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot retrieve item from invalidated cache."));
        return nullptr;
    }
    return m_items.value(checksum);
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::itemByPath(const QString &path) const

    Returns an item from the \a path or \c nullptr in case no such item
    is cached. Depending on the size of the cache, this can be much
    slower than retrieving an item with \l{itemByChecksum()}.
*/
template <typename T>
T *GenericDataCache<T>::itemByPath(const QString &path) const
{
    auto it = std::find_if(m_items.constBegin(), m_items.constEnd(),
        [&](T *item) {
            return (QDir::fromNativeSeparators(path) == QDir::fromNativeSeparators(item->path()));
        }
    );
    if (it != m_items.constEnd())
        return it.value();

    return nullptr;
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::registerItem(T *item, bool replace)

    Registers the \a item to the cache. If \a replace is set to \c true,
    the new \a item replaces a previous item with the same checksum.

    The cache takes ownership of the object pointed by \a item. The contents of the
    item are copied to the cache with a subdirectory name that matches the checksum
    of the item.

    Returns \c true on success or \c false if the item could not be registered.
*/
template <typename T>
bool GenericDataCache<T>::registerItem(T *item, bool replace)
{
    if (m_invalidated) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot register item to invalidated cache."));
        return false;
    }
    if (!item) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot register null item."));
        return false;
    }
    if (!item->isValid()) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot register invalid item with checksum %1").arg(QLatin1String(item->checksum())));
        return false;
    }
    if (m_items.contains(item->checksum())) {
        if (replace) {// replace existing item including contents on disk
            removeItem(item->checksum());
        } else {
            setErrorString(QCoreApplication::translate("GenericDataCache",
                "Cannot register item with checksum %1. An item with the same checksum "
                "already exists in cache.").arg(QLatin1String(item->checksum())));
            return false;
        }
    }

    const QString newPath = m_path + QDir::separator() + QString::fromLatin1(item->checksum());
    try {
        // A directory is in the way but it isn't registered to the current cache, remove.
        if (QDir().exists(newPath))
            QInstaller::removeDirectory(newPath);

        QInstaller::copyDirectoryContents(item->path(), newPath);
    } catch (const Error &e) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Error while copying item to path \"%1\": %2").arg(newPath, e.message()));
        return false;
    }

    item->setPath(newPath);
    if (item->isValid()) {
        m_items.insert(item->checksum(), item);
        return true;
    }
    return false;
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::removeItem(const QByteArray &checksum)

    Removes the item specified by \a checksum from the cache and deletes the
    contents of the item from disk. Returns \c true if the item
    was removed successfully, \c false otherwise.
*/
template <typename T>
bool GenericDataCache<T>::removeItem(const QByteArray &checksum)
{
    if (m_invalidated) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot remove item from invalidated cache."));
        return false;
    }
    QScopedPointer<T> item(m_items.take(checksum));
    if (!item) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot remove item specified by checksum %1: no such item exists.").arg(QLatin1String(checksum)));
        return false;
    }

    try {
        QInstaller::removeDirectory(item->path());
    } catch (const Error &e) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Error while removing directory \"%1\": %2").arg(item->path(), e.message()));
        return false;
    }
    return true;
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::obsoleteItems() const

    Returns items considered obsolete from the cache.
*/
template<typename T>
QList<T *> GenericDataCache<T>::obsoleteItems() const
{
    const QList<T *> obsoletes = QtConcurrent::blockingFiltered(m_items.values(),
        [&](T *item1) {
            if (item1->isActive()) // We can skip the iteration for active entries
                return false;

            for (T *item2 : qAsConst(m_items)) {
                if (item2->obsoletes(item1))
                    return true;
            }
            return false;
        }
    );
    return obsoletes;
}

/*!
   \fn template <typename T> QInstaller::GenericDataCache<T>::invalidate()

    Marks the cache invalid and clears all items. The contents
    on disk are not deleted. Releases the lock file of the cache.
*/
template <typename T>
void GenericDataCache<T>::invalidate()
{
    if (!m_items.isEmpty()) {
        qDeleteAll(m_items);
        m_items.clear();
    }
    if (m_lock && !m_lock->unlock()) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Error while invalidating cache: %1").arg(m_lock->errorString()));
    }
    m_invalidated = true;
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::setErrorString(const QString &error)

    Sets the current error string to \a error and prints it as a warning to the console.
*/
template<typename T>
void GenericDataCache<T>::setErrorString(const QString &error) const
{
    m_error = error;
    qCWarning(QInstaller::lcInstallerInstallLog) << error;
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::fromDisk()

    Reads the manifest file of the cache if one exists, and populates the internal
    hash from the file contents. Returns \c true if the manifests was read successfully
    or if the reading was omitted. This is the case if the file does not exist yet, or
    the type or version of the manifest does not match the current cache object. In case
    of mismatch the old items are not restored. Returns \c false otherwise.
*/
template<typename T>
bool GenericDataCache<T>::fromDisk()
{
    QFile manifestFile(m_path + QDir::separator() + scManifestFile);
    if (!manifestFile.exists()) // Not yet created
        return true;

    if (!manifestFile.open(QIODevice::ReadOnly)) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot open manifest file: %1").arg(manifestFile.errorString()));
        return false;
    }

    const QByteArray manifestData = manifestFile.readAll();
    const QJsonDocument manifestJsonDoc(QJsonDocument::fromJson(manifestData));
    const QJsonObject docJsonObject = manifestJsonDoc.object();

    const QJsonValue type = docJsonObject.value(QLatin1String("type"));
    if (type.toString() != m_type) {
        qCDebug(QInstaller::lcInstallerInstallLog) << "Discarding existing items from cache of type:"
            << type.toString() << ". New type:" << m_type;
        return true;
    }

    const QJsonValue version = docJsonObject.value(QLatin1String("version"));
    if (KDUpdater::compareVersion(version.toString(), m_version) != 0) {
        qCDebug(QInstaller::lcInstallerInstallLog) << "Discarding existing items from cache with version:"
            << version.toString() << ". New version:" << m_version;
        return true;
    }

    const QJsonArray itemsJsonArray = docJsonObject.value(QLatin1String("items")).toArray();
    for (const auto &itemJsonValue : itemsJsonArray) {
        const QString checksum = itemJsonValue.toString();

        QScopedPointer<T> item(new T(m_path + QDir::separator() + checksum));
        m_items.insert(checksum.toLatin1(), item.take());

        // The cache directory may contain other entries (unrelated directories or
        // invalid old cache items) which we don't care about, unless registering
        // a new entry requires overwriting them.
    }
    return true;
}

/*!
    \fn template <typename T> QInstaller::GenericDataCache<T>::toDisk()

    Writes the manifest file with the contents of the internal item hash.
    Returns \c true on success, \c false otherwise.
*/
template<typename T>
bool GenericDataCache<T>::toDisk()
{
    QFile manifestFile(m_path + QDir::separator() + scManifestFile);
    if (!manifestFile.open(QIODevice::WriteOnly)) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot open manifest file: %1").arg(manifestFile.errorString()));
        return false;
    }

    QJsonArray itemsJsonArray;
    const QList<QByteArray> keys = m_items.keys();
    for (const QByteArray &key : keys)
        itemsJsonArray.append(QJsonValue(QLatin1String(key)));

    QJsonObject docJsonObject;
    docJsonObject.insert(QLatin1String("items"), itemsJsonArray);
    docJsonObject.insert(QLatin1String("version"), m_version);
    if (!m_type.isEmpty())
        docJsonObject.insert(QLatin1String("type"), m_type);

    QJsonDocument manifestJsonDoc;
    manifestJsonDoc.setObject(docJsonObject);
    if (manifestFile.write(manifestJsonDoc.toJson()) == -1) {
        setErrorString(QCoreApplication::translate("GenericDataCache",
            "Cannot write contents for manifest file: %1").arg(manifestFile.errorString()));
        return false;
    }
    return true;
}

template class GenericDataCache<Metadata>;

} // namespace QInstaller