~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to plugin/slave/queue_consumer.cc

  • Committer: Monty Taylor
  • Date: 2011-03-10 18:09:05 UTC
  • mfrom: (2225.2.2 refactor)
  • mto: This revision was merged to the branch mainline in revision 2228.
  • Revision ID: mordred@inaugust.com-20110310180905-ttx05t7q7ff6nl7c
Merge Olad: Refactoring

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* - mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 
3
 *
 
4
 *  Copyright (C) 2011 David Shrewsbury
 
5
 *
 
6
 *  This program 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 2 of the License, or
 
9
 *  (at your option) any later version.
 
10
 *
 
11
 *  This program 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 this program; if not, write to the Free Software
 
18
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
19
 */
 
20
 
 
21
#include <config.h>
 
22
#include <plugin/slave/queue_consumer.h>
 
23
#include <drizzled/message/transaction.pb.h>
 
24
#include <drizzled/message/statement_transform.h>
 
25
#include <drizzled/sql/result_set.h>
 
26
#include <drizzled/execute.h>
 
27
#include <string>
 
28
#include <vector>
 
29
#include <boost/thread.hpp>
 
30
#include <boost/lexical_cast.hpp>
 
31
#include <google/protobuf/text_format.h>
 
32
 
 
33
using namespace std;
 
34
using namespace drizzled;
 
35
 
 
36
namespace slave
 
37
{
 
38
 
 
39
bool QueueConsumer::init()
 
40
{
 
41
  setApplierState("", true);
 
42
  return true;
 
43
}
 
44
 
 
45
 
 
46
void QueueConsumer::shutdown()
 
47
{
 
48
  setApplierState(getErrorMessage(), false);
 
49
}
 
50
 
 
51
 
 
52
bool QueueConsumer::process()
 
53
{
 
54
  TrxIdList completedTransactionIds;
 
55
 
 
56
  getListOfCompletedTransactions(completedTransactionIds);
 
57
 
 
58
  for (size_t x= 0; x < completedTransactionIds.size(); x++)
 
59
  {
 
60
    string commit_id;
 
61
    uint64_t trx_id= completedTransactionIds[x];
 
62
 
 
63
    vector<string> aggregate_sql;  /* final SQL to execute */
 
64
    vector<string> segmented_sql;  /* carryover from segmented statements */
 
65
 
 
66
    message::Transaction transaction;
 
67
    uint32_t segment_id= 1;
 
68
 
 
69
    while (getMessage(transaction, commit_id, trx_id, segment_id++))
 
70
    {
 
71
      convertToSQL(transaction, aggregate_sql, segmented_sql);
 
72
      transaction.Clear();
 
73
    }
 
74
 
 
75
    /*
 
76
     * The last message in a transaction should always have a commit_id
 
77
     * value larger than 0, though other messages of the same transaction
 
78
     * will have commit_id = 0.
 
79
     */
 
80
    assert((not commit_id.empty()) && (commit_id != "0"));
 
81
    assert(segmented_sql.empty());
 
82
 
 
83
    if (not aggregate_sql.empty())
 
84
    {
 
85
      /*
 
86
       * Execution using drizzled::Execute requires some special escaping.
 
87
       */
 
88
      vector<string>::iterator agg_iter;
 
89
      for (agg_iter= aggregate_sql.begin(); agg_iter != aggregate_sql.end(); ++agg_iter)
 
90
      {
 
91
        string &sql= *agg_iter;
 
92
        string::iterator si= sql.begin();
 
93
        for (; si != sql.end(); ++si)
 
94
        {
 
95
          if (*si == '\"')
 
96
          {
 
97
            si= sql.insert(si, '\\');
 
98
            ++si;
 
99
          }
 
100
          else if (*si == '\\')
 
101
          {
 
102
            si= sql.insert(si, '\\');
 
103
            ++si;
 
104
            si= sql.insert(si, '\\');
 
105
            ++si;
 
106
            si= sql.insert(si, '\\');
 
107
            ++si;
 
108
          }
 
109
          else if (*si == ';')
 
110
          {
 
111
            si= sql.insert(si, '\\');
 
112
            ++si;  /* advance back to the semicolon */
 
113
          }
 
114
        }
 
115
      }
 
116
    }
 
117
 
 
118
    if (not executeSQLWithCommitId(aggregate_sql, commit_id))
 
119
    {
 
120
      return false;
 
121
    }
 
122
 
 
123
    if (not deleteFromQueue(trx_id))
 
124
    {
 
125
      return false;
 
126
    }
 
127
  }
 
128
 
 
129
  return true;
 
130
}
 
131
 
 
132
 
 
133
bool QueueConsumer::getMessage(message::Transaction &transaction,
 
134
                              string &commit_id,
 
135
                              uint64_t trx_id,
 
136
                              uint32_t segment_id)
 
137
{
 
138
  string sql("SELECT `msg`, `commit_order` FROM `sys_replication`.`queue`"
 
139
             " WHERE `trx_id` = ");
 
140
  sql.append(boost::lexical_cast<string>(trx_id));
 
141
  sql.append(" AND `seg_id` = ", 16);
 
142
  sql.append(boost::lexical_cast<string>(segment_id));
 
143
 
 
144
  sql::ResultSet result_set(2);
 
145
  Execute execute(*(_session.get()), true);
 
146
  
 
147
  execute.run(sql, result_set);
 
148
  
 
149
  assert(result_set.getMetaData().getColumnCount() == 2);
 
150
 
 
151
  /* Really should only be 1 returned row */
 
152
  uint32_t found_rows= 0;
 
153
  while (result_set.next())
 
154
  {
 
155
    string msg= result_set.getString(0);
 
156
    string com_id= result_set.getString(1);
 
157
 
 
158
    if ((msg == "") || (found_rows == 1))
 
159
      break;
 
160
 
 
161
    /* Neither column should be NULL */
 
162
    assert(result_set.isNull(0) == false);
 
163
    assert(result_set.isNull(1) == false);
 
164
 
 
165
    google::protobuf::TextFormat::ParseFromString(msg, &transaction);
 
166
 
 
167
    commit_id= com_id;
 
168
    found_rows++;
 
169
  }
 
170
 
 
171
  if (found_rows == 0)
 
172
    return false;
 
173
  
 
174
  return true;
 
175
}
 
176
 
 
177
bool QueueConsumer::getListOfCompletedTransactions(TrxIdList &list)
 
178
{
 
179
  Execute execute(*(_session.get()), true);
 
180
  
 
181
  string sql("SELECT `trx_id` FROM `sys_replication`.`queue`"
 
182
             " WHERE `commit_order` IS NOT NULL ORDER BY `commit_order` ASC");
 
183
  
 
184
  /* ResultSet size must match column count */
 
185
  sql::ResultSet result_set(1);
 
186
 
 
187
  execute.run(sql, result_set);
 
188
 
 
189
  assert(result_set.getMetaData().getColumnCount() == 1);
 
190
 
 
191
  while (result_set.next())
 
192
  {
 
193
    assert(result_set.isNull(0) == false);
 
194
    string value= result_set.getString(0);
 
195
    
 
196
    /* empty string returned when no more results */
 
197
    if (value != "")
 
198
    {
 
199
      list.push_back(boost::lexical_cast<uint64_t>(result_set.getString(0)));
 
200
    }
 
201
  }
 
202
  
 
203
  return true;
 
204
}
 
205
 
 
206
 
 
207
bool QueueConsumer::convertToSQL(const message::Transaction &transaction,
 
208
                                vector<string> &aggregate_sql,
 
209
                                vector<string> &segmented_sql)
 
210
{
 
211
  if (transaction.has_event())
 
212
    return true;
 
213
 
 
214
  size_t num_statements= transaction.statement_size();
 
215
 
 
216
  /*
 
217
   * Loop through all Statement messages within this Transaction and
 
218
   * convert each to equivalent SQL statements. Complete Statements will
 
219
   * be appended to aggregate_sql, while segmented Statements will remain
 
220
   * in segmented_sql to be appended to until completed, or rolled back.
 
221
   */
 
222
 
 
223
  for (size_t idx= 0; idx < num_statements; idx++)
 
224
  {
 
225
    const message::Statement &statement= transaction.statement(idx);
 
226
    
 
227
    /* We won't bother with executing a rolled back transaction */
 
228
    if (statement.type() == message::Statement::ROLLBACK)
 
229
    {
 
230
      assert(idx == (num_statements - 1));  /* should be the final Statement */
 
231
      aggregate_sql.clear();
 
232
      segmented_sql.clear();
 
233
      break;
 
234
    }
 
235
 
 
236
    switch (statement.type())
 
237
    {
 
238
      /* DDL cannot be in a transaction, so precede with a COMMIT */
 
239
      case message::Statement::TRUNCATE_TABLE:
 
240
      case message::Statement::CREATE_SCHEMA:
 
241
      case message::Statement::ALTER_SCHEMA:
 
242
      case message::Statement::DROP_SCHEMA:
 
243
      case message::Statement::CREATE_TABLE:
 
244
      case message::Statement::ALTER_TABLE:
 
245
      case message::Statement::DROP_TABLE:
 
246
      case message::Statement::RAW_SQL:  /* currently ALTER TABLE or RENAME */
 
247
      {
 
248
        segmented_sql.push_back("COMMIT");
 
249
        break;
 
250
      }
 
251
 
 
252
      /* Cancel any ongoing statement */
 
253
      case message::Statement::ROLLBACK_STATEMENT:
 
254
      {
 
255
        segmented_sql.clear();
 
256
        continue;
 
257
      }
 
258
      
 
259
      default:
 
260
      {
 
261
        break;
 
262
      }
 
263
    }
 
264
 
 
265
    if (message::transformStatementToSql(statement, segmented_sql,
 
266
                                         message::DRIZZLE, true))
 
267
    {
 
268
      return false;
 
269
    }
 
270
 
 
271
    if (isEndStatement(statement))
 
272
    {
 
273
      aggregate_sql.insert(aggregate_sql.end(),
 
274
                           segmented_sql.begin(),
 
275
                           segmented_sql.end());
 
276
      segmented_sql.clear();
 
277
    }
 
278
  }
 
279
 
 
280
  return true;
 
281
}
 
282
 
 
283
 
 
284
bool QueueConsumer::isEndStatement(const message::Statement &statement)
 
285
{
 
286
  switch (statement.type())
 
287
  {
 
288
    case (message::Statement::INSERT):
 
289
    {
 
290
      const message::InsertData &data= statement.insert_data();
 
291
      if (not data.end_segment())
 
292
        return false;
 
293
      break;
 
294
    }
 
295
    case (message::Statement::UPDATE):
 
296
    {
 
297
      const message::UpdateData &data= statement.update_data();
 
298
      if (not data.end_segment())
 
299
        return false;
 
300
      break;
 
301
    }
 
302
    case (message::Statement::DELETE):
 
303
    {
 
304
      const message::DeleteData &data= statement.delete_data();
 
305
      if (not data.end_segment())
 
306
        return false;
 
307
      break;
 
308
    }
 
309
    default:
 
310
      return true;
 
311
  }
 
312
  return true;
 
313
}
 
314
 
 
315
 
 
316
void QueueConsumer::setApplierState(const string &err_msg, bool status)
 
317
{
 
318
  vector<string> statements;
 
319
  string sql;
 
320
  string msg(err_msg);
 
321
 
 
322
  if (not status)
 
323
  {
 
324
    sql= "UPDATE `sys_replication`.`applier_state` SET `status` = 'STOPPED'";
 
325
  }
 
326
  else
 
327
  {
 
328
    sql= "UPDATE `sys_replication`.`applier_state` SET `status` = 'RUNNING'";
 
329
  }
 
330
  
 
331
  sql.append(", `error_msg` = '", 17);
 
332
 
 
333
  /* Escape embedded quotes and statement terminators */
 
334
  string::iterator it;
 
335
  for (it= msg.begin(); it != msg.end(); ++it)
 
336
  {
 
337
    if (*it == '\'')
 
338
    {
 
339
      it= msg.insert(it, '\'');
 
340
      ++it;  /* advance back to the quote */
 
341
    }
 
342
    else if (*it == ';')
 
343
    {
 
344
      it= msg.insert(it, '\\');
 
345
      ++it;  /* advance back to the semicolon */
 
346
    }
 
347
  }
 
348
  
 
349
  sql.append(msg);
 
350
  sql.append("'", 1);
 
351
 
 
352
  statements.push_back(sql);
 
353
  executeSQL(statements);
 
354
}
 
355
 
 
356
 
 
357
bool QueueConsumer::executeSQLWithCommitId(vector<string> &sql,
 
358
                                           const string &commit_id)
 
359
{
 
360
  string tmp("UPDATE `sys_replication`.`applier_state`"
 
361
             " SET `last_applied_commit_id` = ");
 
362
  tmp.append(commit_id);
 
363
  sql.push_back(tmp);
 
364
  
 
365
  return executeSQL(sql);
 
366
}
 
367
 
 
368
 
 
369
bool QueueConsumer::deleteFromQueue(uint64_t trx_id)
 
370
{
 
371
  string sql("DELETE FROM `sys_replication`.`queue` WHERE `trx_id` = ");
 
372
  sql.append(boost::lexical_cast<std::string>(trx_id));
 
373
 
 
374
  vector<string> sql_vect;
 
375
  sql_vect.push_back(sql);
 
376
 
 
377
  return executeSQL(sql_vect);
 
378
}
 
379
 
 
380
} /* namespace slave */