~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to drizzled/message/transaction_reader.cc

  • Committer: Brian Aker
  • Date: 2010-10-27 21:00:49 UTC
  • mto: This revision was merged to the branch mainline in revision 1886.
  • Revision ID: brian@tangent.org-20101027210049-zfpgx2cfbrh8maq9
A couple of fixes to documentation.

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) 2009 Sun Microsystems
 
5
 *
 
6
 *  Authors:
 
7
 *
 
8
 *    Jay Pipes <joinfu@sun.com>
 
9
 *
 
10
 *  This program is free software; you can redistribute it and/or modify
 
11
 *  it under the terms of the GNU General Public License as published by
 
12
 *  the Free Software Foundation; version 2 of the License.
 
13
 *
 
14
 *  This program is distributed in the hope that it will be useful,
 
15
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 
16
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
17
 *  GNU General Public License for more details.
 
18
 *
 
19
 *  You should have received a copy of the GNU General Public License
 
20
 *  along with this program; if not, write to the Free Software
 
21
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
22
 */
 
23
 
 
24
#include "config.h"
 
25
#include <drizzled/definitions.h>
 
26
#include <drizzled/gettext.h>
 
27
#include <drizzled/replication_services.h>
 
28
#include <drizzled/algorithm/crc32.h>
 
29
#include <sys/types.h>
 
30
#include <sys/stat.h>
 
31
#include <fcntl.h>
 
32
#include <limits.h>
 
33
#include <cstdio>
 
34
#include <cerrno>
 
35
#include <iostream>
 
36
#include <string>
 
37
#include <algorithm>
 
38
#include <vector>
 
39
#include <unistd.h>
 
40
#include <drizzled/message/transaction.pb.h>
 
41
#include <drizzled/message/statement_transform.h>
 
42
#include <drizzled/message/transaction_manager.h>
 
43
#include <drizzled/util/convert.h>
 
44
 
 
45
#include <google/protobuf/io/coded_stream.h>
 
46
#include <google/protobuf/io/zero_copy_stream_impl.h>
 
47
 
 
48
#include <boost/program_options.hpp>
 
49
 
 
50
using namespace std;
 
51
using namespace google;
 
52
using namespace drizzled;
 
53
 
 
54
namespace po= boost::program_options;
 
55
 
 
56
static const char *replace_with_spaces= "\n\r";
 
57
 
 
58
static void printStatement(const message::Statement &statement)
 
59
{
 
60
  vector<string> sql_strings;
 
61
 
 
62
  message::transformStatementToSql(statement,
 
63
                                   sql_strings,
 
64
                                   message::DRIZZLE,
 
65
                                   true /* already in transaction */);
 
66
 
 
67
  for (vector<string>::iterator sql_string_iter= sql_strings.begin();
 
68
       sql_string_iter != sql_strings.end();
 
69
       ++sql_string_iter)
 
70
  {
 
71
    string &sql= *sql_string_iter;
 
72
 
 
73
    /* 
 
74
     * Replace \n and \r with spaces so that SQL statements 
 
75
     * are always on a single line 
 
76
     */
 
77
    {
 
78
      string::size_type found= sql.find_first_of(replace_with_spaces);
 
79
      while (found != string::npos)
 
80
      {
 
81
        sql[found]= ' ';
 
82
        found= sql.find_first_of(replace_with_spaces, found);
 
83
      }
 
84
    }
 
85
 
 
86
    /*
 
87
     * Embedded NUL characters are a pain in the ass.
 
88
     */
 
89
    {
 
90
      string::size_type found= sql.find_first_of('\0');
 
91
      while (found != string::npos)
 
92
      {
 
93
        sql[found]= '\\';
 
94
        sql.insert(found + 1, 1, '0');
 
95
        found= sql.find_first_of('\0', found);
 
96
      }
 
97
    }
 
98
 
 
99
    cout << sql << ';' << endl;
 
100
  }
 
101
}
 
102
 
 
103
static bool isEndStatement(const message::Statement &statement)
 
104
{
 
105
  switch (statement.type())
 
106
  {
 
107
    case (message::Statement::INSERT):
 
108
    {
 
109
      const message::InsertData &data= statement.insert_data();
 
110
      if (not data.end_segment())
 
111
        return false;
 
112
      break;
 
113
    }
 
114
    case (message::Statement::UPDATE):
 
115
    {
 
116
      const message::UpdateData &data= statement.update_data();
 
117
      if (not data.end_segment())
 
118
        return false;
 
119
      break;
 
120
    }
 
121
    case (message::Statement::DELETE):
 
122
    {
 
123
      const message::DeleteData &data= statement.delete_data();
 
124
      if (not data.end_segment())
 
125
        return false;
 
126
      break;
 
127
    }
 
128
    default:
 
129
      return true;
 
130
  }
 
131
  return true;
 
132
}
 
133
 
 
134
static bool isEndTransaction(const message::Transaction &transaction)
 
135
{
 
136
  const message::TransactionContext trx= transaction.transaction_context();
 
137
 
 
138
  size_t num_statements= transaction.statement_size();
 
139
 
 
140
  /*
 
141
   * If any Statement is partial, then we can expect another Transaction
 
142
   * message.
 
143
   */
 
144
  for (size_t x= 0; x < num_statements; ++x)
 
145
  {
 
146
    const message::Statement &statement= transaction.statement(x);
 
147
 
 
148
    if (not isEndStatement(statement))
 
149
      return false;
 
150
  }
 
151
 
 
152
  return true;
 
153
}
 
154
 
 
155
static void printEvent(const message::Event &event)
 
156
{
 
157
  switch (event.type())
 
158
  {
 
159
    case message::Event::STARTUP:
 
160
    {
 
161
      cout << "-- EVENT: Server startup\n";
 
162
      break;
 
163
    }
 
164
    case message::Event::SHUTDOWN:
 
165
    {
 
166
      cout << "-- EVENT: Server shutdown\n";
 
167
      break;
 
168
    }
 
169
    default:
 
170
    {
 
171
      cout << "-- EVENT: Unknown event\n";
 
172
      break;
 
173
    }
 
174
  }
 
175
}
 
176
 
 
177
static void printTransaction(const message::Transaction &transaction,
 
178
                             bool ignore_events)
 
179
{
 
180
  static uint64_t last_trx_id= 0;
 
181
  bool should_commit= true;
 
182
  const message::TransactionContext trx= transaction.transaction_context();
 
183
 
 
184
  /*
 
185
   * First check to see if this is an event message.
 
186
   */
 
187
  if (transaction.has_event())
 
188
  {
 
189
    last_trx_id= trx.transaction_id();
 
190
    if (not ignore_events)
 
191
      printEvent(transaction.event());
 
192
    return;
 
193
  }
 
194
 
 
195
  size_t num_statements= transaction.statement_size();
 
196
  size_t x;
 
197
 
 
198
  /*
 
199
   * One way to determine when a new transaction begins is when the
 
200
   * transaction id changes (if all transactions have their GPB messages
 
201
   * grouped together, which this program will). We check that here.
 
202
   */
 
203
  if (trx.transaction_id() != last_trx_id)
 
204
    cout << "START TRANSACTION;" << endl;
 
205
 
 
206
  last_trx_id= trx.transaction_id();
 
207
 
 
208
  for (x= 0; x < num_statements; ++x)
 
209
  {
 
210
    const message::Statement &statement= transaction.statement(x);
 
211
 
 
212
    if (should_commit)
 
213
      should_commit= isEndStatement(statement);
 
214
 
 
215
    /* A ROLLBACK would be the only Statement within the Transaction
 
216
     * since all other Statements will have been deleted from the
 
217
     * Transaction message, so we should fall out of this loop immediately.
 
218
     * We don't want to issue an unnecessary COMMIT, so we change
 
219
     * should_commit to false here.
 
220
     */
 
221
    if (statement.type() == message::Statement::ROLLBACK)
 
222
      should_commit= false;
 
223
 
 
224
    printStatement(statement);
 
225
  }
 
226
 
 
227
  /*
 
228
   * If ALL Statements are end segments, we can commit this Transaction.
 
229
   * We can also check to see if the transaction_id changed, but this
 
230
   * wouldn't work for the last Transaction in the transaction log since
 
231
   * we don't have another Transaction to compare to. Checking for all
 
232
   * end segments (like we do above) covers this case.
 
233
   */
 
234
  if (should_commit)
 
235
    cout << "COMMIT;" << endl;
 
236
}
 
237
 
 
238
int main(int argc, char* argv[])
 
239
{
 
240
  GOOGLE_PROTOBUF_VERIFY_VERSION;
 
241
  int file;
 
242
 
 
243
  /*
 
244
   * Setup program options
 
245
   */
 
246
  po::options_description desc("Program options");
 
247
  desc.add_options()
 
248
    ("help", N_("Display help and exit"))
 
249
    ("checksum", N_("Perform checksum"))
 
250
    ("ignore-events", N_("Ignore event messages"))
 
251
    ("input-file", po::value< vector<string> >(), N_("Transaction log file"));
 
252
 
 
253
  /*
 
254
   * We allow one positional argument that will be transaction file name
 
255
   */
 
256
  po::positional_options_description pos;
 
257
  pos.add("input-file", 1);
 
258
 
 
259
  /*
 
260
   * Parse the program options
 
261
   */
 
262
  po::variables_map vm;
 
263
  po::store(po::command_line_parser(argc, argv).
 
264
            options(desc).positional(pos).run(), vm);
 
265
  po::notify(vm);
 
266
 
 
267
  /*
 
268
   * If the help option was given, or not input file was supplied,
 
269
   * print out usage information.
 
270
   */
 
271
  if (vm.count("help") || not vm.count("input-file"))
 
272
  {
 
273
    fprintf(stderr, _("Usage: %s [options] TRANSACTION_LOG \n"),
 
274
            argv[0]);
 
275
    fprintf(stderr, _("OPTIONS:\n"));
 
276
    fprintf(stderr, _("--help           :  Display help and exit\n"));
 
277
    fprintf(stderr, _("--checksum       :  Perform checksum\n"));
 
278
    fprintf(stderr, _("--ignore-events  :  Ignore event messages\n"));
 
279
    return -1;
 
280
  }
 
281
 
 
282
  bool do_checksum= vm.count("checksum") ? true : false;
 
283
  bool ignore_events= vm.count("ignore-events") ? true : false;
 
284
 
 
285
  string filename= vm["input-file"].as< vector<string> >()[0];
 
286
  file= open(filename.c_str(), O_RDONLY);
 
287
  if (file == -1)
 
288
  {
 
289
    fprintf(stderr, _("Cannot open file: %s\n"), filename.c_str());
 
290
    return -1;
 
291
  }
 
292
 
 
293
  message::Transaction transaction;
 
294
  message::TransactionManager trx_mgr;
 
295
 
 
296
  protobuf::io::ZeroCopyInputStream *raw_input= new protobuf::io::FileInputStream(file);
 
297
  protobuf::io::CodedInputStream *coded_input= new protobuf::io::CodedInputStream(raw_input);
 
298
 
 
299
  char *buffer= NULL;
 
300
  char *temp_buffer= NULL;
 
301
  uint32_t length= 0;
 
302
  uint32_t previous_length= 0;
 
303
  uint32_t checksum= 0;
 
304
  bool result= true;
 
305
  uint32_t message_type= 0;
 
306
 
 
307
  /* Read in the length of the command */
 
308
  while (result == true && 
 
309
         coded_input->ReadLittleEndian32(&message_type) == true &&
 
310
         coded_input->ReadLittleEndian32(&length) == true)
 
311
  {
 
312
    if (message_type != ReplicationServices::TRANSACTION)
 
313
    {
 
314
      fprintf(stderr, _("Found a non-transaction message in log.  Currently, not supported.\n"));
 
315
      exit(1);
 
316
    }
 
317
 
 
318
    if (length > INT_MAX)
 
319
    {
 
320
      fprintf(stderr, _("Attempted to read record bigger than INT_MAX\n"));
 
321
      exit(1);
 
322
    }
 
323
 
 
324
    if (buffer == NULL)
 
325
    {
 
326
      /* 
 
327
       * First time around...just malloc the length.  This block gets rid
 
328
       * of a GCC warning about uninitialized temp_buffer.
 
329
       */
 
330
      temp_buffer= (char *) malloc(static_cast<size_t>(length));
 
331
    }
 
332
    /* No need to allocate if we have a buffer big enough... */
 
333
    else if (length > previous_length)
 
334
    {
 
335
      temp_buffer= (char *) realloc(buffer, static_cast<size_t>(length));
 
336
    }
 
337
 
 
338
    if (temp_buffer == NULL)
 
339
    {
 
340
      fprintf(stderr, _("Memory allocation failure trying to allocate %" PRIu64 " bytes.\n"),
 
341
              static_cast<uint64_t>(length));
 
342
      break;
 
343
    }
 
344
    else
 
345
      buffer= temp_buffer;
 
346
 
 
347
    /* Read the Command */
 
348
    result= coded_input->ReadRaw(buffer, (int) length);
 
349
    if (result == false)
 
350
    {
 
351
      char errmsg[STRERROR_MAX];
 
352
      strerror_r(errno, errmsg, sizeof(errmsg));
 
353
      fprintf(stderr, _("Could not read transaction message.\n"));
 
354
      fprintf(stderr, _("GPB ERROR: %s.\n"), errmsg);
 
355
      string hexdump;
 
356
      hexdump.reserve(length * 4);
 
357
      bytesToHexdumpFormat(hexdump, reinterpret_cast<const unsigned char *>(buffer), length);
 
358
      fprintf(stderr, _("HEXDUMP:\n\n%s\n"), hexdump.c_str());
 
359
      break;
 
360
    }
 
361
 
 
362
    result= transaction.ParseFromArray(buffer, static_cast<int32_t>(length));
 
363
    if (result == false)
 
364
    {
 
365
      fprintf(stderr, _("Unable to parse command. Got error: %s.\n"), transaction.InitializationErrorString().c_str());
 
366
      if (buffer != NULL)
 
367
      {
 
368
        string hexdump;
 
369
        hexdump.reserve(length * 4);
 
370
        bytesToHexdumpFormat(hexdump, reinterpret_cast<const unsigned char *>(buffer), length);
 
371
        fprintf(stderr, _("HEXDUMP:\n\n%s\n"), hexdump.c_str());
 
372
      }
 
373
      break;
 
374
    }
 
375
 
 
376
    if (not isEndTransaction(transaction))
 
377
    {
 
378
      trx_mgr.store(transaction);
 
379
    }
 
380
    else
 
381
    {
 
382
      const message::TransactionContext trx= transaction.transaction_context();
 
383
      uint64_t transaction_id= trx.transaction_id();
 
384
 
 
385
      /*
 
386
       * If there are any previous Transaction messages for this transaction,
 
387
       * store this one, then output all of them together.
 
388
       */
 
389
      if (trx_mgr.contains(transaction_id))
 
390
      {
 
391
        trx_mgr.store(transaction);
 
392
 
 
393
        uint32_t size= trx_mgr.getTransactionBufferSize(transaction_id);
 
394
        uint32_t idx= 0;
 
395
 
 
396
        while (idx != size)
 
397
        {
 
398
          message::Transaction new_trx;
 
399
          trx_mgr.getTransactionMessage(new_trx, transaction_id, idx);
 
400
          printTransaction(new_trx, ignore_events);
 
401
          idx++;
 
402
        }
 
403
 
 
404
        /* No longer need this transaction */
 
405
        trx_mgr.remove(transaction_id);
 
406
      }
 
407
      else
 
408
      {
 
409
        printTransaction(transaction, ignore_events);
 
410
      }
 
411
    }
 
412
 
 
413
    /* Skip 4 byte checksum */
 
414
    coded_input->ReadLittleEndian32(&checksum);
 
415
 
 
416
    if (do_checksum)
 
417
    {
 
418
      if (checksum != drizzled::algorithm::crc32(buffer, static_cast<size_t>(length)))
 
419
      {
 
420
        fprintf(stderr, _("Checksum failed. Wanted %" PRIu32 " got %" PRIu32 "\n"), checksum, drizzled::algorithm::crc32(buffer, static_cast<size_t>(length)));
 
421
      }
 
422
    }
 
423
 
 
424
    previous_length= length;
 
425
  } /* end while */
 
426
 
 
427
  if (buffer)
 
428
    free(buffer);
 
429
 
 
430
  delete coded_input;
 
431
  delete raw_input;
 
432
 
 
433
  return (result == true ? 0 : 1);
 
434
}
 
435