~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/replication_services.cc

Reverted 1103

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
3
 *
4
 
 *  Copyright (C) 2008-2009 Sun Microsystems, Inc.
5
 
 *  Copyright (C) 2009-2010 Jay Pipes <jaypipes@gmail.com>
 
4
 *  Copyright (C) 2008-2009 Sun Microsystems
6
5
 *
7
6
 *  Authors:
8
7
 *
9
 
 *    Jay Pipes <jaypipes@gmail.com>
 
8
 *    Jay Pipes <joinfu@sun.com>
10
9
 *
11
10
 *  This program is free software; you can redistribute it and/or modify
12
11
 *  it under the terms of the GNU General Public License as published by
24
23
 
25
24
/**
26
25
 * @file Server-side utility which is responsible for managing the 
27
 
 * communication between the kernel and the replication plugins:
28
 
 *
29
 
 * - TransactionReplicator
30
 
 * - TransactionApplier
31
 
 * - Publisher
32
 
 * - Subscriber
33
 
 *
34
 
 * ReplicationServices is a bridge between replication modules and the kernel,
35
 
 * and its primary function is to  */
 
26
 * communication between the kernel, replicator plugins, and applier plugins.
 
27
 *
 
28
 * ReplicationServices is a bridge between modules and the kernel, and its
 
29
 * primary function is to take internal events (for instance the start of a 
 
30
 * transaction, the changing of a record, or the rollback of a transaction) 
 
31
 * and construct GPB Messages that are passed to the registered replicator and
 
32
 * applier plugins.
 
33
 *
 
34
 * The reason for this functionality is to encapsulate all communication
 
35
 * between the kernel and the replicator/applier plugins into GPB Messages.
 
36
 * Instead of the plugin having to understand the (often fluidly changing)
 
37
 * mechanics of the kernel, all the plugin needs to understand is the message
 
38
 * format, and GPB messages provide a nice, clear, and versioned format for 
 
39
 * these messages.
 
40
 *
 
41
 * @see /drizzled/message/replication.proto
 
42
 */
36
43
 
37
 
#include "config.h"
 
44
#include "drizzled/server_includes.h"
38
45
#include "drizzled/replication_services.h"
39
 
#include "drizzled/plugin/transaction_replicator.h"
40
 
#include "drizzled/plugin/transaction_applier.h"
41
 
#include "drizzled/message/transaction.pb.h"
 
46
#include "drizzled/plugin/replicator.h"
 
47
#include "drizzled/plugin/applier.h"
 
48
#include "drizzled/message/replication.pb.h"
 
49
#include "drizzled/message/table.pb.h"
42
50
#include "drizzled/gettext.h"
43
51
#include "drizzled/session.h"
44
 
#include "drizzled/error.h"
 
52
#include "drizzled/plugin_registry.h"
45
53
 
46
 
#include <string>
47
54
#include <vector>
48
 
#include <algorithm>
49
 
 
50
 
using namespace std;
 
55
 
 
56
using namespace drizzled;
 
57
 
 
58
ReplicationServices replication_services;
 
59
 
 
60
void add_replicator(plugin::Replicator *replicator)
 
61
{
 
62
  replication_services.attachReplicator(replicator);
 
63
}
 
64
 
 
65
void remove_replicator(plugin::Replicator *replicator)
 
66
{
 
67
  replication_services.detachReplicator(replicator);
 
68
}
 
69
 
 
70
void add_applier(plugin::Applier *applier)
 
71
{
 
72
  replication_services.attachApplier(applier);
 
73
}
 
74
 
 
75
void remove_applier(plugin::Applier *applier)
 
76
{
 
77
  replication_services.detachApplier(applier);
 
78
}
51
79
 
52
80
namespace drizzled
53
81
{
54
82
 
55
 
ReplicationServices::ReplicationServices() :
56
 
  is_active(false)
57
 
{
58
 
}
59
 
 
60
 
void ReplicationServices::normalizeReplicatorName(string &name)
61
 
{
62
 
  transform(name.begin(),
63
 
            name.end(),
64
 
            name.begin(),
65
 
            ::tolower);
66
 
  if (name.find("replicator") == string::npos)
67
 
    name.append("replicator", 10);
68
 
  {
69
 
    size_t found_underscore= name.find('_');
70
 
    while (found_underscore != string::npos)
71
 
    {
72
 
      name.erase(found_underscore, 1);
73
 
      found_underscore= name.find('_');
74
 
    }
75
 
  }
76
 
}
77
 
 
78
 
bool ReplicationServices::evaluateRegisteredPlugins()
79
 
{
80
 
  /* 
81
 
   * We loop through appliers that have registered with us
82
 
   * and attempts to pair the applier with its requested
83
 
   * replicator.  If an applier has requested a replicator
84
 
   * that has either not been built or has not registered
85
 
   * with the replication services, we print an error and
86
 
   * return false
87
 
   */
88
 
  if (appliers.empty())
89
 
    return true;
90
 
 
91
 
  if (replicators.empty() && not appliers.empty())
92
 
  {
93
 
    errmsg_printf(error::ERROR,
94
 
                  N_("You registered a TransactionApplier plugin but no "
95
 
                     "TransactionReplicator plugins were registered.\n"));
96
 
    return false;
97
 
  }
98
 
 
99
 
  for (Appliers::iterator appl_iter= appliers.begin();
100
 
       appl_iter != appliers.end();
101
 
       ++appl_iter)
102
 
  {
103
 
    plugin::TransactionApplier *applier= (*appl_iter).second;
104
 
    string requested_replicator_name= (*appl_iter).first;
105
 
    normalizeReplicatorName(requested_replicator_name);
106
 
 
107
 
    bool found= false;
108
 
    Replicators::iterator repl_iter;
109
 
    for (repl_iter= replicators.begin();
110
 
         repl_iter != replicators.end();
111
 
         ++repl_iter)
112
 
    {
113
 
      string replicator_name= (*repl_iter)->getName();
114
 
      normalizeReplicatorName(replicator_name);
115
 
 
116
 
      if (requested_replicator_name.compare(replicator_name) == 0)
117
 
      {
118
 
        found= true;
119
 
        break;
120
 
      }
121
 
    }
122
 
    if (not found)
123
 
    {
124
 
      errmsg_printf(error::ERROR,
125
 
                    N_("You registered a TransactionApplier plugin but no "
126
 
                       "TransactionReplicator plugins were registered that match the "
127
 
                       "requested replicator name of '%s'.\n"
128
 
                       "We have deactivated the TransactionApplier '%s'.\n"),
129
 
                       requested_replicator_name.c_str(),
130
 
                       applier->getName().c_str());
131
 
      applier->deactivate();
132
 
      return false;
133
 
    }
134
 
    else
135
 
    {
136
 
      replication_streams.push_back(make_pair(*repl_iter, applier));
137
 
    }
138
 
  }
139
 
  is_active= true;
140
 
  return true;
141
 
}
142
 
 
143
 
void ReplicationServices::attachReplicator(plugin::TransactionReplicator *in_replicator)
 
83
ReplicationServices::ReplicationServices()
 
84
{
 
85
  is_active= false;
 
86
}
 
87
 
 
88
void ReplicationServices::evaluateActivePlugins()
 
89
{
 
90
  /* 
 
91
   * We loop through replicators and appliers, evaluating
 
92
   * whether or not there is at least one active replicator
 
93
   * and one active applier.  If not, we set is_active
 
94
   * to false.
 
95
   */
 
96
  bool tmp_is_active= false;
 
97
 
 
98
  if (replicators.size() == 0 || appliers.size() == 0)
 
99
  {
 
100
    is_active= false;
 
101
    return;
 
102
  }
 
103
 
 
104
  /* 
 
105
   * Determine if any remaining replicators and if those
 
106
   * replicators are active...if not, set is_active
 
107
   * to false
 
108
   */
 
109
  std::vector<plugin::Replicator *>::iterator repl_iter= replicators.begin();
 
110
  while (repl_iter != replicators.end())
 
111
  {
 
112
    if ((*repl_iter)->isActive())
 
113
    {
 
114
      tmp_is_active= true;
 
115
      break;
 
116
    }
 
117
    ++repl_iter;
 
118
  }
 
119
  if (! tmp_is_active)
 
120
  {
 
121
    /* No active replicators. Set is_active to false and exit. */
 
122
    is_active= false;
 
123
    return;
 
124
  }
 
125
 
 
126
  /* 
 
127
   * OK, we know there's at least one active replicator.
 
128
   *
 
129
   * Now determine if any remaining replicators and if those
 
130
   * replicators are active...if not, set is_active
 
131
   * to false
 
132
   */
 
133
  std::vector<plugin::Applier *>::iterator appl_iter= appliers.begin();
 
134
  while (appl_iter != appliers.end())
 
135
  {
 
136
    if ((*appl_iter)->isActive())
 
137
    {
 
138
      is_active= true;
 
139
      return;
 
140
    }
 
141
    ++appl_iter;
 
142
  }
 
143
  /* If we get here, there are no active appliers */
 
144
  is_active= false;
 
145
}
 
146
 
 
147
void ReplicationServices::attachReplicator(plugin::Replicator *in_replicator)
144
148
{
145
149
  replicators.push_back(in_replicator);
 
150
  evaluateActivePlugins();
146
151
}
147
152
 
148
 
void ReplicationServices::detachReplicator(plugin::TransactionReplicator *in_replicator)
 
153
void ReplicationServices::detachReplicator(plugin::Replicator *in_replicator)
149
154
{
150
155
  replicators.erase(std::find(replicators.begin(), replicators.end(), in_replicator));
151
 
}
152
 
 
153
 
void ReplicationServices::attachApplier(plugin::TransactionApplier *in_applier, const string &requested_replicator_name)
154
 
{
155
 
  appliers.push_back(make_pair(requested_replicator_name, in_applier));
156
 
}
157
 
 
158
 
void ReplicationServices::detachApplier(plugin::TransactionApplier *)
159
 
{
 
156
  evaluateActivePlugins();
 
157
}
 
158
 
 
159
void ReplicationServices::attachApplier(plugin::Applier *in_applier)
 
160
{
 
161
  appliers.push_back(in_applier);
 
162
  evaluateActivePlugins();
 
163
}
 
164
 
 
165
void ReplicationServices::detachApplier(plugin::Applier *in_applier)
 
166
{
 
167
  appliers.erase(std::find(appliers.begin(), appliers.end(), in_applier));
 
168
  evaluateActivePlugins();
160
169
}
161
170
 
162
171
bool ReplicationServices::isActive() const
164
173
  return is_active;
165
174
}
166
175
 
167
 
plugin::ReplicationReturnCode ReplicationServices::pushTransactionMessage(Session &in_session,
168
 
                                                                          message::Transaction &to_push)
169
 
{
170
 
  plugin::ReplicationReturnCode result= plugin::SUCCESS;
171
 
 
172
 
  for (ReplicationStreams::iterator iter= replication_streams.begin();
173
 
       iter != replication_streams.end();
174
 
       ++iter)
175
 
  {
176
 
    plugin::TransactionReplicator *cur_repl= (*iter).first;
177
 
    plugin::TransactionApplier *cur_appl= (*iter).second;
178
 
 
179
 
    result= cur_repl->replicate(cur_appl, in_session, to_push);
180
 
 
181
 
    if (result == plugin::SUCCESS)
182
 
    {
183
 
      /* 
184
 
       * We update the timestamp for the last applied Transaction so that
 
176
void ReplicationServices::setCommandTransactionContext(message::Command *in_command
 
177
                                                     , Session *in_session) const
 
178
{
 
179
  message::TransactionContext *trx= in_command->mutable_transaction_context();
 
180
  trx->set_server_id(in_session->getServerId());
 
181
  trx->set_transaction_id(in_session->getTransactionId());
 
182
}
 
183
 
 
184
void ReplicationServices::startTransaction(Session *in_session)
 
185
{
 
186
  if (! is_active)
 
187
    return;
 
188
  
 
189
  message::Command command;
 
190
  command.set_type(message::Command::START_TRANSACTION);
 
191
  command.set_timestamp(in_session->getCurrentTimestamp());
 
192
 
 
193
  setCommandTransactionContext(&command, in_session);
 
194
  
 
195
  push(&command);
 
196
}
 
197
 
 
198
void ReplicationServices::commitTransaction(Session *in_session)
 
199
{
 
200
  if (! is_active)
 
201
    return;
 
202
  
 
203
  message::Command command;
 
204
  command.set_type(message::Command::COMMIT);
 
205
  command.set_timestamp(in_session->getCurrentTimestamp());
 
206
 
 
207
  setCommandTransactionContext(&command, in_session);
 
208
  
 
209
  push(&command);
 
210
}
 
211
 
 
212
void ReplicationServices::rollbackTransaction(Session *in_session)
 
213
{
 
214
  if (! is_active)
 
215
    return;
 
216
  
 
217
  message::Command command;
 
218
  command.set_type(message::Command::ROLLBACK);
 
219
  command.set_timestamp(in_session->getCurrentTimestamp());
 
220
 
 
221
  setCommandTransactionContext(&command, in_session);
 
222
  
 
223
  push(&command);
 
224
}
 
225
 
 
226
void ReplicationServices::insertRecord(Session *in_session, Table *in_table)
 
227
{
 
228
  if (! is_active)
 
229
    return;
 
230
 
 
231
  message::Command command;
 
232
  command.set_type(message::Command::INSERT);
 
233
  command.set_timestamp(in_session->getCurrentTimestamp());
 
234
 
 
235
  setCommandTransactionContext(&command, in_session);
 
236
 
 
237
  const char *schema_name= in_table->getShare()->db.str;
 
238
  const char *table_name= in_table->getShare()->table_name.str;
 
239
 
 
240
  command.set_schema(schema_name);
 
241
  command.set_table(table_name);
 
242
 
 
243
  /* 
 
244
   * Now we construct the specialized InsertRecord command inside
 
245
   * the message::Command container...
 
246
   */
 
247
  message::InsertRecord *change_record= command.mutable_insert_record();
 
248
 
 
249
  Field *current_field;
 
250
  Field **table_fields= in_table->field;
 
251
  String *string_value= new (in_session->mem_root) String(ReplicationServices::DEFAULT_RECORD_SIZE);
 
252
  string_value->set_charset(system_charset_info);
 
253
 
 
254
  message::Table::Field *current_proto_field;
 
255
 
 
256
  /* We will read all the table's fields... */
 
257
  in_table->setReadSet();
 
258
 
 
259
  while ((current_field= *table_fields++) != NULL) 
 
260
  {
 
261
    current_proto_field= change_record->add_insert_field();
 
262
    current_proto_field->set_name(std::string(current_field->field_name));
 
263
    current_proto_field->set_type(message::Table::Field::VARCHAR); /* @TODO real types! */
 
264
    string_value= current_field->val_str(string_value);
 
265
    change_record->add_insert_value(std::string(string_value->c_ptr()));
 
266
    string_value->free();
 
267
  }
 
268
  
 
269
  push(&command);
 
270
}
 
271
 
 
272
void ReplicationServices::updateRecord(Session *in_session,
 
273
                                       Table *in_table, 
 
274
                                       const unsigned char *old_record, 
 
275
                                       const unsigned char *new_record)
 
276
{
 
277
  if (! is_active)
 
278
    return;
 
279
  
 
280
  message::Command command;
 
281
  command.set_type(message::Command::UPDATE);
 
282
  command.set_timestamp(in_session->getCurrentTimestamp());
 
283
 
 
284
  setCommandTransactionContext(&command, in_session);
 
285
 
 
286
  const char *schema_name= in_table->getShare()->db.str;
 
287
  const char *table_name= in_table->getShare()->table_name.str;
 
288
 
 
289
  command.set_schema(schema_name);
 
290
  command.set_table(table_name);
 
291
 
 
292
  /* 
 
293
   * Now we construct the specialized UpdateRecord command inside
 
294
   * the message::Command container...
 
295
   */
 
296
  message::UpdateRecord *change_record= command.mutable_update_record();
 
297
 
 
298
  Field *current_field;
 
299
  Field **table_fields= in_table->field;
 
300
  String *string_value= new (in_session->mem_root) String(ReplicationServices::DEFAULT_RECORD_SIZE);
 
301
  string_value->set_charset(system_charset_info);
 
302
 
 
303
  message::Table::Field *current_proto_field;
 
304
 
 
305
  while ((current_field= *table_fields++) != NULL) 
 
306
  {
 
307
    /*
 
308
     * The below really should be moved into the Field API and Record API.  But for now
 
309
     * we do this crazy pointer fiddling to figure out if the current field
 
310
     * has been updated in the supplied record raw byte pointers.
 
311
     */
 
312
    const unsigned char *old_ptr= (const unsigned char *) old_record + (ptrdiff_t) (current_field->ptr - in_table->record[0]); 
 
313
    const unsigned char *new_ptr= (const unsigned char *) new_record + (ptrdiff_t) (current_field->ptr - in_table->record[0]); 
 
314
 
 
315
    uint32_t field_length= current_field->pack_length(); /** @TODO This isn't always correct...check varchar diffs. */
 
316
 
 
317
    if (memcmp(old_ptr, new_ptr, field_length) != 0)
 
318
    {
 
319
      /* Field is changed from old to new */
 
320
      current_proto_field= change_record->add_update_field();
 
321
      current_proto_field->set_name(std::string(current_field->field_name));
 
322
      current_proto_field->set_type(message::Table::Field::VARCHAR); /* @TODO real types! */
 
323
 
 
324
      /* Store the original "read bit" for this field */
 
325
      bool is_read_set= current_field->isReadSet();
 
326
 
 
327
      /* We need to mark that we will "read" this field... */
 
328
      in_table->setReadSet(current_field->field_index);
 
329
 
 
330
      /* Read the string value of this field's contents */
 
331
      string_value= current_field->val_str(string_value);
 
332
 
 
333
      /* 
 
334
       * Reset the read bit after reading field to its original state.  This 
 
335
       * prevents the field from being included in the WHERE clause
 
336
       */
 
337
      current_field->setReadSet(is_read_set);
 
338
 
 
339
      change_record->add_after_value(std::string(string_value->c_ptr()));
 
340
      string_value->free();
 
341
    }
 
342
 
 
343
    /* 
 
344
     * Add the WHERE clause values now...the fields which return true
 
345
     * for isReadSet() are in the WHERE clause.  For tables with no
 
346
     * primary or unique key, all fields will be returned.
 
347
     */
 
348
    if (current_field->isReadSet())
 
349
    {
 
350
      current_proto_field= change_record->add_where_field();
 
351
      current_proto_field->set_name(std::string(current_field->field_name));
 
352
      current_proto_field->set_type(message::Table::Field::VARCHAR); /* @TODO real types! */
 
353
      string_value= current_field->val_str(string_value);
 
354
      change_record->add_where_value(std::string(string_value->c_ptr()));
 
355
      string_value->free();
 
356
    }
 
357
  }
 
358
 
 
359
  push(&command);
 
360
}
 
361
 
 
362
void ReplicationServices::deleteRecord(Session *in_session, Table *in_table)
 
363
{
 
364
  if (! is_active)
 
365
    return;
 
366
  
 
367
  message::Command command;
 
368
  command.set_type(message::Command::DELETE);
 
369
  command.set_timestamp(in_session->getCurrentTimestamp());
 
370
 
 
371
  setCommandTransactionContext(&command, in_session);
 
372
 
 
373
  const char *schema_name= in_table->getShare()->db.str;
 
374
  const char *table_name= in_table->getShare()->table_name.str;
 
375
 
 
376
  command.set_schema(schema_name);
 
377
  command.set_table(table_name);
 
378
 
 
379
  /* 
 
380
   * Now we construct the specialized DeleteRecord command inside
 
381
   * the message::Command container...
 
382
   */
 
383
  message::DeleteRecord *change_record= command.mutable_delete_record();
 
384
 
 
385
  Field *current_field;
 
386
  Field **table_fields= in_table->field;
 
387
  String *string_value= new (in_session->mem_root) String(ReplicationServices::DEFAULT_RECORD_SIZE);
 
388
  string_value->set_charset(system_charset_info);
 
389
 
 
390
  message::Table::Field *current_proto_field;
 
391
 
 
392
  while ((current_field= *table_fields++) != NULL)
 
393
  {
 
394
    /*
 
395
     * Add the WHERE clause values now...the fields which return true
 
396
     * for isReadSet() are in the WHERE clause.  For tables with no
 
397
     * primary or unique key, all fields will be returned.
 
398
     */
 
399
    if (current_field->isReadSet())
 
400
    {
 
401
      current_proto_field= change_record->add_where_field();
 
402
      current_proto_field->set_name(std::string(current_field->field_name));
 
403
      current_proto_field->set_type(message::Table::Field::VARCHAR); /* @TODO real types! */
 
404
      string_value= current_field->val_str(string_value);
 
405
      change_record->add_where_value(std::string(string_value->c_ptr()));
 
406
      string_value->free();
 
407
    }
 
408
  }
 
409
 
 
410
  push(&command);
 
411
}
 
412
 
 
413
void ReplicationServices::rawStatement(Session *in_session, const char *in_query, size_t in_query_len)
 
414
{
 
415
  if (! is_active)
 
416
    return;
 
417
  
 
418
  message::Command command;
 
419
  command.set_type(message::Command::RAW_SQL);
 
420
  command.set_timestamp(in_session->getCurrentTimestamp());
 
421
 
 
422
  setCommandTransactionContext(&command, in_session);
 
423
 
 
424
  std::string query(in_query, in_query_len);
 
425
  command.set_sql(query);
 
426
 
 
427
  push(&command);
 
428
}
 
429
 
 
430
void ReplicationServices::push(message::Command *to_push)
 
431
{
 
432
  std::vector<plugin::Replicator *>::iterator repl_iter= replicators.begin();
 
433
  std::vector<plugin::Applier *>::iterator appl_start_iter, appl_iter;
 
434
  appl_start_iter= appliers.begin();
 
435
 
 
436
  plugin::Replicator *cur_repl;
 
437
  plugin::Applier *cur_appl;
 
438
 
 
439
  while (repl_iter != replicators.end())
 
440
  {
 
441
    cur_repl= *repl_iter;
 
442
    if (! cur_repl->isActive())
 
443
    {
 
444
      ++repl_iter;
 
445
      continue;
 
446
    }
 
447
    
 
448
    appl_iter= appl_start_iter;
 
449
    while (appl_iter != appliers.end())
 
450
    {
 
451
      cur_appl= *appl_iter;
 
452
 
 
453
      if (! cur_appl->isActive())
 
454
      {
 
455
        ++appl_iter;
 
456
        continue;
 
457
      }
 
458
 
 
459
      cur_repl->replicate(cur_appl, to_push);
 
460
      
 
461
      /* 
 
462
       * We update the timestamp for the last applied Command so that
185
463
       * publisher plugins can ask the replication services when the
186
 
       * last known applied Transaction was using the getLastAppliedTimestamp()
 
464
       * last known applied Command was using the getLastAppliedTimestamp()
187
465
       * method.
188
466
       */
189
 
      last_applied_timestamp.fetch_and_store(to_push.transaction_context().end_timestamp());
 
467
      last_applied_timestamp.fetch_and_store(to_push->timestamp());
 
468
      ++appl_iter;
190
469
    }
191
 
    else
192
 
      return result;
 
470
    ++repl_iter;
193
471
  }
194
 
  return result;
195
 
}
196
 
 
197
 
ReplicationServices::ReplicationStreams &ReplicationServices::getReplicationStreams()
198
 
{
199
 
  return replication_streams;
200
 
}
201
 
 
202
 
} /* namespace drizzled */
 
472
}
 
473
 
 
474
} /* end namespace drizzled */