servermanager.cpp 14.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
    Copyright (c) 2008 Volker Krause <vkrause@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 "servermanager.h"
21
#include "servermanager_p.h"
22

23
24
#include "agenttype.h"
#include "agentmanager.h"
25
#include "session_p.h"
26
#include "firstrun_p.h"
27

28
#include "akonadicore_debug.h"
Laurent Montel's avatar
Laurent Montel committed
29

30
#include <Kdelibs4ConfigMigrator>
31
#include <KLocalizedString>
32

33
34
35
36
#include "private/protocol_p.h"
#include "private/standarddirs_p.h"
#include "private/dbus_p.h"
#include "private/instance_p.h"
37

Daniel Vrátil's avatar
Daniel Vrátil committed
38
39
40
41
42
43
#include <QDBusConnection>
#include <QDBusServiceWatcher>
#include <QDBusConnectionInterface>
#include <QDBusInterface>
#include <QDBusReply>
#include <QProcess>
44
#include <QTimer>
45
#include <QScopedPointer>
46
#include <qnamespace.h>
47
48
49
50
51

using namespace Akonadi;

class Akonadi::ServerManagerPrivate
{
Guy Maurel's avatar
Guy Maurel committed
52
53
54
55
56
public:
    ServerManagerPrivate()
        : instance(new ServerManager(this))
        , mState(ServerManager::NotRunning)
        , mSafetyTimer(new QTimer)
57
    {
Guy Maurel's avatar
Guy Maurel committed
58
59
60
        mState = instance->state();
        mSafetyTimer->setSingleShot(true);
        mSafetyTimer->setInterval(30000);
Laurent Montel's avatar
Laurent Montel committed
61
        QObject::connect(mSafetyTimer.data(), &QTimer::timeout, instance, [this]() { timeout();});
Guy Maurel's avatar
Guy Maurel committed
62
63
64
        if (mState == ServerManager::Running && Internal::clientType() == Internal::User && !ServerManager::hasInstanceIdentifier()) {
            mFirstRunner = new Firstrun(instance);
        }
65
66
67
68
    }

    ~ServerManagerPrivate()
    {
Guy Maurel's avatar
Guy Maurel committed
69
        delete instance;
70
71
    }

72
73
    void checkStatusChanged()
    {
Guy Maurel's avatar
Guy Maurel committed
74
        setState(instance->state());
75
76
    }

Guy Maurel's avatar
Guy Maurel committed
77
    void setState(ServerManager::State state)
78
    {
Guy Maurel's avatar
Guy Maurel committed
79
80
        if (mState != state) {
            mState = state;
81
            Q_EMIT instance->stateChanged(state);
Guy Maurel's avatar
Guy Maurel committed
82
            if (state == ServerManager::Running) {
83
                Q_EMIT instance->started();
Guy Maurel's avatar
Guy Maurel committed
84
85
86
87
                if (!mFirstRunner && Internal::clientType() == Internal::User && !ServerManager::hasInstanceIdentifier()) {
                    mFirstRunner = new Firstrun(instance);
                }
            } else if (state == ServerManager::NotRunning || state == ServerManager::Broken) {
88
                Q_EMIT instance->stopped();
Guy Maurel's avatar
Guy Maurel committed
89
            }
Laurent Montel's avatar
Laurent Montel committed
90
91
92
93
94
            if (state == ServerManager::Starting || state == ServerManager::Stopping) {
                QMetaObject::invokeMethod(mSafetyTimer.data(), QOverload<>::of(&QTimer::start), Qt::QueuedConnection);   // in case we are in a different thread
            } else {
                QMetaObject::invokeMethod(mSafetyTimer.data(), &QTimer::stop, Qt::QueuedConnection);   // in case we are in a different thread
            }
95
        }
96
97
98
99
    }

    void timeout()
    {
Guy Maurel's avatar
Guy Maurel committed
100
101
102
        if (mState == ServerManager::Starting || mState == ServerManager::Stopping) {
            setState(ServerManager::Broken);
        }
103
104
    }

Laurent Montel's avatar
Laurent Montel committed
105
    ServerManager *instance = nullptr;
106
    static int serverProtocolVersion;
107
    static uint generation;
108
    ServerManager::State mState;
109
    QScopedPointer<QTimer> mSafetyTimer;
Laurent Montel's avatar
Laurent Montel committed
110
    Firstrun *mFirstRunner = nullptr;
111
    static Internal::ClientType clientType;
112
    QString mBrokenReason;
113
    std::unique_ptr<QDBusServiceWatcher> serviceWatcher;
114
115
};

116
int ServerManagerPrivate::serverProtocolVersion = -1;
117
uint ServerManagerPrivate::generation = 0;
118
Internal::ClientType ServerManagerPrivate::clientType = Internal::User;
119

120
Q_GLOBAL_STATIC(ServerManagerPrivate, sInstance)
121

Guy Maurel's avatar
Guy Maurel committed
122
123
ServerManager::ServerManager(ServerManagerPrivate *dd)
    : d(dd)
124
{
Laurent Montel's avatar
Laurent Montel committed
125
126
127
128
    Kdelibs4ConfigMigrator migrate(QStringLiteral("servermanager"));
    migrate.setConfigFiles(QStringList() << QStringLiteral("akonadi-firstrunrc"));
    migrate.migrate();

Guy Maurel's avatar
Guy Maurel committed
129
130
    qRegisterMetaType<Akonadi::ServerManager::State>();

131
    d->serviceWatcher = std::make_unique<QDBusServiceWatcher>(
132
            ServerManager::serviceName(ServerManager::Server), QDBusConnection::sessionBus(),
133
134
135
136
            QDBusServiceWatcher::WatchForRegistration | QDBusServiceWatcher::WatchForUnregistration);
    d->serviceWatcher->addWatchedService(ServerManager::serviceName(ServerManager::Control));
    d->serviceWatcher->addWatchedService(ServerManager::serviceName(ServerManager::ControlLock));
    d->serviceWatcher->addWatchedService(ServerManager::serviceName(ServerManager::UpgradeIndicator));
Guy Maurel's avatar
Guy Maurel committed
137
138
139
140
141

    // this (and also the two connects below) are queued so that they trigger after AgentManager is done loading
    // the current agent types and instances
    // this ensures the invariant of AgentManager reporting a consistent state if ServerManager::state() == Running
    // that's the case with direct connections as well, but only after you enter the event loop once
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    connect(d->serviceWatcher.get(), &QDBusServiceWatcher::serviceRegistered,
            this, [this]() {
                d->serverProtocolVersion = -1;
                d->checkStatusChanged();
            }, Qt::QueuedConnection);
    connect(d->serviceWatcher.get(), &QDBusServiceWatcher::serviceUnregistered,
            this, [this](const QString &name) {
                if (name == ServerManager::serviceName(ServerManager::ControlLock) && d->mState == ServerManager::Starting) {
                    // Control.Lock has disappeared during startup, which means that akonadi_control
                    // has terminated, most probably because it was not able to start akonadiserver
                    // process. Don't wait 30 seconds for sefetyTimeout, but go into Broken state
                    // immediately.
                    d->setState(ServerManager::Broken);
                    return;
                }

                d->serverProtocolVersion = -1;
                d->checkStatusChanged();
            }, Qt::QueuedConnection);
Guy Maurel's avatar
Guy Maurel committed
161
162
163
164
165
166
167

    // AgentManager is dangerous to use for agents themselves
    if (Internal::clientType() != Internal::User) {
        return;
    }
    connect(AgentManager::self(), SIGNAL(typeAdded(Akonadi::AgentType)), SLOT(checkStatusChanged()), Qt::QueuedConnection);
    connect(AgentManager::self(), SIGNAL(typeRemoved(Akonadi::AgentType)), SLOT(checkStatusChanged()), Qt::QueuedConnection);
168
169
}

Guy Maurel's avatar
Guy Maurel committed
170
ServerManager *Akonadi::ServerManager::self()
171
{
Guy Maurel's avatar
Guy Maurel committed
172
    return sInstance->instance;
173
174
175
176
}

bool ServerManager::start()
{
177
178
    const bool controlRegistered = QDBusConnection::sessionBus().interface()->isServiceRegistered(ServerManager::serviceName(ServerManager::Control));
    const bool serverRegistered = QDBusConnection::sessionBus().interface()->isServiceRegistered(ServerManager::serviceName(ServerManager::Server));
Guy Maurel's avatar
Guy Maurel committed
179
180
181
    if (controlRegistered && serverRegistered) {
        return true;
    }
182

183
    const bool controlLockRegistered = QDBusConnection::sessionBus().interface()->isServiceRegistered(ServerManager::serviceName(ServerManager::ControlLock));
Guy Maurel's avatar
Guy Maurel committed
184
    if (controlLockRegistered || controlRegistered) {
185
        qCDebug(AKONADICORE_LOG) << "Akonadi server is already starting up";
Guy Maurel's avatar
Guy Maurel committed
186
187
188
189
        sInstance->setState(Starting);
        return true;
    }

190
    qCDebug(AKONADICORE_LOG) << "executing akonadi_control";
Guy Maurel's avatar
Guy Maurel committed
191
192
    QStringList args;
    if (hasInstanceIdentifier()) {
193
        args << QStringLiteral("--instance") << instanceIdentifier();
194
    }
195
    const bool ok = QProcess::startDetached(QStringLiteral("akonadi_control"), args);
Guy Maurel's avatar
Guy Maurel committed
196
    if (!ok) {
197
        qCWarning(AKONADICORE_LOG) << "Unable to execute akonadi_control, falling back to D-Bus auto-launch";
198
        QDBusReply<void> reply = QDBusConnection::sessionBus().interface()->startService(ServerManager::serviceName(ServerManager::Control));
Guy Maurel's avatar
Guy Maurel committed
199
        if (!reply.isValid()) {
200
            qCDebug(AKONADICORE_LOG) << "Akonadi server could not be started via D-Bus either: "
Laurent Montel's avatar
Laurent Montel committed
201
                                     << reply.error().message();
Guy Maurel's avatar
Guy Maurel committed
202
203
204
205
206
            return false;
        }
    }
    sInstance->setState(Starting);
    return true;
207
208
209
210
}

bool ServerManager::stop()
{
Guy Maurel's avatar
Guy Maurel committed
211
    QDBusInterface iface(ServerManager::serviceName(ServerManager::Control),
212
213
                         QStringLiteral("/ControlManager"),
                         QStringLiteral("org.freedesktop.Akonadi.ControlManager"));
Guy Maurel's avatar
Guy Maurel committed
214
215
216
    if (!iface.isValid()) {
        return false;
    }
217
    iface.call(QDBus::NoBlock, QStringLiteral("shutdown"));
Guy Maurel's avatar
Guy Maurel committed
218
219
    sInstance->setState(Stopping);
    return true;
220
221
}

Guy Maurel's avatar
Guy Maurel committed
222
void ServerManager::showSelfTestDialog(QWidget *parent)
223
{
Daniel Vrátil's avatar
Daniel Vrátil committed
224
    Q_UNUSED(parent);
225
    QProcess::startDetached(QStringLiteral("akonadiselftest"), QStringList());
226
227
}

228
229
bool ServerManager::isRunning()
{
Guy Maurel's avatar
Guy Maurel committed
230
    return state() == Running;
231
}
232

233
234
ServerManager::State ServerManager::state()
{
Guy Maurel's avatar
Guy Maurel committed
235
236
237
    ServerManager::State previousState = NotRunning;
    if (sInstance.exists()) {   // be careful, this is called from the ServerManager::Private ctor, so using sInstance unprotected can cause infinite recursion
        previousState = sInstance->mState;
238
        sInstance->mBrokenReason.clear();
239
240
    }

241
    const bool serverUpgrading = QDBusConnection::sessionBus().interface()->isServiceRegistered(ServerManager::serviceName(ServerManager::UpgradeIndicator));
Guy Maurel's avatar
Guy Maurel committed
242
243
244
245
    if (serverUpgrading) {
        return Upgrading;
    }

246
247
    const bool controlRegistered = QDBusConnection::sessionBus().interface()->isServiceRegistered(ServerManager::serviceName(ServerManager::Control));
    const bool serverRegistered = QDBusConnection::sessionBus().interface()->isServiceRegistered(ServerManager::serviceName(ServerManager::Server));
Guy Maurel's avatar
Guy Maurel committed
248
249
250
251
    if (controlRegistered && serverRegistered) {
        // check if the server protocol is recent enough
        if (sInstance.exists()) {
            if (Internal::serverProtocolVersion() >= 0 &&
252
253
254
255
                    Internal::serverProtocolVersion() != Protocol::version()) {
                sInstance->mBrokenReason = i18n("The Akonadi server protocol version differs from the protocol version used by this application.\n"
                                                "If you recently updated your system please log out and back in to make sure all applications use the "
                                                "correct protocol version.");
Guy Maurel's avatar
Guy Maurel committed
256
257
258
259
260
261
262
                return Broken;
            }
        }

        // AgentManager is dangerous to use for agents themselves
        if (Internal::clientType() == Internal::User) {
            // besides the running server processes we also need at least one resource to be operational
Laurent Montel's avatar
Laurent Montel committed
263
264
            const AgentType::List agentTypes = AgentManager::self()->types();
            for (const AgentType &type : agentTypes) {
Laurent Montel's avatar
Laurent Montel committed
265
                if (type.capabilities().contains(QLatin1String("Resource"))) {
Guy Maurel's avatar
Guy Maurel committed
266
267
268
                    return Running;
                }
            }
269
270
271
            if (sInstance.exists()) {
                sInstance->mBrokenReason = i18n("There are no Akonadi Agents available. Please verify your KDE PIM installation.");
            }
Guy Maurel's avatar
Guy Maurel committed
272
273
274
275
276
277
            return Broken;
        } else {
            return Running;
        }
    }

278
    const bool controlLockRegistered = QDBusConnection::sessionBus().interface()->isServiceRegistered(ServerManager::serviceName(ServerManager::ControlLock));
Guy Maurel's avatar
Guy Maurel committed
279
    if (controlLockRegistered || controlRegistered) {
280
        qCDebug(AKONADICORE_LOG) << "Akonadi server is only partially running. Server:" << serverRegistered << "ControlLock:" << controlLockRegistered << "Control:" << controlRegistered;
Guy Maurel's avatar
Guy Maurel committed
281
282
        if (previousState == Running) {
            return NotRunning; // we don't know if it's starting or stopping, probably triggered by someone else
283
        }
Guy Maurel's avatar
Guy Maurel committed
284
        return previousState;
285
    }
286

Guy Maurel's avatar
Guy Maurel committed
287
    if (serverRegistered) {
288
        qCWarning(AKONADICORE_LOG) << "Akonadi server running without control process!";
Guy Maurel's avatar
Guy Maurel committed
289
290
291
292
293
        return Broken;
    }

    if (previousState == Starting) {   // valid case where nothing is running (yet)
        return previousState;
294
    }
Guy Maurel's avatar
Guy Maurel committed
295
    return NotRunning;
296
297
}

298
299
300
301
302
303
304
305
QString ServerManager::brokenReason()
{
    if (sInstance.exists()) {
        return sInstance->mBrokenReason;
    }
    return QString();
}

306
QString ServerManager::instanceIdentifier()
307
{
308
    return Instance::identifier();
309
310
}

311
bool ServerManager::hasInstanceIdentifier()
312
{
313
    return Instance::hasIdentifier();
314
}
315

Guy Maurel's avatar
Guy Maurel committed
316
QString ServerManager::serviceName(ServerManager::ServiceType serviceType)
317
{
Guy Maurel's avatar
Guy Maurel committed
318
319
    switch (serviceType) {
    case Server:
320
        return DBus::serviceName(DBus::Server);
Guy Maurel's avatar
Guy Maurel committed
321
    case Control:
322
        return DBus::serviceName(DBus::Control);
Guy Maurel's avatar
Guy Maurel committed
323
    case ControlLock:
324
        return DBus::serviceName(DBus::ControlLock);
Guy Maurel's avatar
Guy Maurel committed
325
    case UpgradeIndicator:
326
        return DBus::serviceName(DBus::UpgradeIndicator);
Guy Maurel's avatar
Guy Maurel committed
327
328
329
    }
    Q_ASSERT(!"WTF?");
    return QString();
330
331
}

Guy Maurel's avatar
Guy Maurel committed
332
QString ServerManager::agentServiceName(ServiceAgentType agentType, const QString &identifier)
333
{
Guy Maurel's avatar
Guy Maurel committed
334
    switch (agentType) {
335
    case Agent:
336
        return DBus::agentServiceName(identifier, DBus::Agent);
337
    case Resource:
338
        return DBus::agentServiceName(identifier, DBus::Resource);
339
    case Preprocessor:
340
        return DBus::agentServiceName(identifier, DBus::Preprocessor);
Guy Maurel's avatar
Guy Maurel committed
341
342
343
    }
    Q_ASSERT(!"WTF?");
    return QString();
344
345
}

346
347
QString ServerManager::serverConfigFilePath(OpenMode openMode)
{
348
349
350
351
    return StandardDirs::serverConfigFile(
            openMode == Akonadi::ServerManager::ReadOnly
                ? StandardDirs::ReadOnly
                : StandardDirs::ReadWrite);
352
353
354
355
}

QString ServerManager::agentConfigFilePath(const QString &identifier)
{
356
    return StandardDirs::agentConfigFile(identifier);
357
358
}

Guy Maurel's avatar
Guy Maurel committed
359
QString ServerManager::addNamespace(const QString &string)
360
{
361
362
    if (Instance::hasIdentifier()) {
        return string % QLatin1Char('_') % Instance::identifier();
Guy Maurel's avatar
Guy Maurel committed
363
364
    }
    return string;
365
366
}

367
368
369
370
371
uint ServerManager::generation()
{
    return Internal::generation();
}

372
int Internal::serverProtocolVersion()
373
{
Guy Maurel's avatar
Guy Maurel committed
374
    return ServerManagerPrivate::serverProtocolVersion;
375
376
}

Guy Maurel's avatar
Guy Maurel committed
377
void Internal::setServerProtocolVersion(int version)
378
{
Guy Maurel's avatar
Guy Maurel committed
379
380
381
382
    ServerManagerPrivate::serverProtocolVersion = version;
    if (sInstance.exists()) {
        sInstance->checkStatusChanged();
    }
383
384
}

385
386
387
388
389
390
391
392
393
394
uint Internal::generation()
{
    return ServerManagerPrivate::generation;
}

void Internal::setGeneration(uint generation)
{
    ServerManagerPrivate::generation = generation;
}

395
396
Internal::ClientType Internal::clientType()
{
Guy Maurel's avatar
Guy Maurel committed
397
    return ServerManagerPrivate::clientType;
398
399
}

Guy Maurel's avatar
Guy Maurel committed
400
void Internal::setClientType(ClientType type)
401
{
Guy Maurel's avatar
Guy Maurel committed
402
    ServerManagerPrivate::clientType = type;
403
404
}

405
#include "moc_servermanager.cpp"