cgroup_data_model.cpp 14.2 KB
Newer Older
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
/*
    Copyright (c) 2019 David Edmundson <davidedmundson@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "cgroup_data_model.h"

#include "cgroup.h"
#include "extended_process_list.h"
#include "process_attribute.h"
#include "process_data_model.h"
#include "Formatter.h"

#include <KLocalizedString>

#include <QMetaEnum>
#include <QTimer>
#include <QDebug>
#include <QDir>

#include <algorithm>
36
#include <filesystem>
37
38
39
40
41
42

using namespace  KSysGuard;

class KSysGuard::CGroupDataModelPrivate
{
public:
43
44
    QVector<KSysGuard::Process*> processesFor(CGroup *app);

45
    QSharedPointer<ExtendedProcesses> m_processes;
46
47
48
49
50
    QTimer *m_updateTimer;
    ProcessAttributeModel *m_attributeModel = nullptr;
    QHash<QString, KSysGuard::ProcessAttribute* > m_availableAttributes;
    QVector<KSysGuard::ProcessAttribute* > m_enabledAttributes;

51
    bool m_available = false;
52
53
54
55
56
57
    QString m_root;
    QScopedPointer<CGroup> m_rootGroup;

    QVector<CGroup *> m_cGroups; // an ordered list of unfiltered cgroups from our root
    QHash<QString, CGroup *> m_cgroupMap; // all known cgroups from our root
    QHash<QString, CGroup *> m_oldGroups;
58
    QHash<CGroup*, QVector<Process*>> m_processMap; // cached mapping of cgroup to list of processes of that group
59
60
61
62
63
64
65
66
};

class GroupNameAttribute : public ProcessAttribute
{
public:
    GroupNameAttribute(QObject *parent) :
        KSysGuard::ProcessAttribute(QStringLiteral("menuId"), i18nc("@title", "Desktop ID"), parent) {
    }
67
68
    QVariant cgroupData(CGroup *app, const QVector<KSysGuard::Process*> &processes) const override {
        Q_UNUSED(processes)
69
70
71
72
73
74
75
76
77
78
        return app->service()->menuId();
    }
};

class AppIconAttribute : public KSysGuard::ProcessAttribute
{
public:
    AppIconAttribute(QObject *parent) :
        KSysGuard::ProcessAttribute(QStringLiteral("iconName"), i18nc("@title", "Icon"), parent) {
    }
79
80
    QVariant cgroupData(CGroup *app, const QVector<KSysGuard::Process*> &processes) const override {
        Q_UNUSED(processes)
81
82
83
84
85
86
87
88
89
90
        return app->service()->icon();
    }
};

class AppNameAttribute : public KSysGuard::ProcessAttribute
{
public:
    AppNameAttribute(QObject *parent) :
        KSysGuard::ProcessAttribute(QStringLiteral("appName"), i18nc("@title", "Name"), parent) {
    }
91
92
    QVariant cgroupData(CGroup *app, const QVector<KSysGuard::Process*> &processes) const override {
        Q_UNUSED(processes)
93
94
95
96
97
        return app->service()->name();
    }
};

CGroupDataModel::CGroupDataModel(QObject *parent)
98
99
100
101
102
    : CGroupDataModel(QStringLiteral("/"), parent)
{
}

CGroupDataModel::CGroupDataModel(const QString &root, QObject *parent)
103
104
105
106
    : QAbstractItemModel(parent)
    , d(new CGroupDataModelPrivate)
{
    d->m_updateTimer = new QTimer(this);
107
    d->m_processes = ExtendedProcesses::instance();
108
109
110
111
112
113
114
115
116
117

    QVector<ProcessAttribute *> attributes = d->m_processes->attributes();
    attributes.reserve(attributes.count() + 3);
    attributes.append(new GroupNameAttribute(this));
    attributes.append(new AppNameAttribute(this));
    attributes.append(new AppIconAttribute(this));
    for (auto attr : qAsConst(attributes)) {
        d->m_availableAttributes[attr->id()] = attr;
    }

118
119
120
121
    if (CGroup::cgroupSysBasePath().isEmpty()) {
        return;
    }

122
123
124
125
126
127
    connect(d->m_updateTimer, &QTimer::timeout, this, [this]() {
        update();
    });
    d->m_updateTimer->setInterval(2000);
    d->m_updateTimer->start();

128
129
130
131
132
133
134
    // updateAllProcesses will delete processes that no longer exist, a method that
    // can be called by any user of the shared Processes
    // so clear out our cache of cgroup -> process whenever anything gets removed
    connect(d->m_processes.data(), &Processes::beginRemoveProcess, this, [this]() {
        d->m_processMap.clear();
    });

135
    setRoot(root);
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
}

CGroupDataModel::~CGroupDataModel()
{
}

int CGroupDataModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    }
    return d->m_cGroups.count();
}

QModelIndex CGroupDataModel::index(int row, int column, const QModelIndex &parent) const
{
    if (row < 0 || row >= d->m_cGroups.count()) {
        return QModelIndex();
    }
    if (parent.isValid()) {
        return QModelIndex();
    }
    return createIndex(row, column, d->m_cGroups.at(row));
}

QModelIndex CGroupDataModel::parent(const QModelIndex &child) const
{
    Q_UNUSED(child)
    return QModelIndex();
}

int CGroupDataModel::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    }

    return d->m_enabledAttributes.count();
}

QStringList CGroupDataModel::availableAttributes() const
{
    return d->m_availableAttributes.keys();
}

QStringList CGroupDataModel::enabledAttributes() const
{
    QStringList rc;
    rc.reserve(d->m_enabledAttributes.size());
    for (auto attr : qAsConst(d->m_enabledAttributes)) {
        rc << attr->id();
    }
    return rc;
}

void CGroupDataModel::setEnabledAttributes(const QStringList &enabledAttributes)
{
     beginResetModel();

     QVector<ProcessAttribute*> unusedAttributes = d->m_enabledAttributes;
     d->m_enabledAttributes.clear();

     for (auto attribute: enabledAttributes) {
         auto attr = d->m_availableAttributes.value(attribute, nullptr);
         if (!attr) {
             qWarning() << "Could not find attribute" << attribute;
             continue;
         }
         unusedAttributes.removeOne(attr);
         d->m_enabledAttributes << attr;
         int columnIndex = d->m_enabledAttributes.count() - 1;

         // reconnect as using the attribute in the lambda makes everything super fast
         disconnect(attr, &KSysGuard::ProcessAttribute::dataChanged, this, nullptr);
         connect(attr, &KSysGuard::ProcessAttribute::dataChanged, this, [this, columnIndex](KSysGuard::Process *process) {
             auto cgroup = d->m_cgroupMap.value(process->cGroup());
             if (!cgroup) {
                 return;
             }
             const QModelIndex index = getQModelIndex(cgroup, columnIndex);
             emit dataChanged(index, index);
         });

     }

     for (auto unusedAttr : qAsConst(unusedAttributes)) {
         disconnect(unusedAttr, &KSysGuard::ProcessAttribute::dataChanged, this, nullptr);
     }

     endResetModel();

     emit enabledAttributesChanged();
}

QModelIndex CGroupDataModel::getQModelIndex(CGroup *cgroup, int column) const
{
    Q_ASSERT(cgroup);
    int row = d->m_cGroups.indexOf(cgroup);
    return index(row, column, QModelIndex());
}

QHash<int, QByteArray> CGroupDataModel::roleNames() const
{
    QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
    QMetaEnum e = ProcessDataModel::staticMetaObject.enumerator(ProcessDataModel::staticMetaObject.indexOfEnumerator("AdditionalRoles"));

    for (int i = 0; i < e.keyCount(); ++i) {
        roles.insert(e.value(i), e.key(i));
    }

    return roles;
}

QVariant CGroupDataModel::data(const QModelIndex &index, int role) const
{
    if (!checkIndex(index, CheckIndexOption::IndexIsValid)) {
        return QVariant();
    }
    int attr = index.column();
    auto attribute = d->m_enabledAttributes[attr];
    switch(role) {
        case Qt::DisplayRole:
        case ProcessDataModel::FormattedValue: {
            KSysGuard::CGroup *app = reinterpret_cast< KSysGuard::CGroup* > (index.internalPointer());
260
            const QVariant value = attribute->cgroupData(app, d->processesFor(app));
261
262
263
264
            return KSysGuard::Formatter::formatValue(value, attribute->unit());
        }
        case ProcessDataModel::Value: {
            KSysGuard::CGroup *app = reinterpret_cast< KSysGuard::CGroup* > (index.internalPointer());
265
            const QVariant value = attribute->cgroupData(app, d->processesFor(app));
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
            return value;
        }
        case ProcessDataModel::Attribute: {
            return attribute->id();
        }
        case ProcessDataModel::Minimum: {
            return attribute->min();
        }
        case ProcessDataModel::Maximum: {
            return attribute->max();
        }
        case ProcessDataModel::ShortName: {
            if (!attribute->shortName().isEmpty()) {
                return attribute->shortName();
            }
            return attribute->name();
        }
        case ProcessDataModel::Name: {
            return attribute->name();
        }
        case ProcessDataModel::Unit: {
            return attribute->unit();
        }
        case ProcessDataModel::PIDs: {
290
291
292
293
            const auto pids = static_cast<KSysGuard::CGroup*>(index.internalPointer())->pids();
            QVariantList result;
            std::transform(pids.begin(), pids.end(), std::back_inserter(result), [](pid_t pid) { return int(pid); } );
            return result;
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
        }
    }
    return QVariant();
}

QVariant CGroupDataModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Vertical) {
        return QVariant();
    }

    if (section < 0 || section >= columnCount()) {
        return QVariant();
    }

    auto attribute = d->m_enabledAttributes[section];

    switch (role) {
    case Qt::DisplayRole:
    case ProcessDataModel::ShortName: {
        if (!attribute->shortName().isEmpty()) {
            return attribute->shortName();
        }
        return attribute->name();
    }
    case ProcessDataModel::Name:
        return attribute->name();
    case ProcessDataModel::Value:
    case ProcessDataModel::Attribute: {
        return attribute->id();
    }
    case ProcessDataModel::Unit: {
        auto attribute = d->m_enabledAttributes[section];
        return attribute->unit();
    }
    case ProcessDataModel::Minimum: {
        return attribute->min();
    }
    case ProcessDataModel::Maximum: {
        return attribute->max();
    }
    default:
        break;
    }

    return QVariant();
}

ProcessAttributeModel *CGroupDataModel::attributesModel()
{
    //lazy load
    if (!d->m_attributeModel) {
346
        d->m_attributeModel = new KSysGuard::ProcessAttributeModel(d->m_availableAttributes.values().toVector(), this);
347
348
349
350
351
352
353
354
355
356
357
358
359
    }
    return d->m_attributeModel;
}

bool CGroupDataModel::isEnabled() const
{
    return d->m_updateTimer->isActive();
}

void CGroupDataModel::setEnabled(bool enabled)
{
    if (enabled) {
        d->m_updateTimer->start();
360
        QMetaObject::invokeMethod(this, [this] {update();}, Qt::QueuedConnection);
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
    } else {
        d->m_updateTimer->stop();
    }
}

QString CGroupDataModel::root() const
{
    return d->m_root;
}

void CGroupDataModel::setRoot(const QString &root)
{
    if (root == d->m_root) {
        return;
    }
    d->m_root = root;
    emit rootChanged();
378
    QMetaObject::invokeMethod(this, [this] {update();}, Qt::QueuedConnection);
379
380
381
382
383
384
385
386
387
388
389
390
391
392

    const QString path = CGroup::cgroupSysBasePath() + root;
    bool available = QFile::exists(path);

    if (available) {
        d->m_rootGroup.reset(new CGroup(root));
    } else {
        d->m_rootGroup.reset();
    }

    if (available != d->m_available) {
        d->m_available = available;
        emit availableChanged();
    }
393
394
395
396
397
398
399
400
401
402
403
404
}

void CGroupDataModel::update()
{
    if (!d->m_rootGroup) {
        return;
    }

    d->m_oldGroups = d->m_cgroupMap;

    // In an ideal world we would only the relevant process
    // but Ksysguard::Processes doesn't handle that very well
405
    d->m_processes->updateAllProcesses(d->m_updateTimer->interval());
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427

    update(d->m_rootGroup.data());

    for (auto c : qAsConst(d->m_oldGroups)) {
        int row = d->m_cGroups.indexOf(c);
        if (row >= 0) {
            beginRemoveRows(QModelIndex(), row, row);
            d->m_cGroups.removeOne(c);
            endRemoveRows();
        }
        d->m_cgroupMap.remove(c->id());
        delete c;
    }
}

bool CGroupDataModel::filterAcceptsCGroup(const QString &id)
{
    return id.endsWith(QLatin1String(".service")) || id.endsWith(QLatin1String(".scope"));
}

void CGroupDataModel::update(CGroup *node)
{
428
    namespace fs = std::filesystem;
429
430
431
432
    const QString path = CGroup::cgroupSysBasePath() + node->id();

    // Update our own stat info
    // This may trigger some dataChanged
433
    node->requestPids(this, [this, node](QVector<pid_t> pids) {
434
        auto row = d->m_cGroups.indexOf(node);
435
436
        if (row >= 0) {
            d->m_cGroups[row]->setPids(pids);
437
            d->m_processMap.remove(d->m_cGroups[row]);
438
439
            Q_EMIT dataChanged(index(row, 0, QModelIndex()), index(row, columnCount()-1, QModelIndex()));
        }
440
    });
441

442
443
444
445
446
447

    for (const auto& entry : fs::directory_iterator(path.toUtf8().data())) {
        if (!entry.is_directory()) {
            continue;
        }
        const QString childId = node->id() % QLatin1Char('/') % QString::fromUtf8(entry.path().filename().c_str());
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
        CGroup *childNode = d->m_cgroupMap[childId];
        if (!childNode) {
            childNode = new CGroup(childId);
            d->m_cgroupMap[childNode->id()] = childNode;

            if (filterAcceptsCGroup(childId)) {
                int row = d->m_cGroups.count();
                beginInsertRows(QModelIndex(), row, row);
                d->m_cGroups.append(childNode);
                endInsertRows();
            }
        }
        update(childNode);
        d->m_oldGroups.remove(childId);
    }
}
464

465
466
467
468
469
bool CGroupDataModel::isAvailable() const
{
    return d->m_available;
}

470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
QVector<Process*> CGroupDataModelPrivate::processesFor(CGroup *app)
{
    if (m_processMap.contains(app)) {
        return m_processMap.value(app);
    }

    QVector<Process*> result;
    const auto pids = app->pids();
    std::for_each(pids.begin(), pids.end(), [this, &result](pid_t pid) {
        auto process = m_processes->getProcess(pid);
        if (process) {
            result.append(process);
        }
    });

    m_processMap.insert(app, result);

    return result;
}