File: cgroup.cpp

package info (click to toggle)
libksysguard 4%3A6.5.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,596 kB
  • sloc: cpp: 13,691; xml: 297; sh: 23; makefile: 11
file content (208 lines) | stat: -rw-r--r-- 5,879 bytes parent folder | download | duplicates (2)
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
/*
    SPDX-FileCopyrightText: 2019 David Edmundson <davidedmundson@kde.org>
    SPDX-FileCopyrightText: 2020 David Redondo <kde@david-redondo.de>

    SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "cgroup.h"

#include <QDebug>
#include <QDir>
#include <QFile>
#include <QPointer>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QStandardPaths>
#include <QStringView>
#include <QThreadPool>

#include "process.h"

#include <ranges>

using namespace KSysGuard;

class KSysGuard::CGroupPrivate
{
public:
    CGroupPrivate(const QString &_processGroupId)
        : processGroupId(_processGroupId)
        , service(serviceFromAppId(_processGroupId))
    {
    }
    const QString processGroupId;
    const KService::Ptr service;
    QList<pid_t> pids;

    static KService::Ptr serviceFromAppId(const QString &appId);

    static QRegularExpression s_appIdFromProcessGroupPattern;
    static QString unescapeName(const QString &cgroupId);

    class ReadPidsRunnable;
};

class CGroupPrivate::ReadPidsRunnable : public QRunnable
{
public:
    ReadPidsRunnable(QObject *context, const QString &path, std::function<void(QList<pid_t>)> callback)
        : m_context(context)
        , m_path(path)
        , m_callback(callback)
    {
    }

    void run() override
    {
        QFile pidFile(m_path);
        if (!pidFile.open(QFile::ReadOnly | QIODevice::Text)) {
            return;
        }
        QTextStream stream(&pidFile);

        QList<pid_t> pids;
        QString line = stream.readLine();
        while (!line.isNull()) {
            pids.append(line.toLong());
            line = stream.readLine();
        }
        // Ensure we call the callback on the thread the context object lives on.
        if (m_context) {
            QMetaObject::invokeMethod(m_context, std::bind(m_callback, pids));
        }
    }

private:
    QPointer<QObject> m_context;
    QString m_path;
    std::function<void(QList<pid_t>)> m_callback;
};

class CGroupSystemInformation
{
public:
    CGroupSystemInformation();
    QString sysGgroupRoot;
};

Q_GLOBAL_STATIC(CGroupSystemInformation, s_cGroupSystemInformation)

// The spec says that the two following schemes are allowed
// - app[-<launcher>]-<ApplicationID>-<RANDOM>.scope
// - app[-<launcher>]-<ApplicationID>[@<RANDOM>].service
// Flatpak's are currently in a cgroup, but they don't follow the specification
// this has been fixed, but this provides some compatibility till that lands
// app vs apps exists because the spec changed.
// We allow app[-<launcher>]-<ApplicationID>[@<RANDOM>].slice which is not standard but very close for gnome terminal
QRegularExpression
    CGroupPrivate::s_appIdFromProcessGroupPattern(QStringLiteral("(apps|app|flatpak)-(?:[^-]*-)?([^-]+(?=-.*\\.scope)|[^@]+(?=(?:@.*)?\\.service|.slice))"));

CGroup::CGroup(const QString &id)
    : d(new CGroupPrivate(id))
{
}

CGroup::~CGroup()
{
}

QString KSysGuard::CGroup::id() const
{
    return d->processGroupId;
}

KService::Ptr KSysGuard::CGroup::service() const
{
    return d->service;
}

QList<pid_t> CGroup::pids() const
{
    return d->pids;
}

void CGroup::setPids(const QList<pid_t> &pids)
{
    d->pids = pids;
}

void CGroup::requestPids(QObject *context, std::function<void(QList<pid_t>)> callback)
{
    QString path = cgroupSysBasePath() + d->processGroupId + QLatin1String("/cgroup.procs");
    auto readPidsRunnable = new CGroupPrivate::ReadPidsRunnable(context, path, callback);
    QThreadPool::globalInstance()->start(readPidsRunnable);
}

QString CGroupPrivate::unescapeName(const QString &name)
{
    // strings are escaped in the form of \xZZ where ZZ is a two digits in hex representing an ascii code
    QString rc = name;
    while (true) {
        int escapeCharIndex = rc.indexOf(QLatin1Char('\\'));
        if (escapeCharIndex < 0) {
            break;
        }
        const QStringView sequence = QStringView(rc).mid(escapeCharIndex, 4);
        if (sequence.length() != 4 || sequence.at(1) != QLatin1Char('x')) {
            qWarning() << "Badly formed cgroup name" << name;
            return name;
        }
        bool ok;
        int character = sequence.mid(2).toInt(&ok, 16);
        if (ok) {
            rc.replace(escapeCharIndex, 4, QLatin1Char(character));
        }
    }
    return rc;
}

KService::Ptr CGroupPrivate::serviceFromAppId(const QString &processGroup)
{
    const auto parts = processGroup.split(QLatin1Char('/'));

    QString appId;

    for (const auto &cgroupId : std::ranges::reverse_view(parts)) {
        const auto &appIdMatch = s_appIdFromProcessGroupPattern.match(cgroupId);
        if (appIdMatch.isValid() && appIdMatch.hasMatch()) {
            appId = unescapeName(appIdMatch.captured(2));
            break;
        }
    }

    if (appId.isEmpty()) {
        // create a transient service object just to have a sensible name
        return KService::Ptr(new KService(parts.last(), QString(), QString()));
    }

    KService::Ptr service = KService::serviceByMenuId(appId + QStringLiteral(".desktop"));
    if (!service && processGroup.endsWith(QLatin1String("@autostart.service"))) {
        auto file = QStandardPaths::locate(QStandardPaths::GenericConfigLocation, QLatin1String("autostart/%1.desktop").arg(appId));
        if (!file.isEmpty()) {
            service = new KService(file);
        }
    }
    if (!service) {
        service = new KService(appId, QString(), QString());
    }

    return service;
}

QString CGroup::cgroupSysBasePath()
{
    return s_cGroupSystemInformation->sysGgroupRoot;
}

CGroupSystemInformation::CGroupSystemInformation()
{
    QDir base(QStringLiteral("/sys/fs/cgroup"));
    if (base.exists(QLatin1String("unified"))) {
        sysGgroupRoot = base.absoluteFilePath(QStringLiteral("unified"));
        return;
    }
    if (base.exists()) {
        sysGgroupRoot = base.absolutePath();
    }
}