summaryrefslogtreecommitdiffstats
path: root/tools/monitor/main.cpp
blob: a3c7ae770787d81c1d2f1eac55515dbc2bdb2497 (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
/**
 * A monitor application that runs a set of servers.
 * (C) 2009  Thorbjørn Lindeijer
 *
 * When a server crashes, a gdb process is spawned to create a backtrace,
 * which is emailed when the CRASH_REPORT_RECEIVER environment variable
 * is set. The crashed server is restarted.
 */

#include <QtCore>

#include <signal.h>
#include <sys/socket.h>
#include <unistd.h>

/**
 * A thread that keeps a server running. It restarts the server when it quits
 * for some external reason, and sends out backtraces when appropriate.
 */
class ServerThread : public QThread
{
public:
    ServerThread(const QString &executable, QObject *parent = 0)
        : QThread(parent)
        , mProcess(0)
        , mExecutable(executable)
        , mRunning(false)
    {}

    void runServer();
    void stopServer();

protected:
    void run();

private:
    void startProcess();
    void maybeSendBacktrace();

    QProcess *mProcess;
    QString mExecutable;
    QTime mLastCrash;
    bool mRunning;
};

void ServerThread::runServer()
{
    Q_ASSERT(!mRunning);
    if (!QFile::exists(mExecutable)) {
        qDebug() << mExecutable << "not found";
        return;
    }
    mRunning = true;
    start();
}

void ServerThread::run()
{
    mProcess = new QProcess;
    startProcess();

    while (mRunning) {
        mProcess->waitForFinished(1000);

        if (mRunning && mProcess->state() == QProcess::NotRunning) {
            /* The process stopped without being requested via the monitor.
             * Check for crash and send report when appropriate, then restart
             * the process.
             */
            qDebug() << mExecutable << "terminated unexpectedly";
            maybeSendBacktrace();

            qDebug() << "Restarting" << mExecutable << "in 3 seconds...";
            sleep(3);
            startProcess();
        }

        if (!mRunning && mProcess->state() == QProcess::Running) {
            // Need to shut down the process
            qDebug() << "Terminating" << mExecutable;
            mProcess->terminate();
            if (!mProcess->waitForFinished(3000)) {
                qDebug() << mExecutable << "didn't terminate within 3 seconds,"
                        " killing";
                mProcess->kill();
            }
            break;
        }
    }

    delete mProcess;
    mProcess = 0;
}

void ServerThread::startProcess()
{
    mProcess->start(mExecutable);

    // Give the process 3 seconds to start up
    if (!mProcess->waitForStarted(3000)) {
        qDebug() << "Failed to start" << mExecutable;
        mRunning = false;
    } else {
        qDebug() << mExecutable << "started";
    }
}

void ServerThread::maybeSendBacktrace()
{
    QFile coreFile("core");

    if (!coreFile.exists()) {
        qDebug() << "No core dump found";
        return;
    }

    char *receiver = getenv("CRASH_REPORT_RECEIVER");
    if (!receiver) {
        qDebug() << "CRASH_REPORT_RECEIVER environment variable not set";
        return;
    }

    QProcess gdb;
    gdb.start(QString("gdb %1 core -q -x print-backtrace.gdb")
            .arg(mExecutable));

    if (!gdb.waitForStarted()) {
        qDebug() << "Failed to launch gdb";
        coreFile.remove();
        return;
    }

    if (!gdb.waitForFinished()) {
        qDebug() << "gdb process is not finishing, killing";
        gdb.kill();
        coreFile.remove();
        return;
    }

    coreFile.remove();

    const QByteArray gdbOutput = gdb.readAllStandardOutput();
    qDebug() << "gdb output:\n" << gdbOutput.constData();

    QTime current = QTime::currentTime();
    if (!mLastCrash.isNull() && mLastCrash.secsTo(current) < 60 * 10) {
        qDebug() << "Sent a crash report less than 10 minutes ago, "
            "dropping this one";
        return;
    }

    mLastCrash = current;

    QProcess mail;
    mail.start(QString("mail -s \"Crash report for %1\" %2")
            .arg(mExecutable, QString::fromLocal8Bit(receiver)));

    if (!mail.waitForStarted()) {
        qDebug() << "Failed to launch mail";
        return;
    }

    mail.write(gdbOutput);
    mail.closeWriteChannel();

    if (mail.waitForFinished()) {
        qDebug() << "Crash report sent to" << receiver;
    } else {
        qDebug() << "mail process is not finishing, killing";
        mail.kill();
    }
}


void ServerThread::stopServer()
{
    mRunning = false;
    wait();
}

class ServerMonitor : public QObject
{
    Q_OBJECT

public:
    ServerMonitor(const QStringList &serverExecutables);

    void start()
    {
        foreach (ServerThread *server, mServers)
            server->runServer();
    }

    static void setupUnixSignalHandlers();
    static void termSignalHandler(int);

private slots:
    void aboutToQuit()
    {
        // Stop servers in reverse order
        for (int i = mServers.count() - 1; i >= 0; --i)
            mServers[i]->stopServer();
    }

    void handleSigTerm();

private:
    QList<ServerThread*> mServers;
    QSocketNotifier *snTerm;

    static int sigtermFd[2];
};


/* What follows is a bit of jumping through hoops in order to perform Qt stuff
 * in response to UNIX signals. Based on documentation at:
 * http://doc.trolltech.com/4.5/unix-signals.html
 */

int ServerMonitor::sigtermFd[2];

ServerMonitor::ServerMonitor(const QStringList &serverExecutables)
{
    if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigtermFd))
        qFatal("Couldn't create TERM socketpair");

    snTerm = new QSocketNotifier(sigtermFd[1], QSocketNotifier::Read, this);
    connect(snTerm, SIGNAL(activated(int)),
            QCoreApplication::instance(), SLOT(quit()));

    foreach (const QString &executable, serverExecutables)
        mServers.append(new ServerThread(executable, this));
}

void ServerMonitor::setupUnixSignalHandlers()
{
    struct sigaction term;
    term.sa_handler = ServerMonitor::termSignalHandler;
    sigemptyset(&term.sa_mask);
    term.sa_flags = SA_RESTART;

    if (sigaction(SIGTERM, &term, 0))
        qFatal("Could not set TERM signal handler");
}

void ServerMonitor::termSignalHandler(int)
{
    char tmp = 1;
    ssize_t num = ::write(sigtermFd[0], &tmp, sizeof(tmp));
    Q_UNUSED(num);
}

void ServerMonitor::handleSigTerm()
{
    snTerm->setEnabled(false);
    char tmp;
    ssize_t num = ::read(sigtermFd[1], &tmp, sizeof(tmp));
    Q_UNUSED(num);

    QCoreApplication::quit();

    snTerm->setEnabled(true);
}


int main(int argc, char *argv[])
{
    ServerMonitor::setupUnixSignalHandlers();

    QCoreApplication app(argc, argv);

    QStringList arguments = app.arguments();
    QStringList serverExecutables;

    if (!arguments.count() > 1) {
        arguments.removeFirst();
        serverExecutables = arguments;
    } else {
        serverExecutables
                << "src/manaserv-account"
                << "src/manaserv-game";
    }

    ServerMonitor monitor(serverExecutables);
    monitor.start();

    QObject::connect(&app, SIGNAL(aboutToQuit()),
                     &monitor, SLOT(aboutToQuit()));

    return app.exec();
}

#include "main.moc"