~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to plugin/slave/queue_producer.cc

  • Committer: Olaf van der Spek
  • Date: 2011-03-23 10:31:37 UTC
  • mto: (2247.1.1 build)
  • mto: This revision was merged to the branch mainline in revision 2248.
  • Revision ID: olafvdspek@gmail.com-20110323103137-lwevis2tfchgu18u
Propogate return void

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_producer.h>
 
23
#include <drizzled/errmsg_print.h>
 
24
#include <drizzled/sql/result_set.h>
 
25
#include <drizzled/execute.h>
 
26
#include <drizzled/gettext.h>
 
27
#include <drizzled/message/transaction.pb.h>
 
28
#include <boost/lexical_cast.hpp>
 
29
#include <google/protobuf/text_format.h>
 
30
 
 
31
using namespace std;
 
32
using namespace drizzled;
 
33
 
 
34
namespace slave
 
35
{
 
36
 
 
37
QueueProducer::~QueueProducer()
 
38
{
 
39
  if (_is_connected)
 
40
    closeConnection();
 
41
}
 
42
 
 
43
bool QueueProducer::init()
 
44
{
 
45
  setIOState("", true);
 
46
  return reconnect(true);
 
47
}
 
48
 
 
49
bool QueueProducer::process()
 
50
{
 
51
  if (_saved_max_commit_id == 0)
 
52
  {
 
53
    if (not queryForMaxCommitId(&_saved_max_commit_id))
 
54
    {
 
55
      if (_last_return == DRIZZLE_RETURN_LOST_CONNECTION)
 
56
      {
 
57
        if (reconnect(false))
 
58
        {
 
59
          return true;    /* reconnect successful, try again */
 
60
        }
 
61
        else
 
62
        {
 
63
          _last_error_message= "Master offline";
 
64
          return false;   /* reconnect failed, shutdown the thread */
 
65
        }
 
66
      }
 
67
      else
 
68
      {
 
69
        return false;     /* unrecoverable error, shutdown the thread */
 
70
      }
 
71
    }
 
72
  }
 
73
 
 
74
  /* Keep getting events until caught up */
 
75
  enum drizzled::error_t err;
 
76
  while ((err= (queryForReplicationEvents(_saved_max_commit_id))) == EE_OK)
 
77
  {}
 
78
 
 
79
  if (err == ER_YES)  /* We encountered an error */
 
80
  {
 
81
    if (_last_return == DRIZZLE_RETURN_LOST_CONNECTION)
 
82
    {
 
83
      if (reconnect(false))
 
84
      {
 
85
        return true;    /* reconnect successful, try again */
 
86
      }
 
87
      else
 
88
      {
 
89
        _last_error_message= "Master offline";
 
90
        return false;   /* reconnect failed, shutdown the thread */
 
91
      }
 
92
    }
 
93
    else
 
94
    {
 
95
      return false;     /* unrecoverable error, shutdown the thread */
 
96
    }
 
97
  }
 
98
 
 
99
  return true;
 
100
}
 
101
 
 
102
void QueueProducer::shutdown()
 
103
{
 
104
  setIOState(_last_error_message, false);
 
105
  if (_is_connected)
 
106
    closeConnection();
 
107
}
 
108
 
 
109
bool QueueProducer::reconnect(bool initial_connection)
 
110
{
 
111
  if (not initial_connection)
 
112
  {
 
113
    errmsg_printf(error::ERROR, _("Lost connection to master. Reconnecting."));
 
114
  }
 
115
 
 
116
  _is_connected= false;
 
117
  _last_return= DRIZZLE_RETURN_OK;
 
118
  _last_error_message.clear();
 
119
  boost::posix_time::seconds duration(_seconds_between_reconnects);
 
120
 
 
121
  uint32_t attempts= 1;
 
122
 
 
123
  while (not openConnection())
 
124
  {
 
125
    if (attempts++ == _max_reconnects)
 
126
      break;
 
127
    boost::this_thread::sleep(duration);
 
128
  }
 
129
 
 
130
  return _is_connected;
 
131
}
 
132
 
 
133
bool QueueProducer::openConnection()
 
134
{
 
135
  if (drizzle_create(&_drizzle) == NULL)
 
136
  {
 
137
    _last_return= DRIZZLE_RETURN_INTERNAL_ERROR;
 
138
    _last_error_message= "Replication slave: ";
 
139
    _last_error_message.append(drizzle_error(&_drizzle));
 
140
    errmsg_printf(error::ERROR, _("%s"), _last_error_message.c_str());
 
141
    return false;
 
142
  }
 
143
  
 
144
  if (drizzle_con_create(&_drizzle, &_connection) == NULL)
 
145
  {
 
146
    _last_return= DRIZZLE_RETURN_INTERNAL_ERROR;
 
147
    _last_error_message= "Replication slave: ";
 
148
    _last_error_message.append(drizzle_error(&_drizzle));
 
149
    errmsg_printf(error::ERROR, _("%s"), _last_error_message.c_str());
 
150
    return false;
 
151
  }
 
152
  
 
153
  drizzle_con_set_tcp(&_connection, _master_host.c_str(), _master_port);
 
154
  drizzle_con_set_auth(&_connection, _master_user.c_str(), _master_pass.c_str());
 
155
 
 
156
  drizzle_return_t ret= drizzle_con_connect(&_connection);
 
157
 
 
158
  if (ret != DRIZZLE_RETURN_OK)
 
159
  {
 
160
    _last_return= ret;
 
161
    _last_error_message= "Replication slave: ";
 
162
    _last_error_message.append(drizzle_error(&_drizzle));
 
163
    errmsg_printf(error::ERROR, _("%s"), _last_error_message.c_str());
 
164
    return false;
 
165
  }
 
166
  
 
167
  _is_connected= true;
 
168
 
 
169
  return true;
 
170
}
 
171
 
 
172
bool QueueProducer::closeConnection()
 
173
{
 
174
  drizzle_return_t ret;
 
175
  drizzle_result_st result;
 
176
 
 
177
  _is_connected= false;
 
178
 
 
179
  if (drizzle_quit(&_connection, &result, &ret) == NULL)
 
180
  {
 
181
    _last_return= ret;
 
182
    drizzle_result_free(&result);
 
183
    return false;
 
184
  }
 
185
 
 
186
  drizzle_result_free(&result);
 
187
 
 
188
  return true;
 
189
}
 
190
 
 
191
bool QueueProducer::queryForMaxCommitId(uint64_t *max_commit_id)
 
192
{
 
193
  /*
 
194
   * This SQL will get the maximum commit_id value we have pulled over from
 
195
   * the master. We query two tables because either the queue will be empty,
 
196
   * in which case the last_applied_commit_id will be the value we want, or
 
197
   * we have yet to drain the queue,  we get the maximum value still in
 
198
   * the queue.
 
199
   */
 
200
  string sql("SELECT MAX(x.cid) FROM"
 
201
             " (SELECT MAX(`commit_order`) AS cid FROM `sys_replication`.`queue`"
 
202
             "  UNION ALL SELECT `last_applied_commit_id` AS cid"
 
203
             "  FROM `sys_replication`.`applier_state`) AS x");
 
204
 
 
205
  sql::ResultSet result_set(1);
 
206
  Execute execute(*(_session.get()), true);
 
207
  execute.run(sql, result_set);
 
208
  assert(result_set.getMetaData().getColumnCount() == 1);
 
209
 
 
210
  /* Really should only be 1 returned row */
 
211
  uint32_t found_rows= 0;
 
212
  while (result_set.next())
 
213
  {
 
214
    string value= result_set.getString(0);
 
215
 
 
216
    if ((value == "") || (found_rows == 1))
 
217
      break;
 
218
 
 
219
    assert(result_set.isNull(0) == false);
 
220
    *max_commit_id= boost::lexical_cast<uint64_t>(value);
 
221
    found_rows++;
 
222
  }
 
223
 
 
224
  if (found_rows == 0)
 
225
  {
 
226
    _last_error_message= "Could not determine last committed transaction.";
 
227
    return false;
 
228
  }
 
229
 
 
230
  return true;
 
231
}
 
232
 
 
233
bool QueueProducer::queryForTrxIdList(uint64_t max_commit_id,
 
234
                                      vector<uint64_t> &list)
 
235
{
 
236
  (void)list;
 
237
  string sql("SELECT `id` FROM `data_dictionary`.`sys_replication_log`"
 
238
             " WHERE `commit_id` > ");
 
239
  sql.append(boost::lexical_cast<string>(max_commit_id));
 
240
  sql.append(" ORDER BY `commit_id` LIMIT 25");
 
241
 
 
242
  drizzle_return_t ret;
 
243
  drizzle_result_st result;
 
244
  drizzle_query_str(&_connection, &result, sql.c_str(), &ret);
 
245
  
 
246
  if (ret != DRIZZLE_RETURN_OK)
 
247
  {
 
248
    _last_return= ret;
 
249
    _last_error_message= "Replication slave: ";
 
250
    _last_error_message.append(drizzle_error(&_drizzle));
 
251
    errmsg_printf(error::ERROR, _("%s"), _last_error_message.c_str());
 
252
    drizzle_result_free(&result);
 
253
    return false;
 
254
  }
 
255
 
 
256
  ret= drizzle_result_buffer(&result);
 
257
 
 
258
  if (ret != DRIZZLE_RETURN_OK)
 
259
  {
 
260
    _last_return= ret;
 
261
    _last_error_message= "Replication slave: ";
 
262
    _last_error_message.append(drizzle_error(&_drizzle));
 
263
    errmsg_printf(error::ERROR, _("%s"), _last_error_message.c_str());
 
264
    drizzle_result_free(&result);
 
265
    return false;
 
266
  }
 
267
 
 
268
  drizzle_row_t row;
 
269
 
 
270
  while ((row= drizzle_row_next(&result)) != NULL)
 
271
  {
 
272
    if (row[0])
 
273
    {
 
274
      list.push_back(boost::lexical_cast<uint32_t>(row[0]));
 
275
    }
 
276
    else
 
277
    {
 
278
      _last_return= ret;
 
279
      _last_error_message= "Replication slave: Unexpected NULL for trx id";
 
280
      errmsg_printf(error::ERROR, _("%s"), _last_error_message.c_str());
 
281
      drizzle_result_free(&result);
 
282
      return false;
 
283
    }
 
284
  }
 
285
 
 
286
  drizzle_result_free(&result);
 
287
  return true;
 
288
}
 
289
 
 
290
 
 
291
bool QueueProducer::queueInsert(const char *trx_id,
 
292
                                const char *seg_id,
 
293
                                const char *commit_id,
 
294
                                const char *msg,
 
295
                                const char *msg_length)
 
296
{
 
297
  message::Transaction message;
 
298
 
 
299
  message.ParseFromArray(msg, boost::lexical_cast<int>(msg_length));
 
300
 
 
301
  /*
 
302
   * The SQL to insert our results into the local queue.
 
303
   */
 
304
  string sql= "INSERT INTO `sys_replication`.`queue`"
 
305
              " (`trx_id`, `seg_id`, `commit_order`, `msg`) VALUES (";
 
306
  sql.append(trx_id);
 
307
  sql.append(", ", 2);
 
308
  sql.append(seg_id);
 
309
  sql.append(", ", 2);
 
310
  sql.append(commit_id);
 
311
  sql.append(", '", 3);
 
312
 
 
313
  /*
 
314
   * Ideally we would store the Transaction message in binary form, as it
 
315
   * it stored on the master and tranferred to the slave. However, we are
 
316
   * inserting using drizzle::Execute which doesn't really handle binary
 
317
   * data. Until that is changed, we store as plain text.
 
318
   */
 
319
  string message_text;
 
320
  google::protobuf::TextFormat::PrintToString(message, &message_text);  
 
321
 
 
322
  /*
 
323
   * Execution using drizzled::Execute requires some special escaping.
 
324
   */
 
325
  string::iterator it= message_text.begin();
 
326
  for (; it != message_text.end(); ++it)
 
327
  {
 
328
    if (*it == '\"')
 
329
    {
 
330
      it= message_text.insert(it, '\\');
 
331
      ++it;
 
332
    }
 
333
    else if (*it == '\'')
 
334
    {
 
335
      it= message_text.insert(it, '\\');
 
336
      ++it;
 
337
      it= message_text.insert(it, '\\');
 
338
      ++it;
 
339
    }
 
340
    else if (*it == '\\')
 
341
    {
 
342
      it= message_text.insert(it, '\\');
 
343
      ++it;
 
344
      it= message_text.insert(it, '\\');
 
345
      ++it;
 
346
      it= message_text.insert(it, '\\');
 
347
      ++it;
 
348
    }
 
349
    else if (*it == ';')
 
350
    {
 
351
      it= message_text.insert(it, '\\');
 
352
      ++it;  /* advance back to the semicolon */
 
353
    }
 
354
  }
 
355
 
 
356
  sql.append(message_text);
 
357
  sql.append("')", 2);
 
358
 
 
359
  vector<string> statements;
 
360
  statements.push_back(sql);
 
361
 
 
362
  if (not executeSQL(statements))
 
363
  {
 
364
    markInErrorState();
 
365
    return false;
 
366
  }
 
367
 
 
368
  uint64_t tmp_commit_id= boost::lexical_cast<uint64_t>(commit_id);
 
369
  if (tmp_commit_id > _saved_max_commit_id)
 
370
    _saved_max_commit_id= tmp_commit_id;
 
371
 
 
372
  return true;
 
373
}
 
374
 
 
375
 
 
376
enum drizzled::error_t QueueProducer::queryForReplicationEvents(uint64_t max_commit_id)
 
377
{
 
378
  vector<uint64_t> trx_id_list;
 
379
 
 
380
  if (not queryForTrxIdList(max_commit_id, trx_id_list))
 
381
    return ER_YES;
 
382
 
 
383
  if (trx_id_list.size() == 0)    /* nothing to get from the master */
 
384
  {
 
385
    return ER_NO;
 
386
  }
 
387
 
 
388
  /*
 
389
   * The SQL to pull everything we need from the master.
 
390
   */
 
391
  string sql= "SELECT `id`, `segid`, `commit_id`, `message`, `message_len` "
 
392
              " FROM `data_dictionary`.`sys_replication_log` WHERE `id` IN (";
 
393
 
 
394
  for (size_t x= 0; x < trx_id_list.size(); x++)
 
395
  {
 
396
    if (x > 0)
 
397
      sql.append(", ", 2);
 
398
    sql.append(boost::lexical_cast<string>(trx_id_list[x]));
 
399
  }
 
400
 
 
401
  sql.append(")", 1);
 
402
 
 
403
  drizzle_return_t ret;
 
404
  drizzle_result_st result;
 
405
  drizzle_query_str(&_connection, &result, sql.c_str(), &ret);
 
406
  
 
407
  if (ret != DRIZZLE_RETURN_OK)
 
408
  {
 
409
    _last_return= ret;
 
410
    _last_error_message= "Replication slave: ";
 
411
    _last_error_message.append(drizzle_error(&_drizzle));
 
412
    errmsg_printf(error::ERROR, _("%s"), _last_error_message.c_str());
 
413
    drizzle_result_free(&result);
 
414
    return ER_YES;
 
415
  }
 
416
 
 
417
  /* TODO: Investigate 1-row-at-a-time buffering */
 
418
 
 
419
  ret= drizzle_result_buffer(&result);
 
420
 
 
421
  if (ret != DRIZZLE_RETURN_OK)
 
422
  {
 
423
    _last_return= ret;
 
424
    _last_error_message= "Replication slave: ";
 
425
    _last_error_message.append(drizzle_error(&_drizzle));
 
426
    errmsg_printf(error::ERROR, _("%s"), _last_error_message.c_str());
 
427
    drizzle_result_free(&result);
 
428
    return ER_YES;
 
429
  }
 
430
 
 
431
  drizzle_row_t row;
 
432
 
 
433
  while ((row= drizzle_row_next(&result)) != NULL)
 
434
  {
 
435
    if (not queueInsert(row[0], row[1], row[2], row[3], row[4]))
 
436
    {
 
437
      errmsg_printf(error::ERROR,
 
438
                    _("Replication slave: Unable to insert into queue."));
 
439
      drizzle_result_free(&result);
 
440
      return ER_YES;
 
441
    }
 
442
  }
 
443
 
 
444
  drizzle_result_free(&result);
 
445
 
 
446
  return EE_OK;
 
447
}
 
448
 
 
449
 
 
450
void QueueProducer::setIOState(const string &err_msg, bool status)
 
451
{
 
452
  vector<string> statements;
 
453
  string sql;
 
454
  string msg(err_msg);
 
455
 
 
456
  if (not status)
 
457
  {
 
458
    sql= "UPDATE `sys_replication`.`io_state` SET `status` = 'STOPPED'";
 
459
  }
 
460
  else
 
461
  {
 
462
    sql= "UPDATE `sys_replication`.`io_state` SET `status` = 'RUNNING'";
 
463
  }
 
464
  
 
465
  sql.append(", `error_msg` = '", 17);
 
466
 
 
467
  /* Escape embedded quotes and statement terminators */
 
468
  string::iterator it;
 
469
  for (it= msg.begin(); it != msg.end(); ++it)
 
470
  {
 
471
    if (*it == '\'')
 
472
    {
 
473
      it= msg.insert(it, '\'');
 
474
      ++it;  /* advance back to the quote */
 
475
    }
 
476
    else if (*it == ';')
 
477
    {
 
478
      it= msg.insert(it, '\\');
 
479
      ++it;  /* advance back to the semicolon */
 
480
    }
 
481
  }
 
482
  
 
483
  sql.append(msg);
 
484
  sql.append("'", 1);
 
485
 
 
486
  statements.push_back(sql);
 
487
  executeSQL(statements);
 
488
}
 
489
 
 
490
} /* namespace slave */