~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-02-28 14:09:50 UTC
  • mfrom: (2207 bootstrap)
  • mto: (2209.1.2 build)
  • mto: This revision was merged to the branch mainline in revision 2210.
  • Revision ID: olafvdspek@gmail.com-20110228140950-2nu0hyzhuww3wssx
Merge trunk

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