~ubuntu-branches/ubuntu/trusty/tomahawk/trusty-proposed

« back to all changes in this revision

Viewing changes to src/libtomahawk/database/DatabaseWorker.cpp

  • Committer: Package Import Robot
  • Author(s): Harald Sitter
  • Date: 2013-03-07 21:50:13 UTC
  • Revision ID: package-import@ubuntu.com-20130307215013-6gdjkdds7i9uenvs
Tags: upstream-0.6.0+dfsg
ImportĀ upstreamĀ versionĀ 0.6.0+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* === This file is part of Tomahawk Player - <http://tomahawk-player.org> ===
 
2
 *
 
3
 *   Copyright 2010-2011, Christian Muehlhaeuser <muesli@tomahawk-player.org>
 
4
 *   Copyright 2010-2011, Jeff Mitchell <jeff@tomahawk-player.org>
 
5
 *
 
6
 *   Tomahawk is free software: you can redistribute it and/or modify
 
7
 *   it under the terms of the GNU General Public License as published by
 
8
 *   the Free Software Foundation, either version 3 of the License, or
 
9
 *   (at your option) any later version.
 
10
 *
 
11
 *   Tomahawk is distributed in the hope that it will be useful,
 
12
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 
14
 *   GNU General Public License for more details.
 
15
 *
 
16
 *   You should have received a copy of the GNU General Public License
 
17
 *   along with Tomahawk. If not, see <http://www.gnu.org/licenses/>.
 
18
 */
 
19
 
 
20
#include "DatabaseWorker.h"
 
21
 
 
22
#include <QTimer>
 
23
#include <QTime>
 
24
#include <QSqlQuery>
 
25
 
 
26
#include "Source.h"
 
27
#include "Database.h"
 
28
#include "DatabaseImpl.h"
 
29
#include "DatabaseCommandLoggable.h"
 
30
#include "TomahawkSqlQuery.h"
 
31
#include "utils/Logger.h"
 
32
 
 
33
#ifndef QT_NO_DEBUG
 
34
    //#define DEBUG_TIMING TRUE
 
35
#endif
 
36
 
 
37
 
 
38
DatabaseWorkerThread::DatabaseWorkerThread( Database* db, bool mutates )
 
39
    : QThread()
 
40
    , m_db( db )
 
41
    , m_mutates( mutates )
 
42
{
 
43
}
 
44
 
 
45
 
 
46
void
 
47
DatabaseWorkerThread::run()
 
48
{
 
49
    tDebug() << Q_FUNC_INFO << "DatabaseWorkerThread starting...";
 
50
    m_worker = QWeakPointer< DatabaseWorker >( new DatabaseWorker( m_db, m_mutates ) );
 
51
    exec();    
 
52
    tDebug() << Q_FUNC_INFO << "DatabaseWorkerThread finishing...";
 
53
    if ( m_worker )
 
54
        delete m_worker.data();
 
55
}
 
56
 
 
57
 
 
58
DatabaseWorkerThread::~DatabaseWorkerThread()
 
59
{
 
60
}
 
61
 
 
62
 
 
63
QWeakPointer< DatabaseWorker >
 
64
DatabaseWorkerThread::worker() const
 
65
{
 
66
    return m_worker;
 
67
}
 
68
 
 
69
 
 
70
DatabaseWorker::DatabaseWorker( Database* db, bool mutates )
 
71
    : QObject()
 
72
    , m_db( db )
 
73
    , m_outstanding( 0 )
 
74
{
 
75
    Q_UNUSED( mutates );
 
76
    tDebug() << Q_FUNC_INFO << "New db connection with name:" << Database::instance()->impl()->database().connectionName() << "on thread" << this->thread();
 
77
}
 
78
 
 
79
 
 
80
DatabaseWorker::~DatabaseWorker()
 
81
{
 
82
    tDebug() << Q_FUNC_INFO << m_outstanding;
 
83
 
 
84
    if ( m_outstanding )
 
85
    {
 
86
        foreach ( const QSharedPointer<DatabaseCommand>& cmd, m_commands )
 
87
        {
 
88
            tDebug() << "Outstanding db command to finish:" << cmd->guid() << cmd->commandname();
 
89
        }
 
90
    }
 
91
}
 
92
 
 
93
 
 
94
void
 
95
DatabaseWorker::enqueue( const QList< QSharedPointer<DatabaseCommand> >& cmds )
 
96
{
 
97
    QMutexLocker lock( &m_mut );
 
98
    m_outstanding += cmds.count();
 
99
    m_commands << cmds;
 
100
 
 
101
    if ( m_outstanding == cmds.count() )
 
102
        QTimer::singleShot( 0, this, SLOT( doWork() ) );
 
103
}
 
104
 
 
105
 
 
106
void
 
107
DatabaseWorker::enqueue( const QSharedPointer<DatabaseCommand>& cmd )
 
108
{
 
109
    QMutexLocker lock( &m_mut );
 
110
    m_outstanding++;
 
111
    m_commands << cmd;
 
112
 
 
113
    if ( m_outstanding == 1 )
 
114
        QTimer::singleShot( 0, this, SLOT( doWork() ) );
 
115
}
 
116
 
 
117
 
 
118
void
 
119
DatabaseWorker::doWork()
 
120
{
 
121
    /*
 
122
        Run the dbcmd. Only inside a transaction if the cmd does mutates.
 
123
 
 
124
        If the cmd is modifying local content (ie source->isLocal()) then
 
125
        log to the database oplog for replication to peers.
 
126
 
 
127
     */
 
128
 
 
129
#ifdef DEBUG_TIMING
 
130
    QTime timer;
 
131
    timer.start();
 
132
#endif
 
133
 
 
134
    QList< QSharedPointer<DatabaseCommand> > cmdGroup;
 
135
    QSharedPointer<DatabaseCommand> cmd;
 
136
    {
 
137
        QMutexLocker lock( &m_mut );
 
138
        cmd = m_commands.takeFirst();
 
139
    }
 
140
 
 
141
    DatabaseImpl* impl = Database::instance()->impl();
 
142
    if ( cmd->doesMutates() )
 
143
    {
 
144
        bool transok = impl->database().transaction();
 
145
        Q_ASSERT( transok );
 
146
        Q_UNUSED( transok );
 
147
    }
 
148
 
 
149
    unsigned int completed = 0;
 
150
    try
 
151
    {
 
152
        bool finished = false;
 
153
        {
 
154
            while ( !finished )
 
155
            {
 
156
                completed++;
 
157
                cmd->_exec( impl ); // runs actual SQL stuff
 
158
 
 
159
                if ( cmd->loggable() )
 
160
                {
 
161
                    // We only save our own ops to the oplog, since incoming ops from peers
 
162
                    // are applied immediately.
 
163
                    //
 
164
                    // Crazy idea: if peers had keypairs and could sign ops/msgs, in theory it
 
165
                    // would be safe to sync ops for friend A from friend B's cache, if he saved them,
 
166
                    // which would mean you could get updates even if a peer was offline.
 
167
                    if ( cmd->source()->isLocal() && !cmd->localOnly() )
 
168
                    {
 
169
                        // save to op-log
 
170
                        DatabaseCommandLoggable* command = (DatabaseCommandLoggable*)cmd.data();
 
171
                        logOp( command );
 
172
                    }
 
173
                    else
 
174
                    {
 
175
                        // Make a note of the last guid we applied for this source
 
176
                        // so we can always request just the newer ops in future.
 
177
                        //
 
178
                        if ( !cmd->singletonCmd() )
 
179
                        {
 
180
                            TomahawkSqlQuery query = impl->newquery();
 
181
                            query.prepare( "UPDATE source SET lastop = ? WHERE id = ?" );
 
182
                            query.addBindValue( cmd->guid() );
 
183
                            query.addBindValue( cmd->source()->id() );
 
184
 
 
185
                            if ( !query.exec() )
 
186
                            {
 
187
                                throw "Failed to set lastop";
 
188
                            }
 
189
                        }
 
190
                    }
 
191
                }
 
192
 
 
193
                cmdGroup << cmd;
 
194
                if ( cmd->groupable() && !m_commands.isEmpty() )
 
195
                {
 
196
                    QMutexLocker lock( &m_mut );
 
197
                    if ( m_commands.first()->groupable() )
 
198
                    {
 
199
                        cmd = m_commands.takeFirst();
 
200
                    }
 
201
                    else
 
202
                    {
 
203
                        finished = true;
 
204
                    }
 
205
                }
 
206
                else
 
207
                    finished = true;
 
208
            }
 
209
 
 
210
            if ( cmd->doesMutates() )
 
211
            {
 
212
                qDebug() << "Committing" << cmd->commandname() << cmd->guid();
 
213
                if ( !impl->newquery().commitTransaction() )
 
214
                {
 
215
                    tDebug() << "FAILED TO COMMIT TRANSACTION*";
 
216
                    throw "commit failed";
 
217
                }
 
218
            }
 
219
 
 
220
#ifdef DEBUG_TIMING
 
221
            uint duration = timer.elapsed();
 
222
            tDebug() << "DBCmd Duration:" << duration << "ms, now running postcommit for" << cmd->commandname();
 
223
#endif
 
224
 
 
225
            foreach ( QSharedPointer<DatabaseCommand> c, cmdGroup )
 
226
                c->postCommit();
 
227
 
 
228
#ifdef DEBUG_TIMING
 
229
            tDebug() << "Post commit finished in" << timer.elapsed() - duration << "ms for" << cmd->commandname();
 
230
#endif
 
231
        }
 
232
    }
 
233
    catch( const char * msg )
 
234
    {
 
235
        tLog() << endl
 
236
                 << "*ERROR* processing databasecommand:"
 
237
                 << cmd->commandname()
 
238
                 << msg
 
239
                 << impl->database().lastError().databaseText()
 
240
                 << impl->database().lastError().driverText()
 
241
                 << endl;
 
242
 
 
243
        if ( cmd->doesMutates() )
 
244
            impl->database().rollback();
 
245
 
 
246
        Q_ASSERT( false );
 
247
    }
 
248
    catch(...)
 
249
    {
 
250
        qDebug() << "Uncaught exception processing dbcmd";
 
251
        if ( cmd->doesMutates() )
 
252
            impl->database().rollback();
 
253
 
 
254
        Q_ASSERT( false );
 
255
        throw;
 
256
    }
 
257
 
 
258
    foreach ( QSharedPointer<DatabaseCommand> c, cmdGroup )
 
259
        c->emitFinished();
 
260
 
 
261
    QMutexLocker lock( &m_mut );
 
262
    m_outstanding -= completed;
 
263
    if ( m_outstanding > 0 )
 
264
        QTimer::singleShot( 0, this, SLOT( doWork() ) );
 
265
}
 
266
 
 
267
 
 
268
// this should take a const command, need to check/make json stuff mutable for some objs tho maybe.
 
269
void
 
270
DatabaseWorker::logOp( DatabaseCommandLoggable* command )
 
271
{
 
272
    TomahawkSqlQuery oplogquery = Database::instance()->impl()->newquery();
 
273
    qDebug() << "INSERTING INTO OPTLOG:" << command->source()->id() << command->guid() << command->commandname();
 
274
    oplogquery.prepare( "INSERT INTO oplog(source, guid, command, singleton, compressed, json) "
 
275
                        "VALUES(?, ?, ?, ?, ?, ?)" );
 
276
 
 
277
    QVariantMap variant = QJson::QObjectHelper::qobject2qvariant( command );
 
278
    QByteArray ba = m_serializer.serialize( variant );
 
279
 
 
280
//     qDebug() << "OP JSON:" << ba.isNull() << ba << "from:" << variant; // debug
 
281
 
 
282
    bool compressed = false;
 
283
    if( ba.length() >= 512 )
 
284
    {
 
285
        // We need to compress this in this thread, since inserting into the log
 
286
        // has to happen as part of the same transaction as the dbcmd.
 
287
        // (we are in a worker thread for RW dbcmds anyway, so it's ok)
 
288
        //qDebug() << "Compressing DB OP JSON, uncompressed size:" << ba.length();
 
289
        ba = qCompress( ba, 9 );
 
290
        compressed = true;
 
291
        //qDebug() << "Compressed DB OP JSON size:" << ba.length();
 
292
    }
 
293
 
 
294
    if ( command->singletonCmd() )
 
295
    {
 
296
        tDebug() << "Singleton command, deleting previous oplog commands";
 
297
 
 
298
        TomahawkSqlQuery oplogdelquery = Database::instance()->impl()->newquery();
 
299
        oplogdelquery.prepare( QString( "DELETE FROM oplog WHERE source %1 AND singleton = 'true' AND command = ?" )
 
300
                                  .arg( command->source()->isLocal() ? "IS NULL" : QString( "= %1" ).arg( command->source()->id() ) ) );
 
301
 
 
302
        oplogdelquery.bindValue( 0, command->commandname() );
 
303
        oplogdelquery.exec();
 
304
    }
 
305
 
 
306
    tDebug() << "Saving to oplog:" << command->commandname()
 
307
             << "bytes:" << ba.length()
 
308
             << "guid:" << command->guid();
 
309
 
 
310
    oplogquery.bindValue( 0, command->source()->isLocal() ?
 
311
                          QVariant(QVariant::Int) : command->source()->id() );
 
312
    oplogquery.bindValue( 1, command->guid() );
 
313
    oplogquery.bindValue( 2, command->commandname() );
 
314
    oplogquery.bindValue( 3, command->singletonCmd() );
 
315
    oplogquery.bindValue( 4, compressed );
 
316
    oplogquery.bindValue( 5, ba );
 
317
    if( !oplogquery.exec() )
 
318
    {
 
319
        tLog() << "Error saving to oplog";
 
320
        throw "Failed to save to oplog";
 
321
    }
 
322
}