CommandInterpreter.cpp 61.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (C) 2003 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

17 18 19
#include <ndb_global.h>
#include <my_sys.h>

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
//#define HAVE_GLOBAL_REPLICATION

#include <Vector.hpp>
#ifdef  HAVE_GLOBAL_REPLICATION
#include "../rep/repapi/repapi.h"
#endif

#include <mgmapi.h>

class MgmtSrvr;

/** 
 *  @class CommandInterpreter
 *  @brief Reads command line in management client
 *
 *  This class has one public method which reads a command line 
 *  from a stream. It then interpret that commmand line and calls a suitable 
 *  method in the MgmtSrvr class which executes the command.
 *
 *  For command syntax, see the HELP command.
 */ 
class CommandInterpreter {
public:
  /**
   *   Constructor
   *   @param mgmtSrvr: Management server to use when executing commands
   */
47
  CommandInterpreter(const char *, int verbose);
48 49 50 51 52 53 54 55 56
  ~CommandInterpreter();
  
  /**
   *   Reads one line from the stream, parse the line to find 
   *   a command and then calls a suitable method which executes 
   *   the command.
   *
   *   @return true until quit/bye/exit has been typed
   */
57
  int execute(const char *_line, int _try_reconnect=-1, int *error= 0);
58 59 60

private:
  void printError();
61
  int execute_impl(const char *_line);
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

  /**
   *   Analyse the command line, after the first token.
   *
   *   @param  processId:           DB process id to send command to or -1 if
   *                                command will be sent to all DB processes.
   *   @param  allAfterFirstToken:  What the client gave after the 
   *                                first token on the command line
   */
  void analyseAfterFirstToken(int processId, char* allAfterFirstTokenCstr);

  /**
   *   Parse the block specification part of the LOG* commands,
   *   things after LOG*: [BLOCK = {ALL|<blockName>+}]
   *
   *   @param  allAfterLog: What the client gave after the second token 
   *                        (LOG*) on the command line
   *   @param  blocks, OUT: ALL or name of all the blocks
   *   @return: true if correct syntax, otherwise false
   */
  bool parseBlockSpecification(const char* allAfterLog, 
			       Vector<const char*>& blocks);
  
  /**
   *   A bunch of execute functions: Executes one of the commands
   *
   *   @param  processId:   DB process id to send command to
   *   @param  parameters:  What the client gave after the command name 
   *                        on the command line.
   *   For example if complete input from user is: "1 LOGLEVEL 22" then the
   *   parameters argument is the string with everything after LOGLEVEL, in
   *   this case "22". Each function is responsible to check the parameters
   *   argument.
   */
  void executeHelp(char* parameters);
  void executeShow(char* parameters);
98
  void executeConnect(char* parameters);
99
  void executePurge(char* parameters);
100
  int  executeShutdown(char* parameters);
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  void executeRun(char* parameters);
  void executeInfo(char* parameters);
  void executeClusterLog(char* parameters);

public:
  void executeStop(int processId, const char* parameters, bool all);
  void executeEnterSingleUser(char* parameters);
  void executeExitSingleUser(char* parameters);
  void executeStart(int processId, const char* parameters, bool all);
  void executeRestart(int processId, const char* parameters, bool all);
  void executeLogLevel(int processId, const char* parameters, bool all);
  void executeError(int processId, const char* parameters, bool all);
  void executeTrace(int processId, const char* parameters, bool all);
  void executeLog(int processId, const char* parameters, bool all);
  void executeLogIn(int processId, const char* parameters, bool all);
  void executeLogOut(int processId, const char* parameters, bool all);
  void executeLogOff(int processId, const char* parameters, bool all);
  void executeTestOn(int processId, const char* parameters, bool all);
  void executeTestOff(int processId, const char* parameters, bool all);
  void executeSet(int processId, const char* parameters, bool all);
  void executeGetStat(int processId, const char* parameters, bool all);
  void executeStatus(int processId, const char* parameters, bool all);
  void executeEventReporting(int processId, const char* parameters, bool all);
  void executeDumpState(int processId, const char* parameters, bool all);
125
  int executeStartBackup(char * parameters);
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
  void executeAbortBackup(char * parameters);

  void executeRep(char* parameters);

  void executeCpc(char * parameters);

public:
  bool connect();
  bool disconnect();

  /**
   * A execute function definition
   */
public:
  typedef void (CommandInterpreter::* ExecuteFunction)(int processId, 
						       const char * param, 
						       bool all);
  
  struct CommandFunctionPair {
    const char * command;
    ExecuteFunction executeFunction;
  };
private:
  /**
   * 
   */
  void executeForAll(const char * cmd, 
		     ExecuteFunction fun,
		     const char * param);

  NdbMgmHandle m_mgmsrv;
  bool connected;
158
  int m_verbose;
159
  int try_reconnect;
160
  int m_error;
161 162 163 164 165 166 167 168 169 170 171 172 173
#ifdef HAVE_GLOBAL_REPLICATION  
  NdbRepHandle m_repserver;
  const char *rep_host;
  bool rep_connected;
#endif
};


/*
 * Facade object for CommandInterpreter
 */

#include "ndb_mgmclient.hpp"
174
#include "ndb_mgmclient.h"
175

176
Ndb_mgmclient::Ndb_mgmclient(const char *host,int verbose)
177
{
178
  m_cmd= new CommandInterpreter(host,verbose);
179 180 181 182 183
}
Ndb_mgmclient::~Ndb_mgmclient()
{
  delete m_cmd;
}
184
int Ndb_mgmclient::execute(const char *_line, int _try_reconnect, int *error)
185
{
186
  return m_cmd->execute(_line,_try_reconnect,error);
187 188 189 190 191 192 193
}
int
Ndb_mgmclient::disconnect()
{
  return m_cmd->disconnect();
}

194 195 196 197 198
extern "C" {
  Ndb_mgmclient_handle ndb_mgmclient_handle_create(const char *connect_string)
  {
    return (Ndb_mgmclient_handle) new Ndb_mgmclient(connect_string);
  }
199
  int ndb_mgmclient_execute(Ndb_mgmclient_handle h, int argc, char** argv)
200 201 202 203 204 205
  {
    return ((Ndb_mgmclient*)h)->execute(argc, argv, 1);
  }
  int ndb_mgmclient_handle_destroy(Ndb_mgmclient_handle h)
  {
    delete (Ndb_mgmclient*)h;
206
    return 0;
207 208
  }
}
209 210 211
/*
 * The CommandInterpreter
 */
212 213 214 215

#include <mgmapi.h>
#include <mgmapi_debug.h>
#include <version.h>
216
#include <NdbAutoPtr.hpp>
217 218
#include <NdbOut.hpp>
#include <NdbSleep.h>
219
#include <NdbMem.h>
220 221 222 223 224 225 226
#include <EventLogger.hpp>
#include <signaldata/SetLogLevelOrd.hpp>
#include <signaldata/GrepImpl.hpp>
#ifdef HAVE_GLOBAL_REPLICATION

#endif // HAVE_GLOBAL_REPLICATION
#include "MgmtErrorReporter.hpp"
227 228 229 230
#include <Parser.hpp>
#include <SocketServer.hpp>
#include <util/InputStream.hpp>
#include <util/OutputStream.hpp>
231

232
int Ndb_mgmclient::execute(int argc, char** argv, int _try_reconnect, int *error)
233 234 235 236 237 238 239 240
{
  if (argc <= 0)
    return 0;
  BaseString _line(argv[0]);
  for (int i= 1; i < argc; i++)
  {
    _line.appfmt(" %s", argv[i]);
  }
241
  return m_cmd->execute(_line.c_str(),_try_reconnect, error);
242
}
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

/*****************************************************************************
 * HELP
 *****************************************************************************/
static const char* helpText =
"---------------------------------------------------------------------------\n"
" NDB Cluster -- Management Client -- Help\n"
"---------------------------------------------------------------------------\n"
"HELP                                   Print help text\n"
"HELP SHOW                              Help for SHOW command\n"
#ifdef HAVE_GLOBAL_REPLICATION
"HELP REPLICATION                       Help for global replication\n"
#endif // HAVE_GLOBAL_REPLICATION
#ifdef VM_TRACE // DEBUG ONLY
"HELP DEBUG                             Help for debug compiled version\n"
#endif
"SHOW                                   Print information about cluster\n"
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
260
#if 0
261 262
"SHOW CONFIG                            Print configuration\n"
"SHOW PARAMETERS                        Print configuration parameters\n"
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
263
#endif
264 265
"START BACKUP                           Start backup\n"
"ABORT BACKUP <backup id>               Abort backup\n"
266
"SHUTDOWN                               Shutdown all processes in cluster and quit\n"
267 268 269
"CLUSTERLOG ON [<severity>] ...         Enable Cluster logging\n"
"CLUSTERLOG OFF [<severity>] ...        Disable Cluster logging\n"
"CLUSTERLOG TOGGLE [<severity>] ...     Toggle severity filter on/off\n"
270 271 272 273 274 275 276 277
"CLUSTERLOG INFO                        Print cluster log information\n"
"<id> START                             Start DB node (started with -n)\n"
"<id> RESTART [-n] [-i]                 Restart DB node\n"
"<id> STOP                              Stop DB node\n"
"ENTER SINGLE USER MODE <api-node>      Enter single user mode\n"
"EXIT SINGLE USER MODE                  Exit single user mode\n"
"<id> STATUS                            Print status\n"
"<id> CLUSTERLOG {<category>=<level>}+  Set log level for cluster log\n"
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
278
#ifdef HAVE_GLOBAL_REPLICATION
279
"REP CONNECT <host:port>                Connect to REP server on host:port\n"
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
280
#endif
281
"PURGE STALE SESSIONS                   Reset reserved nodeid's in the mgmt server\n"
282
"CONNECT [<connectstring>]              Connect to management server (reconnect if already connected)\n"
283 284 285 286 287 288 289 290 291
"QUIT                                   Quit management client\n"
;

static const char* helpTextShow =
"---------------------------------------------------------------------------\n"
" NDB Cluster -- Management Client -- Help for SHOW command\n"
"---------------------------------------------------------------------------\n"
"SHOW prints NDB Cluster information\n\n"
"SHOW               Print information about cluster\n" 
292
#if 0
293 294
"SHOW CONFIG        Print configuration (in initial config file format)\n" 
"SHOW PARAMETERS    Print information about configuration parameters\n\n"
295
#endif
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
;

#ifdef HAVE_GLOBAL_REPLICATION
static const char* helpTextRep =
"---------------------------------------------------------------------------\n"
" NDB Cluster -- Management Client -- Help for Global Replication\n"
"---------------------------------------------------------------------------\n"
"Commands should be executed on the standby NDB Cluster\n"
"These features are in an experimental release state.\n"
"\n"
"Simple Commands:\n"
"REP START              Start Global Replication\n" 
"REP START REQUESTOR    Start Global Replication Requestor\n" 
"REP STATUS             Show Global Replication status\n" 
"REP STOP               Stop Global Replication\n"
"REP STOP REQUESTOR     Stop Global Replication Requestor\n"
"\n" 
"Advanced Commands:\n"
"REP START <protocol>   Starts protocol\n"
"REP STOP <protocol>    Stops protocol\n"
"<protocol> = TRANSFER | APPLY | DELETE\n"
"\n"
#ifdef VM_TRACE // DEBUG ONLY
"Debugging commands:\n"
"REP DELETE             Removes epochs stored in primary and standy systems\n"
"REP DROP <tableid>     Drop a table in SS identified by table id\n"
"REP SLOWSTOP           Stop Replication (Tries to synchonize with primary)\n" 
"REP FASTSTOP           Stop Replication (Stops in consistent state)\n" 
"<component> = SUBSCRIPTION\n"
"              METALOG | METASCAN | DATALOG | DATASCAN\n"
"              REQUESTOR | TRANSFER | APPLY | DELETE\n"
#endif
;
#endif // HAVE_GLOBAL_REPLICATION

#ifdef VM_TRACE // DEBUG ONLY
static const char* helpTextDebug =
"---------------------------------------------------------------------------\n"
" NDB Cluster -- Management Client -- Help for Debugging (Internal use only)\n"
"---------------------------------------------------------------------------\n"
"SHOW PROPERTIES                       Print config properties object\n"
"<id> LOGLEVEL {<category>=<level>}+   Set log level\n"
#ifdef ERROR_INSERT
"<id> ERROR <errorNo>                  Inject error into NDB node\n"
#endif
"<id> TRACE <traceNo>                  Set trace number\n"
"<id> LOG [BLOCK = {ALL|<block>+}]     Set logging on in & out signals\n"
"<id> LOGIN [BLOCK = {ALL|<block>+}]   Set logging on in signals\n"
"<id> LOGOUT [BLOCK = {ALL|<block>+}]  Set logging on out signals\n"
"<id> LOGOFF [BLOCK = {ALL|<block>+}]  Unset signal logging\n"
"<id> TESTON                           Start signal logging\n"
"<id> TESTOFF                          Stop signal logging\n"
"<id> SET <configParamName> <value>    Update configuration variable\n"
"<id> DUMP <arg>                       Dump system state to cluster.log\n"
"<id> GETSTAT                          Print statistics\n"
"\n"
"<id>       = ALL | Any database node id\n"
;
#endif

static bool
convert(const char* s, int& val) {
  
  if (s == NULL)
    return false;

  if (strlen(s) == 0)
    return false;

  errno = 0;
  char* p;
  long v = strtol(s, &p, 10);
  if (errno != 0)
    return false;

  if (p != &s[strlen(s)])
    return false;
  
  val = v;
  return true;
}

/*
 * Constructor
 */
381 382
CommandInterpreter::CommandInterpreter(const char *_host,int verbose) 
  : m_verbose(verbose)
383 384 385 386
{
  m_mgmsrv = ndb_mgm_create_handle();
  if(m_mgmsrv == NULL) {
    ndbout_c("Cannot create handle to management server.");
387 388 389 390
    exit(-1);
  }
  if (ndb_mgm_set_connectstring(m_mgmsrv, _host))
  {
391
    printError();
392
    exit(-1);
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  }

  connected = false;
  try_reconnect = 0;
#ifdef HAVE_GLOBAL_REPLICATION
  rep_host = NULL;
  m_repserver = NULL;
  rep_connected = false;
#endif
}

/*
 * Destructor
 */
CommandInterpreter::~CommandInterpreter() 
{
  connected = false;
  ndb_mgm_destroy_handle(&m_mgmsrv);
}

413
static bool 
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
emptyString(const char* s) 
{
  if (s == NULL) {
    return true;
  }

  for (unsigned int i = 0; i < strlen(s); ++i) {
    if (! isspace(s[i])) {
      return false;
    }
  }

  return true;
}

void
CommandInterpreter::printError() 
{
432 433
  if (ndb_mgm_check_connection(m_mgmsrv))
    connected= false;
434 435 436 437 438 439 440 441 442 443 444 445 446
  ndbout_c("* %5d: %s", 
	   ndb_mgm_get_latest_error(m_mgmsrv),
	   ndb_mgm_get_latest_error_msg(m_mgmsrv));
  ndbout_c("*        %s", ndb_mgm_get_latest_error_desc(m_mgmsrv));
}

//*****************************************************************************
//*****************************************************************************

bool 
CommandInterpreter::connect() 
{
  if(!connected) {
447
    if(!ndb_mgm_connect(m_mgmsrv, try_reconnect-1, 5, 1))
448
    {
449
      connected = true;
450 451 452 453 454 455 456
      if (m_verbose)
      {
	printf("Connected to Management Server at: %s:%d\n",
	       ndb_mgm_get_connected_host(m_mgmsrv),
	       ndb_mgm_get_connected_port(m_mgmsrv));
      }
    }
457 458 459 460 461 462 463
  }
  return connected;
}

bool 
CommandInterpreter::disconnect() 
{
464
  if (connected && (ndb_mgm_disconnect(m_mgmsrv) == -1)) {
465 466 467 468 469 470 471 472 473 474
    ndbout_c("Could not disconnect from management server");
    printError();
  }
  connected = false;
  return true;
}

//*****************************************************************************
//*****************************************************************************

475
int 
476 477
CommandInterpreter::execute(const char *_line, int _try_reconnect,
			    int *error) 
478 479 480
{
  if (_try_reconnect >= 0)
    try_reconnect=_try_reconnect;
481 482 483 484 485 486 487 488 489 490 491 492 493
  int result= execute_impl(_line);
  if (error)
    *error= m_error;
  return result;
}

int 
CommandInterpreter::execute_impl(const char *_line) 
{
  DBUG_ENTER("CommandInterpreter::execute_impl");
  DBUG_PRINT("enter",("line=\"%s\"",_line));
  m_error= 0;

494 495 496
  char * line;
  if(_line == NULL) {
    //   ndbout << endl;
497
    DBUG_RETURN(false);
498
  }
499 500
  line = my_strdup(_line,MYF(MY_WME));
  My_auto_ptr<char> ptr(line);
501
  
502 503
  if (emptyString(line) ||
      line[0] == '#') {
504
    DBUG_RETURN(true);
505 506 507 508 509 510
  }
  
  // if there is anything in the line proceed
  char* firstToken = strtok(line, " ");
  char* allAfterFirstToken = strtok(NULL, "");
  
511 512
  if (strcasecmp(firstToken, "HELP") == 0 ||
      strcasecmp(firstToken, "?") == 0) {
513
    executeHelp(allAfterFirstToken);
514 515
    DBUG_RETURN(true);
  }
516
  else if (strcasecmp(firstToken, "CONNECT") == 0) {
517 518
    executeConnect(allAfterFirstToken);
    DBUG_RETURN(true);
519
  }
520 521 522 523 524
  else if (strcasecmp(firstToken, "SLEEP") == 0) {
    if (allAfterFirstToken)
      sleep(atoi(allAfterFirstToken));
    DBUG_RETURN(true);
  }
525 526 527 528 529 530
  else if((strcasecmp(firstToken, "QUIT") == 0 ||
	  strcasecmp(firstToken, "EXIT") == 0 ||
	  strcasecmp(firstToken, "BYE") == 0) && 
	  allAfterFirstToken == NULL){
    DBUG_RETURN(false);
  }
531 532 533 534

  if (!connect())
    DBUG_RETURN(true);

535
  if (strcasecmp(firstToken, "SHOW") == 0) {
536
    executeShow(allAfterFirstToken);
537
    DBUG_RETURN(true);
538
  }
539
  else if (strcasecmp(firstToken, "SHUTDOWN") == 0) {
540
    m_error= executeShutdown(allAfterFirstToken);
541
    DBUG_RETURN(true);
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
542
  }
543
  else if (strcasecmp(firstToken, "CLUSTERLOG") == 0){
544
    executeClusterLog(allAfterFirstToken);
545
    DBUG_RETURN(true);
546
  }
547
  else if(strcasecmp(firstToken, "START") == 0 &&
548
	  allAfterFirstToken != NULL &&
549 550
	  strncasecmp(allAfterFirstToken, "BACKUP", sizeof("BACKUP") - 1) == 0){
    m_error= executeStartBackup(allAfterFirstToken);
551
    DBUG_RETURN(true);
552
  }
553
  else if(strcasecmp(firstToken, "ABORT") == 0 &&
554
	  allAfterFirstToken != NULL &&
555
	  strncasecmp(allAfterFirstToken, "BACKUP", sizeof("BACKUP") - 1) == 0){
556
    executeAbortBackup(allAfterFirstToken);
557
    DBUG_RETURN(true);
558
  }
559
  else if (strcasecmp(firstToken, "PURGE") == 0) {
560
    executePurge(allAfterFirstToken);
561
    DBUG_RETURN(true);
562
  } 
563
#ifdef HAVE_GLOBAL_REPLICATION
564 565
  else if(strcasecmp(firstToken, "REPLICATION") == 0 ||
	  strcasecmp(firstToken, "REP") == 0) {
566
    executeRep(allAfterFirstToken);
567
    DBUG_RETURN(true);
568 569
  }
#endif // HAVE_GLOBAL_REPLICATION
570
  else if(strcasecmp(firstToken, "ENTER") == 0 &&
571
	  allAfterFirstToken != NULL &&
572
	  strncasecmp(allAfterFirstToken, "SINGLE USER MODE ", 
573 574
		  sizeof("SINGLE USER MODE") - 1) == 0){
    executeEnterSingleUser(allAfterFirstToken);
575
    DBUG_RETURN(true);
576
  }
577
  else if(strcasecmp(firstToken, "EXIT") == 0 &&
578
	  allAfterFirstToken != NULL &&
579
	  strncasecmp(allAfterFirstToken, "SINGLE USER MODE ", 
580 581
		  sizeof("SINGLE USER MODE") - 1) == 0){
    executeExitSingleUser(allAfterFirstToken);
582
    DBUG_RETURN(true);
583
  }
584
  else if (strcasecmp(firstToken, "ALL") == 0) {
585 586 587 588 589 590 591 592
    analyseAfterFirstToken(-1, allAfterFirstToken);
  } else {
    /**
     * First token should be a digit, node ID
     */
    int nodeId;

    if (! convert(firstToken, nodeId)) {
593
      ndbout << "Invalid command: " << _line << endl;
594
      ndbout << "Type HELP for help." << endl << endl;
595
      DBUG_RETURN(true);
596 597
    }

598
    if (nodeId <= 0) {
599
      ndbout << "Invalid node ID: " << firstToken << "." << endl;
600
      DBUG_RETURN(true);
601 602 603 604 605
    }
    
    analyseAfterFirstToken(nodeId, allAfterFirstToken);
    
  }
606
  DBUG_RETURN(true);
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
}


/**
 * List of commands used as second command argument
 */
static const CommandInterpreter::CommandFunctionPair commands[] = {
  { "START", &CommandInterpreter::executeStart }
  ,{ "RESTART", &CommandInterpreter::executeRestart }
  ,{ "STOP", &CommandInterpreter::executeStop }
  ,{ "STATUS", &CommandInterpreter::executeStatus }
  ,{ "LOGLEVEL", &CommandInterpreter::executeLogLevel }
  ,{ "CLUSTERLOG", &CommandInterpreter::executeEventReporting }
#ifdef ERROR_INSERT
  ,{ "ERROR", &CommandInterpreter::executeError }
#endif
  ,{ "TRACE", &CommandInterpreter::executeTrace }
  ,{ "LOG", &CommandInterpreter::executeLog }
  ,{ "LOGIN", &CommandInterpreter::executeLogIn }
  ,{ "LOGOUT", &CommandInterpreter::executeLogOut }
  ,{ "LOGOFF", &CommandInterpreter::executeLogOff }
  ,{ "TESTON", &CommandInterpreter::executeTestOn }
  ,{ "TESTOFF", &CommandInterpreter::executeTestOff }
  ,{ "SET", &CommandInterpreter::executeSet }
  ,{ "GETSTAT", &CommandInterpreter::executeGetStat }
  ,{ "DUMP", &CommandInterpreter::executeDumpState }
};


//*****************************************************************************
//*****************************************************************************
void
CommandInterpreter::analyseAfterFirstToken(int processId,
					   char* allAfterFirstToken) {
  
  if (emptyString(allAfterFirstToken)) {
    if (processId == -1) {
      ndbout << "Expected a command after ALL." << endl;
    }
    else {
      ndbout << "Expected a command after node ID." << endl;
    }
    return;
  }
  
  char* secondToken = strtok(allAfterFirstToken, " ");
  char* allAfterSecondToken = strtok(NULL, "\0");

  const int tmpSize = sizeof(commands)/sizeof(CommandFunctionPair);
  ExecuteFunction fun = 0;
  const char * command = 0;
  for(int i = 0; i<tmpSize; i++){
659
    if(strcasecmp(secondToken, commands[i].command) == 0){
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
      fun = commands[i].executeFunction;
      command = commands[i].command;
      break;
    }
  }
  
  if(fun == 0){
    ndbout << "Invalid command: " << secondToken << endl;
    ndbout << "Type HELP for help." << endl << endl;
    return;
  }
  
  if(processId == -1){
    executeForAll(command, fun, allAfterSecondToken);
  } else {
    (this->*fun)(processId, allAfterSecondToken, false);
  }
677
  ndbout << endl;
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
}

/**
 * Get next nodeid larger than the give node_id. node_id will be
 * set to the next node_id in the list. node_id should be set
 * to 0 (zero) on the first call.
 *
 * @param handle the NDB management handle
 * @param node_id last node_id retreived, 0 at first call
 * @param type type of node to look for
 * @return 1 if a node was found, 0 if no more node exist
 */
static 
int 
get_next_nodeid(struct ndb_mgm_cluster_state *cl,
		int *node_id,
		enum ndb_mgm_node_type type)
{
  int i;
  
  if(cl == NULL)
    return 0;
  
  i=0;
  while((i < cl->no_of_nodes)) {
    if((*node_id < cl->node_states[i].node_id) &&
       (cl->node_states[i].node_type == type)) {
      
      if(i >= cl->no_of_nodes)
	return 0;
      
      *node_id = cl->node_states[i].node_id;
      return 1;
    }
    i++;
  }
  
  return 0;
}

void
CommandInterpreter::executeForAll(const char * cmd, ExecuteFunction fun, 
				  const char * allAfterSecondToken)
{
  int nodeId = 0;
723
  if(strcasecmp(cmd, "STOP") == 0) {
724 725
    ndbout_c("Executing STOP on all nodes.");
    (this->*fun)(nodeId, allAfterSecondToken, true);
726
  } else if(strcasecmp(cmd, "RESTART") == 0) {
727 728 729 730 731 732
    ndbout_c("Executing RESTART on all nodes.");
    ndbout_c("Starting shutdown. This may take a while. Please wait...");
    (this->*fun)(nodeId, allAfterSecondToken, true);
    ndbout_c("Trying to start all nodes of system.");
    ndbout_c("Use ALL STATUS to see the system start-up phases.");
  } else {
733
    struct ndb_mgm_cluster_state *cl= ndb_mgm_get_status(m_mgmsrv);
734 735 736 737 738
    if(cl == 0){
      ndbout_c("Unable get status from management server");
      printError();
      return;
    }
739
    NdbAutoPtr<char> ap1((char*)cl);
740
    while(get_next_nodeid(cl, &nodeId, NDB_MGM_NODE_TYPE_NDB))
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
      (this->*fun)(nodeId, allAfterSecondToken, true);
  }
}

//*****************************************************************************
//*****************************************************************************
bool 
CommandInterpreter::parseBlockSpecification(const char* allAfterLog,
					    Vector<const char*>& blocks) 
{
  // Parse: [BLOCK = {ALL|<blockName>+}]

  if (emptyString(allAfterLog)) {
    return true;
  }

  // Copy allAfterLog since strtok will modify it  
758 759
  char* newAllAfterLog = my_strdup(allAfterLog,MYF(MY_WME));
  My_auto_ptr<char> ap1(newAllAfterLog);
760 761 762 763 764
  char* firstTokenAfterLog = strtok(newAllAfterLog, " ");
  for (unsigned int i = 0; i < strlen(firstTokenAfterLog); ++i) {
    firstTokenAfterLog[i] = toupper(firstTokenAfterLog[i]);
  }
  
765
  if (strcasecmp(firstTokenAfterLog, "BLOCK") != 0) {
766 767 768 769 770 771 772 773 774 775 776 777
    ndbout << "Unexpected value: " << firstTokenAfterLog 
	   << ". Expected BLOCK." << endl;
    return false;
  }

  char* allAfterFirstToken = strtok(NULL, "\0");
  if (emptyString(allAfterFirstToken)) {
    ndbout << "Expected =." << endl;
    return false;
  }

  char* secondTokenAfterLog = strtok(allAfterFirstToken, " ");
778
  if (strcasecmp(secondTokenAfterLog, "=") != 0) {
779 780 781 782 783 784 785
    ndbout << "Unexpected value: " << secondTokenAfterLog 
	   << ". Expected =." << endl;
    return false;
  }

  char* blockName = strtok(NULL, " ");
  bool all = false;
786
  if (blockName != NULL && (strcasecmp(blockName, "ALL") == 0)) {
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
    all = true;
  }
  while (blockName != NULL) {
    blocks.push_back(strdup(blockName));
    blockName = strtok(NULL, " ");
  }

  if (blocks.size() == 0) {
    ndbout << "No block specified." << endl;
    return false;
  }
  if (blocks.size() > 1 && all) {
    // More than "ALL" specified
    ndbout << "Nothing expected after ALL." << endl;
    return false;
  }
  
  return true;
}



/*****************************************************************************
 * HELP
 *****************************************************************************/
void 
CommandInterpreter::executeHelp(char* parameters)
{
  if (emptyString(parameters)) {
    ndbout << helpText;

    ndbout << endl 
	   << "<severity> = " 
	   << "ALERT | CRITICAL | ERROR | WARNING | INFO | DEBUG"
	   << endl;

    ndbout << "<category> = ";
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
824 825 826 827 828 829
    for(int i = CFG_MIN_LOGLEVEL; i <= CFG_MAX_LOGLEVEL; i++){
      const char *str= ndb_mgm_get_event_category_string((ndb_mgm_event_category)i);
      if (str) {
	if (i != CFG_MIN_LOGLEVEL)
	  ndbout << " | ";
	ndbout << str;
830 831 832 833 834 835 836
      }
    }
    ndbout << endl;

    ndbout << "<level>    = " << "0 - 15" << endl;
    ndbout << "<id>       = " << "ALL | Any database node id" << endl;
    ndbout << endl;
837
  } else if (strcasecmp(parameters, "SHOW") == 0) {
838 839
    ndbout << helpTextShow;
#ifdef HAVE_GLOBAL_REPLICATION
840 841
  } else if (strcasecmp(parameters, "REPLICATION") == 0 ||
	     strcasecmp(parameters, "REP") == 0) {
842 843 844
    ndbout << helpTextRep;
#endif // HAVE_GLOBAL_REPLICATION
#ifdef VM_TRACE // DEBUG ONLY
845
  } else if (strcasecmp(parameters, "DEBUG") == 0) {
846 847 848 849 850 851 852 853 854
    ndbout << helpTextDebug;
#endif
  } else {
    ndbout << "Invalid argument: " << parameters << endl;
    ndbout << "Type HELP for help." << endl << endl;
  }
}


tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
855 856 857 858
/*****************************************************************************
 * SHUTDOWN
 *****************************************************************************/

859
int
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
860 861 862 863 864 865
CommandInterpreter::executeShutdown(char* parameters) 
{ 
  ndb_mgm_cluster_state *state = ndb_mgm_get_status(m_mgmsrv);
  if(state == NULL) {
    ndbout_c("Could not get status");
    printError();
866
    return 1;
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
867
  }
868
  NdbAutoPtr<char> ap1((char*)state);
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
869 870 871

  int result = 0;
  result = ndb_mgm_stop(m_mgmsrv, 0, 0);
872
  if (result < 0) {
873
    ndbout << "Shutdown off NDB Cluster storage node(s) failed." << endl;
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
874
    printError();
875
    return result;
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
876 877
  }

878
  ndbout << result << " NDB Cluster storage node(s) have shutdown." << endl;
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
879 880 881 882 883 884 885 886

  int mgm_id= 0;
  for(int i=0; i < state->no_of_nodes; i++) {
    if(state->node_states[i].node_type == NDB_MGM_NODE_TYPE_MGM &&
       state->node_states[i].version != 0){
      if (mgm_id == 0)
	mgm_id= state->node_states[i].node_id;
      else {
887 888
	ndbout << "Unable to locate management server, "
	       << "shutdown manually with <id> STOP"
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
889
	       << endl;
890
	return 1;
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
891 892 893 894 895 896
      }
    }
  }

  result = ndb_mgm_stop(m_mgmsrv, 1, &mgm_id);
  if (result <= 0) {
897
    ndbout << "Shutdown of NDB Cluster management server failed." << endl;
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
898
    printError();
899 900 901
    if (result == 0)
      return 1;
    return result;
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
902 903
  }

904
  connected = false;
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
905
  ndbout << "NDB Cluster management server shutdown." << endl;
906
  return 0;
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
907 908
}

909 910 911 912
/*****************************************************************************
 * SHOW
 *****************************************************************************/

913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938

static
const char *status_string(ndb_mgm_node_status status)
{
  switch(status){
  case NDB_MGM_NODE_STATUS_NO_CONTACT:
    return "not connected";
  case NDB_MGM_NODE_STATUS_NOT_STARTED:
    return "not started";
  case NDB_MGM_NODE_STATUS_STARTING:
    return "starting";
  case NDB_MGM_NODE_STATUS_STARTED:
    return "started";
  case NDB_MGM_NODE_STATUS_SHUTTING_DOWN:
    return "shutting down";
  case NDB_MGM_NODE_STATUS_RESTARTING:
    return "restarting";
  case NDB_MGM_NODE_STATUS_SINGLEUSER:
    return "single user mode";
  default:
    return "unknown state";
  }
}

static void
print_nodes(ndb_mgm_cluster_state *state, ndb_mgm_configuration_iterator *it,
939 940
	    const char *proc_name, int no_proc, ndb_mgm_node_type type,
	    int master_id)
941 942 943
{ 
  int i;
  ndbout << "[" << proc_name
944 945
	 << "(" << ndb_mgm_get_node_type_string(type) << ")]\t"
	 << no_proc << " node(s)" << endl;
946 947 948 949 950 951 952
  for(i=0; i < state->no_of_nodes; i++) {
    struct ndb_mgm_node_state *node_state= &(state->node_states[i]);
    if(node_state->node_type == type) {
      int node_id= node_state->node_id;
      ndbout << "id=" << node_id;
      if(node_state->version != 0) {
	const char *hostname= node_state->connect_address;
953 954
	if (hostname == 0
	    || strlen(hostname) == 0
955
	    || strcasecmp(hostname,"0.0.0.0") == 0)
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
	  ndbout << " ";
	else
	  ndbout << "\t@" << hostname;
	ndbout << "  (Version: "
	       << getMajor(node_state->version) << "."
	       << getMinor(node_state->version) << "."
	       << getBuild(node_state->version);
	if (type == NDB_MGM_NODE_TYPE_NDB) {
	  if (node_state->node_status != NDB_MGM_NODE_STATUS_STARTED) {
	    ndbout << ", " << status_string(node_state->node_status);
	  }
	  if (node_state->node_group >= 0) {
	    ndbout << ", Nodegroup: " << node_state->node_group;
	    if (node_state->dynamic_id == master_id)
	      ndbout << ", Master";
	  }
	}
	ndbout << ")" << endl;
      } else {
	if(ndb_mgm_find(it, CFG_NODE_ID, node_id) != 0){
	  ndbout_c("Unable to find node with id: %d", node_id);
	  return;
	}
	const char *config_hostname= 0;
	ndb_mgm_get_string_parameter(it, CFG_NODE_HOST, &config_hostname);
	if (config_hostname == 0 || config_hostname[0] == 0)
	  config_hostname= "any host";
983 984
	ndbout << " (not connected, accepting connect from "
	       << config_hostname << ")" << endl;
985 986 987 988 989 990
      }
    }
  }
  ndbout << endl;
}

991 992 993 994 995 996 997 998 999
void
CommandInterpreter::executePurge(char* parameters) 
{ 
  int command_ok= 0;
  do {
    if (emptyString(parameters))
      break;
    char* firstToken = strtok(parameters, " ");
    char* nextToken = strtok(NULL, " \0");
1000
    if (strcasecmp(firstToken,"STALE") == 0 &&
1001
	nextToken &&
1002
	strcasecmp(nextToken, "SESSIONS") == 0) {
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
      command_ok= 1;
      break;
    }
  } while(0);

  if (!command_ok) {
    ndbout_c("Unexpected command, expected: PURGE STALE SESSIONS");
    return;
  }

  int i;
  char *str;
  
  if (ndb_mgm_purge_stale_sessions(m_mgmsrv, &str)) {
    ndbout_c("Command failed");
    return;
  }
  if (str) {
    ndbout_c("Purged sessions with node id's: %s", str);
    free(str);
  }
  else
  {
    ndbout_c("No sessions purged");
  }
}

1030 1031
void
CommandInterpreter::executeShow(char* parameters) 
1032 1033
{ 
  int i;
1034 1035 1036 1037 1038 1039 1040
  if (emptyString(parameters)) {
    ndb_mgm_cluster_state *state = ndb_mgm_get_status(m_mgmsrv);
    if(state == NULL) {
      ndbout_c("Could not get status");
      printError();
      return;
    }
1041
    NdbAutoPtr<char> ap1((char*)state);
1042

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    ndb_mgm_configuration * conf = ndb_mgm_get_configuration(m_mgmsrv,0);
    if(conf == 0){
      ndbout_c("Could not get configuration");
      printError();
      return;
    }

    ndb_mgm_configuration_iterator * it;
    it = ndb_mgm_create_configuration_iterator((struct ndb_mgm_configuration *)conf, CFG_SECTION_NODE);

    if(it == 0){
      ndbout_c("Unable to create config iterator");
      return;
    }
    NdbAutoPtr<ndb_mgm_configuration_iterator> ptr(it);

1059
    int
1060 1061 1062 1063
      master_id= 0,
      ndb_nodes= 0,
      api_nodes= 0,
      mgm_nodes= 0;
1064

1065 1066 1067 1068 1069 1070 1071 1072
    for(i=0; i < state->no_of_nodes; i++) {
      if(state->node_states[i].node_type == NDB_MGM_NODE_TYPE_NDB &&
	 state->node_states[i].version != 0){
	master_id= state->node_states[i].dynamic_id;
	break;
      }
    }
    
1073
    for(i=0; i < state->no_of_nodes; i++) {
1074 1075 1076 1077 1078
      switch(state->node_states[i].node_type) {
      case NDB_MGM_NODE_TYPE_API:
	api_nodes++;
	break;
      case NDB_MGM_NODE_TYPE_NDB:
1079
	if (state->node_states[i].dynamic_id < master_id)
1080
	  master_id= state->node_states[i].dynamic_id;
1081 1082 1083 1084 1085 1086 1087 1088
	ndb_nodes++;
	break;
      case NDB_MGM_NODE_TYPE_MGM:
	mgm_nodes++;
	break;
      case NDB_MGM_NODE_TYPE_UNKNOWN:
        ndbout << "Error: Unknown Node Type" << endl;
        return;
1089 1090
      case NDB_MGM_NODE_TYPE_REP:
	abort();
1091 1092 1093
      }
    }

1094 1095
    ndbout << "Cluster Configuration" << endl
	   << "---------------------" << endl;
1096 1097 1098
    print_nodes(state, it, "ndbd",     ndb_nodes, NDB_MGM_NODE_TYPE_NDB, master_id);
    print_nodes(state, it, "ndb_mgmd", mgm_nodes, NDB_MGM_NODE_TYPE_MGM, 0);
    print_nodes(state, it, "mysqld",   api_nodes, NDB_MGM_NODE_TYPE_API, 0);
1099 1100
    //    ndbout << helpTextShow;
    return;
1101 1102
  } else if (strcasecmp(parameters, "PROPERTIES") == 0 ||
	     strcasecmp(parameters, "PROP") == 0) {
1103 1104
    ndbout << "SHOW PROPERTIES is not yet implemented." << endl;
    //  ndbout << "_mgmtSrvr.getConfig()->print();" << endl; /* XXX */
1105 1106
  } else if (strcasecmp(parameters, "CONFIGURATION") == 0 ||
	     strcasecmp(parameters, "CONFIG") == 0){
1107 1108
    ndbout << "SHOW CONFIGURATION is not yet implemented." << endl;
    //nbout << "_mgmtSrvr.getConfig()->printConfigFile();" << endl; /* XXX */
1109 1110 1111
  } else if (strcasecmp(parameters, "PARAMETERS") == 0 ||
	     strcasecmp(parameters, "PARAMS") == 0 ||
	     strcasecmp(parameters, "PARAM") == 0) {
1112 1113 1114 1115 1116 1117 1118 1119
    ndbout << "SHOW PARAMETERS is not yet implemented." << endl;
    //    ndbout << "_mgmtSrvr.getConfig()->getConfigInfo()->print();" 
    //           << endl; /* XXX */
  } else {
    ndbout << "Invalid argument." << endl;
  }
}

1120 1121 1122 1123
void
CommandInterpreter::executeConnect(char* parameters) 
{
  disconnect();
1124 1125 1126 1127 1128 1129 1130 1131
  if (!emptyString(parameters)) {
    if (ndb_mgm_set_connectstring(m_mgmsrv,
				  BaseString(parameters).trim().c_str()))
    {
      printError();
      return;
    }
  }
1132 1133
  connect();
}
1134 1135 1136 1137 1138 1139

//*****************************************************************************
//*****************************************************************************
void 
CommandInterpreter::executeClusterLog(char* parameters) 
{
1140
  DBUG_ENTER("CommandInterpreter::executeClusterLog");
1141
  int i;
1142 1143 1144 1145 1146 1147 1148
  if (emptyString(parameters))
  {
    ndbout << "Missing argument." << endl;
    DBUG_VOID_RETURN;
  }

  enum ndb_mgm_clusterlog_level severity = NDB_MGM_CLUSTERLOG_ALL;
1149
    
1150 1151 1152 1153 1154
  char * tmpString = my_strdup(parameters,MYF(MY_WME));
  My_auto_ptr<char> ap1(tmpString);
  char * tmpPtr = 0;
  char * item = strtok_r(tmpString, " ", &tmpPtr);
  int enable;
1155

1156 1157 1158 1159 1160 1161
  Uint32 *enabled = ndb_mgm_get_logfilter(m_mgmsrv);
  if(enabled == NULL) {
    ndbout << "Couldn't get status" << endl;
    printError();
    DBUG_VOID_RETURN;
  }
1162

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
  /********************
   * CLUSTERLOG INFO
   ********************/
  if (strcasecmp(item, "INFO") == 0) {
    DBUG_PRINT("info",("INFO"));
    if(enabled[0] == 0)
    {
      ndbout << "Cluster logging is disabled." << endl;
      DBUG_VOID_RETURN;
    }
#if 0 
    for(i = 0; i<7;i++)
      printf("enabled[%d] = %d\n", i, enabled[i]);
#endif
    ndbout << "Severities enabled: ";
    for(i = 1; i < (int)NDB_MGM_CLUSTERLOG_ALL; i++) {
      const char *str= ndb_mgm_get_clusterlog_level_string((ndb_mgm_clusterlog_level)i);
      if (str == 0)
      {
	DBUG_ASSERT(false);
	continue;
1184
      }
1185 1186
      if(enabled[i])
	ndbout << BaseString(str).ndb_toupper() << " ";
1187
    }
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    ndbout << endl;
    DBUG_VOID_RETURN;

  } 
  else if (strcasecmp(item, "FILTER") == 0 ||
	   strcasecmp(item, "TOGGLE") == 0)
  {
    DBUG_PRINT("info",("TOGGLE"));
    enable= -1;
  } 
  else if (strcasecmp(item, "OFF") == 0) 
  {
    DBUG_PRINT("info",("OFF"));
    enable= 0;
  } else if (strcasecmp(item, "ON") == 0) {
    DBUG_PRINT("info",("ON"));
    enable= 1;
1205
  } else {
1206 1207
    ndbout << "Invalid argument." << endl;
    DBUG_VOID_RETURN;
1208
  }
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257

  int res_enable;
  item = strtok_r(NULL, " ", &tmpPtr);
  if (item == NULL) {
    res_enable= ndb_mgm_filter_clusterlog(m_mgmsrv,
					  NDB_MGM_CLUSTERLOG_ON, enable, NULL);
    if (res_enable < 0)
    {
      ndbout << "Couldn't set filter" << endl;
      printError();
      DBUG_VOID_RETURN;
    }
    ndbout << "Cluster logging is " << (res_enable ? "enabled.":"disabled") << endl;
    DBUG_VOID_RETURN;
  }

  do {
    severity= NDB_MGM_ILLEGAL_CLUSTERLOG_LEVEL;
    if (strcasecmp(item, "ALL") == 0) {
      severity = NDB_MGM_CLUSTERLOG_ALL;	
    } else if (strcasecmp(item, "ALERT") == 0) {
      severity = NDB_MGM_CLUSTERLOG_ALERT;
    } else if (strcasecmp(item, "CRITICAL") == 0) { 
      severity = NDB_MGM_CLUSTERLOG_CRITICAL;
    } else if (strcasecmp(item, "ERROR") == 0) {
      severity = NDB_MGM_CLUSTERLOG_ERROR;
    } else if (strcasecmp(item, "WARNING") == 0) {
      severity = NDB_MGM_CLUSTERLOG_WARNING;
    } else if (strcasecmp(item, "INFO") == 0) {
      severity = NDB_MGM_CLUSTERLOG_INFO;
    } else if (strcasecmp(item, "DEBUG") == 0) {
      severity = NDB_MGM_CLUSTERLOG_DEBUG;
    } else if (strcasecmp(item, "OFF") == 0 ||
	       strcasecmp(item, "ON") == 0) {
      if (enable < 0) // only makes sense with toggle
	severity = NDB_MGM_CLUSTERLOG_ON;
    }
    if (severity == NDB_MGM_ILLEGAL_CLUSTERLOG_LEVEL) {
      ndbout << "Invalid severity level: " << item << endl;
      DBUG_VOID_RETURN;
    }

    res_enable = ndb_mgm_filter_clusterlog(m_mgmsrv, severity, enable, NULL);
    if (res_enable < 0)
    {
      ndbout << "Couldn't set filter" << endl;
      printError();
      DBUG_VOID_RETURN;
    }
1258
    ndbout << BaseString(item).ndb_toupper().c_str() << " " << (res_enable ? "enabled":"disabled") << endl;
1259 1260 1261 1262 1263

    item = strtok_r(NULL, " ", &tmpPtr);	
  } while(item != NULL);

  DBUG_VOID_RETURN;
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
} 

//*****************************************************************************
//*****************************************************************************

void
CommandInterpreter::executeStop(int processId, const char *, bool all) 
{
  int result = 0;
  if(all) {
    result = ndb_mgm_stop(m_mgmsrv, 0, 0);
  } else {
    result = ndb_mgm_stop(m_mgmsrv, 1, &processId);
  }
1278
  if (result < 0) {
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
    ndbout << "Shutdown failed." << endl;
    printError();
  } else
    {
      if(all)
	ndbout << "NDB Cluster has shutdown." << endl;
      else
	ndbout << "Node " << processId << " has shutdown." << endl;
    }
}

void
CommandInterpreter::executeEnterSingleUser(char* parameters) 
{
  strtok(parameters, " ");
  struct ndb_mgm_reply reply;
  char* id = strtok(NULL, " ");
  id = strtok(NULL, " ");
  id = strtok(NULL, "\0");
  int nodeId = -1;
  if(id == 0 || sscanf(id, "%d", &nodeId) != 1){
    ndbout_c("Invalid arguments: expected <NodeId>");
    ndbout_c("Use SHOW to see what API nodes are configured");
    return;
  }
  int result = ndb_mgm_enter_single_user(m_mgmsrv, nodeId, &reply);
  
  if (result != 0) {
    ndbout_c("Entering single user mode for node %d failed", nodeId);
    printError();
  } else {
    ndbout_c("Entering single user mode");
    ndbout_c("Access will be granted for API node %d only.", nodeId);
    ndbout_c("Use ALL STATUS to see when single user mode has been entered.");
  }
}

void 
CommandInterpreter::executeExitSingleUser(char* parameters) 
{
  int result = ndb_mgm_exit_single_user(m_mgmsrv, 0);
  if (result != 0) {
    ndbout_c("Exiting single user mode failed.");
    printError();
  } else {
    ndbout_c("Exiting single user mode in progress.");
    ndbout_c("Use ALL STATUS to see when single user mode has been exited.");
  }
}

void
CommandInterpreter::executeStart(int processId, const char* parameters,
				 bool all) 
{
  int result;
  if(all) {
    result = ndb_mgm_start(m_mgmsrv, 0, 0);
  } else {
    result = ndb_mgm_start(m_mgmsrv, 1, &processId);
  }

  if (result <= 0) {
    ndbout << "Start failed." << endl;
    printError();
  } else
    {
      if(all)
	ndbout_c("NDB Cluster is being started.");
      else
	ndbout_c("Database node %d is being started.", processId);
    }
}

void
CommandInterpreter::executeRestart(int processId, const char* parameters,
				   bool all) 
{
  int result;
  int nostart = 0;
  int initialstart = 0;
  int abort = 0;

  if(parameters != 0 && strlen(parameters) != 0){
1362 1363
    char * tmpString = my_strdup(parameters,MYF(MY_WME));
    My_auto_ptr<char> ap1(tmpString);
1364 1365 1366
    char * tmpPtr = 0;
    char * item = strtok_r(tmpString, " ", &tmpPtr);
    while(item != NULL){
1367
      if(strcasecmp(item, "-N") == 0)
1368
	nostart = 1;
1369
      if(strcasecmp(item, "-I") == 0)
1370
	initialstart = 1;
1371
      if(strcasecmp(item, "-A") == 0)
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
	abort = 1;
      item = strtok_r(NULL, " ", &tmpPtr);
    }
  }

  if(all) {
    result = ndb_mgm_restart2(m_mgmsrv, 0, NULL, initialstart, nostart, abort);
  } else {
    int v[1];
    v[0] = processId;
    result = ndb_mgm_restart2(m_mgmsrv, 1, v, initialstart, nostart, abort);
  }
  
  if (result <= 0) {
    ndbout.println("Restart failed.", result);
    printError();
  } else
    {
      if(all)
	ndbout << "NDB Cluster is being restarted." << endl;
      else
1393
	ndbout_c("Node %d is being restarted.", processId);
1394 1395 1396 1397 1398 1399 1400
    }
}

void
CommandInterpreter::executeDumpState(int processId, const char* parameters,
				     bool all) 
{
1401
  if(emptyString(parameters)){
1402 1403 1404 1405 1406 1407 1408
    ndbout << "Expected argument" << endl;
    return;
  }

  Uint32 no = 0;
  int pars[25];
  
1409 1410
  char * tmpString = my_strdup(parameters,MYF(MY_WME));
  My_auto_ptr<char> ap1(tmpString);
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
  char * tmpPtr = 0;
  char * item = strtok_r(tmpString, " ", &tmpPtr);
  while(item != NULL){
    if (0x0 <= strtoll(item, NULL, 0) && strtoll(item, NULL, 0) <= 0xffffffff){
      pars[no] = strtoll(item, NULL, 0); 
    } else {
      ndbout << "Illegal value in argument to signal." << endl
	     << "(Value must be between 0 and 0xffffffff.)" 
	     << endl;
      return;
    }
    no++;
    item = strtok_r(NULL, " ", &tmpPtr);
  }
  ndbout << "Sending dump signal with data:" << endl;
  for (Uint32 i=0; i<no; i++) {
    ndbout.setHexFormat(1) << pars[i] << " ";
    if (!(i+1 & 0x3)) ndbout << endl;
  }
  
  struct ndb_mgm_reply reply;
  ndb_mgm_dump_state(m_mgmsrv, processId, pars, no, &reply);
}

void 
CommandInterpreter::executeStatus(int processId, 
				  const char* parameters, bool all) 
{
  if (! emptyString(parameters)) {
1440
    ndbout_c("No parameters expected to this command.");
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
    return;
  }

  ndb_mgm_node_status status;
  Uint32 startPhase, version;
  bool system;
  
  struct ndb_mgm_cluster_state *cl;
  cl = ndb_mgm_get_status(m_mgmsrv);
  if(cl == NULL) {
    ndbout_c("Cannot get status of node %d.", processId);
    printError();
    return;
  }
1455
  NdbAutoPtr<char> ap1((char*)cl);
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467

  int i = 0;
  while((i < cl->no_of_nodes) && cl->node_states[i].node_id != processId)
    i++;
  if(cl->node_states[i].node_id != processId) {
    ndbout << processId << ": Node not found" << endl;
    return;
  }
  status = cl->node_states[i].node_status;
  startPhase = cl->node_states[i].start_phase;
  version = cl->node_states[i].version;

1468
  ndbout << "Node " << processId << ": " << status_string(status);
1469 1470
  switch(status){
  case NDB_MGM_NODE_STATUS_STARTING:
1471
    ndbout << " (Phase " << startPhase << ")";
1472 1473
    break;
  case NDB_MGM_NODE_STATUS_SHUTTING_DOWN:
1474
    ndbout << " (Phase " << startPhase << ")";
1475 1476 1477 1478 1479 1480 1481 1482 1483
    break;
  default:
    break;
  }
  if(status != NDB_MGM_NODE_STATUS_NO_CONTACT)
    ndbout_c(" (Version %d.%d.%d)", 
	     getMajor(version) ,
	     getMinor(version),
	     getBuild(version));
1484 1485
  else
    ndbout << endl;
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
}


//*****************************************************************************
//*****************************************************************************

void 
CommandInterpreter::executeLogLevel(int processId, const char* parameters, 
				    bool all) 
{
  (void) all;
1497 1498 1499 1500
  if (emptyString(parameters)) {
    ndbout << "Expected argument" << endl;
    return;
  } 
1501 1502 1503 1504 1505 1506 1507
  BaseString tmp(parameters);
  Vector<BaseString> spec;
  tmp.split(spec, "=");
  if(spec.size() != 2){
    ndbout << "Invalid loglevel specification: " << parameters << endl;
    return;
  }
1508

1509 1510 1511 1512 1513 1514 1515 1516
  spec[0].trim().ndb_toupper();
  int category = ndb_mgm_match_event_category(spec[0].c_str());
  if(category == NDB_MGM_ILLEGAL_EVENT_CATEGORY){
    category = atoi(spec[0].c_str());
    if(category < NDB_MGM_MIN_EVENT_CATEGORY ||
       category > NDB_MGM_MAX_EVENT_CATEGORY){
      ndbout << "Unknown category: \"" << spec[0].c_str() << "\"" << endl;
      return;
1517 1518
    }
  }
1519 1520 1521 1522 1523 1524 1525
  
  int level = atoi(spec[1].c_str());
  if(level < 0 || level > 15){
    ndbout << "Invalid level: " << spec[1].c_str() << endl;
    return;
  }
  
1526 1527
  ndbout << "Executing LOGLEVEL on node " << processId << flush;

1528 1529 1530
  struct ndb_mgm_reply reply;
  int result;
  result = ndb_mgm_set_loglevel_node(m_mgmsrv, 
1531 1532
				     processId,
				     (ndb_mgm_event_category)category,
1533 1534
				     level, 
				     &reply);
1535
  
1536
  if (result < 0) {
1537
    ndbout_c(" failed.");
1538 1539
    printError();
  } else {
1540
    ndbout_c(" OK!");
1541
  }  
1542
  
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
}

//*****************************************************************************
//*****************************************************************************
void CommandInterpreter::executeError(int processId, 
				      const char* parameters, bool /* all */) 
{
  if (emptyString(parameters)) {
    ndbout << "Missing error number." << endl;
    return;
  }

  // Copy parameters since strtok will modify it
1556 1557
  char* newpar = my_strdup(parameters,MYF(MY_WME)); 
  My_auto_ptr<char> ap1(newpar);
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
  char* firstParameter = strtok(newpar, " ");

  int errorNo;
  if (! convert(firstParameter, errorNo)) {
    ndbout << "Expected an integer." << endl;
    return;
  }

  char* allAfterFirstParameter = strtok(NULL, "\0");
  if (! emptyString(allAfterFirstParameter)) {
    ndbout << "Nothing expected after error number." << endl;
    return;
  }

  ndb_mgm_insert_error(m_mgmsrv, processId, errorNo, NULL);
}

//*****************************************************************************
//*****************************************************************************
void 
CommandInterpreter::executeTrace(int /*processId*/,
				 const char* /*parameters*/, bool /*all*/) 
{
#if 0
  if (emptyString(parameters)) {
    ndbout << "Missing trace number." << endl;
    return;
  }

1587 1588
  char* newpar = my_strdup(parameters,MYF(MY_WME));
  My_auto_ptr<char> ap1(newpar);
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
  char* firstParameter = strtok(newpar, " ");


  int traceNo;
  if (! convert(firstParameter, traceNo)) {
    ndbout << "Expected an integer." << endl;
    return;
  }
  char* allAfterFirstParameter = strtok(NULL, "\0");  

  if (! emptyString(allAfterFirstParameter)) {
    ndbout << "Nothing expected after trace number." << endl;
    return;
  }

  int result = _mgmtSrvr.setTraceNo(processId, traceNo);
  if (result != 0) {
1606
    ndbout << get_error_text(result) << endl;
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
  }
#endif
}

//*****************************************************************************
//*****************************************************************************

void 
CommandInterpreter::executeLog(int processId,
			       const char* parameters, bool all) 
{
  struct ndb_mgm_reply reply;
  Vector<const char *> blocks;
  if (! parseBlockSpecification(parameters, blocks)) {
    return;
  }
1623
  int len=1;
1624 1625
  Uint32 i;
  for(i=0; i<blocks.size(); i++) {
1626
    len += strlen(blocks[i]) + 1;
1627
  }
1628 1629
  char * blockNames = (char*)my_malloc(len,MYF(MY_WME));
  My_auto_ptr<char> ap1(blockNames);
1630
  
1631
  blockNames[0] = 0;
1632
  for(i=0; i<blocks.size(); i++) {
1633 1634 1635 1636
    strcat(blockNames, blocks[i]);
    strcat(blockNames, "|");
  }
  
1637
  int result = ndb_mgm_log_signals(m_mgmsrv,
1638 1639 1640 1641 1642
				   processId, 
				   NDB_MGM_SIGNAL_LOG_MODE_INOUT, 
				   blockNames,
				   &reply);
  if (result != 0) {
1643 1644
    ndbout_c("Execute LOG on node %d failed.", processId);
    printError();
1645 1646 1647 1648 1649 1650 1651 1652 1653
  }
}

//*****************************************************************************
//*****************************************************************************
void 
CommandInterpreter::executeLogIn(int /* processId */,
				 const char* parameters, bool /* all */) 
{
1654
  ndbout << "Command LOGIN not implemented." << endl;
1655 1656 1657 1658 1659 1660 1661 1662
}

//*****************************************************************************
//*****************************************************************************
void 
CommandInterpreter::executeLogOut(int /*processId*/, 
				  const char* parameters, bool /*all*/) 
{
1663
  ndbout << "Command LOGOUT not implemented." << endl;
1664 1665 1666 1667 1668 1669 1670 1671
}

//*****************************************************************************
//*****************************************************************************
void 
CommandInterpreter::executeLogOff(int /*processId*/,
				  const char* parameters, bool /*all*/) 
{
1672
  ndbout << "Command LOGOFF not implemented." << endl;
1673 1674 1675 1676 1677
}

//*****************************************************************************
//*****************************************************************************
void 
1678
CommandInterpreter::executeTestOn(int processId,
1679 1680 1681 1682 1683 1684
				  const char* parameters, bool /*all*/) 
{
  if (! emptyString(parameters)) {
    ndbout << "No parameters expected to this command." << endl;
    return;
  }
1685 1686
  struct ndb_mgm_reply reply;
  int result = ndb_mgm_start_signallog(m_mgmsrv, processId, &reply);
1687
  if (result != 0) {
1688 1689
    ndbout_c("Execute TESTON failed.");
    printError();
1690 1691 1692 1693 1694 1695
  }
}

//*****************************************************************************
//*****************************************************************************
void 
1696
CommandInterpreter::executeTestOff(int processId,
1697 1698 1699 1700 1701 1702
				   const char* parameters, bool /*all*/) 
{
  if (! emptyString(parameters)) {
    ndbout << "No parameters expected to this command." << endl;
    return;
  }
1703 1704
  struct ndb_mgm_reply reply;
  int result = ndb_mgm_stop_signallog(m_mgmsrv, processId, &reply);
1705
  if (result != 0) {
1706 1707
    ndbout_c("Execute TESTOFF failed.");
    printError();
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
  }
}


//*****************************************************************************
//*****************************************************************************
void 
CommandInterpreter::executeSet(int /*processId*/, 
			       const char* parameters, bool /*all*/) 
{
  if (emptyString(parameters)) {
    ndbout << "Missing parameter name." << endl;
    return;
  }
#if 0
  // Copy parameters since strtok will modify it
1724 1725
  char* newpar = my_strdup(parameters,MYF(MY_WME));
  My_auto_ptr<char> ap1(newpar);
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
  char* configParameterName = strtok(newpar, " ");

  char* allAfterParameterName = strtok(NULL, "\0");
  if (emptyString(allAfterParameterName)) {
    ndbout << "Missing parameter value." << endl;
    return;
  }

  char* value = strtok(allAfterParameterName, " ");

  char* allAfterValue = strtok(NULL, "\0");
  if (! emptyString(allAfterValue)) {
    ndbout << "Nothing expected after parameter value." << endl;
    return;
  }

  bool configBackupFileUpdated;
  bool configPrimaryFileUpdated;
  
  // TODO The handling of the primary and backup config files should be 
  // analysed further.
  // How it should be handled if only the backup is possible to write.

  int result = _mgmtSrvr.updateConfigParam(processId, configParameterName, 
					   value, configBackupFileUpdated, 
					   configPrimaryFileUpdated);
  if (result == 0) {
    if (configBackupFileUpdated && configPrimaryFileUpdated) {
      ndbout << "The configuration is updated." << endl;
    }
    else if (configBackupFileUpdated && !configPrimaryFileUpdated) {
      ndbout << "The configuration is updated but it was only possible " 
	     << "to update the backup configuration file, not the primary." 
	     << endl;
    }
    else {
joreland@mysql.com's avatar
joreland@mysql.com committed
1762
      assert(false);
1763 1764 1765
    }
  }
  else {
1766
    ndbout << get_error_text(result) << endl;
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
    if (configBackupFileUpdated && configPrimaryFileUpdated) {
      ndbout << "The configuration files are however updated and "
	     << "the value will be used next time the process is restarted." 
	     << endl;
    }
    else if (configBackupFileUpdated && !configPrimaryFileUpdated) {
      ndbout << "It was only possible to update the backup "
	     << "configuration file, not the primary." << endl;
    }
    else if (!configBackupFileUpdated && !configPrimaryFileUpdated) {
      ndbout << "The configuration files are not updated." << endl;
    }
    else {
      // The primary is not tried to write if the write of backup file fails
joreland@mysql.com's avatar
joreland@mysql.com committed
1781
      abort();
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
    }
  }
#endif
}

//*****************************************************************************
//*****************************************************************************
void CommandInterpreter::executeGetStat(int /*processId*/,
					const char* parameters, bool /*all*/) 
{
  if (! emptyString(parameters)) {
    ndbout << "No parameters expected to this command." << endl;
    return;
  }

#if 0
  MgmtSrvr::Statistics statistics;
  int result = _mgmtSrvr.getStatistics(processId, statistics);
  if (result != 0) {
1801
    ndbout << get_error_text(result) << endl;
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
    return;
  }
#endif
  // Print statistic...
  /*
  ndbout << "Number of GETSTAT commands: " 
  << statistics._test1 << endl;
  */
}

//*****************************************************************************
//*****************************************************************************
				 
void 
CommandInterpreter::executeEventReporting(int processId,
					  const char* parameters, 
					  bool all) 
{
1820 1821 1822 1823
  if (emptyString(parameters)) {
    ndbout << "Expected argument" << endl;
    return;
  }
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
  BaseString tmp(parameters);
  Vector<BaseString> spec;
  tmp.split(spec, "=");
  if(spec.size() != 2){
    ndbout << "Invalid loglevel specification: " << parameters << endl;
    return;
  }

  spec[0].trim().ndb_toupper();
  int category = ndb_mgm_match_event_category(spec[0].c_str());
  if(category == NDB_MGM_ILLEGAL_EVENT_CATEGORY){
1835 1836
    if(!convert(spec[0].c_str(), category) ||
       category < NDB_MGM_MIN_EVENT_CATEGORY ||
1837 1838 1839
       category > NDB_MGM_MAX_EVENT_CATEGORY){
      ndbout << "Unknown category: \"" << spec[0].c_str() << "\"" << endl;
      return;
1840 1841
    }
  }
1842 1843 1844 1845

  int level;
  if (!convert(spec[1].c_str(),level))
  {
1846 1847 1848
    ndbout << "Invalid level: " << spec[1].c_str() << endl;
    return;
  }
1849 1850

  ndbout << "Executing CLUSTERLOG on node " << processId << flush;
1851

1852 1853
  struct ndb_mgm_reply reply;
  int result;
1854
  result = ndb_mgm_set_loglevel_clusterlog(m_mgmsrv, 
1855
					   processId,
1856 1857 1858
					   (ndb_mgm_event_category)category,
					   level, 
					   &reply);
1859 1860
  
  if (result != 0) {
1861
    ndbout_c(" failed."); 
1862 1863
    printError();
  } else {
1864
    ndbout_c(" OK!"); 
1865 1866 1867 1868 1869 1870
  }  
}

/*****************************************************************************
 * Backup
 *****************************************************************************/
1871
int
1872 1873 1874 1875
CommandInterpreter::executeStartBackup(char* /*parameters*/) 
{
  struct ndb_mgm_reply reply;
  unsigned int backupId;
joreland@mysql.com's avatar
joreland@mysql.com committed
1876 1877 1878

  int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_BACKUP, 0 };
  int fd = ndb_mgm_listen_event(m_mgmsrv, filter);
1879 1880 1881 1882
  int result = ndb_mgm_start_backup(m_mgmsrv, &backupId, &reply);
  if (result != 0) {
    ndbout << "Start of backup failed" << endl;
    printError();
joreland@mysql.com's avatar
joreland@mysql.com committed
1883
    close(fd);
1884
    return result;
1885
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896

  char *tmp;
  char buf[1024];
  {
    SocketInputStream in(fd);
    int count = 0;
    do {
      tmp = in.gets(buf, 1024);
      if(tmp)
      {
	ndbout << tmp;
1897
	unsigned int id;
joreland@mysql.com's avatar
joreland@mysql.com committed
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
	if(sscanf(tmp, "%*[^:]: Backup %d ", &id) == 1 && id == backupId){
	  count++;
	}
      }
    } while(count < 2);
  }

  SocketInputStream in(fd, 10);
  do {
    tmp = in.gets(buf, 1024);
    if(tmp && tmp[0] != 0)
    {
      ndbout << tmp;
    }
  } while(tmp && tmp[0] != 0);
  
  close(fd);
1915
  return 0;
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
}

void
CommandInterpreter::executeAbortBackup(char* parameters) 
{
  strtok(parameters, " ");
  struct ndb_mgm_reply reply;
  char* id = strtok(NULL, "\0");
  int bid = -1;
  if(id == 0 || sscanf(id, "%d", &bid) != 1){
    ndbout << "Invalid arguments: expected <BackupId>" << endl;
    return;
  }
  int result = ndb_mgm_abort_backup(m_mgmsrv, bid, &reply);
  if (result != 0) {
    ndbout << "Abort of backup " << bid << " failed" << endl;
    printError();
  } else {
    ndbout << "Abort of backup " << bid << " ordered" << endl;
  }
}

#ifdef HAVE_GLOBAL_REPLICATION
/*****************************************************************************
 * Global Replication
 *
 * For information about the different commands, see
 * GrepReq::Request in file signaldata/grepImpl.cpp.
 *
 * Below are commands as of 2003-07-05 (may change!):
 * START = 0,            ///< Start Global Replication (all phases)
 * START_METALOG = 1,    ///< Start Global Replication (all phases)
 * START_METASCAN = 2,   ///< Start Global Replication (all phases)
 * START_DATALOG = 3,    ///< Start Global Replication (all phases)
 * START_DATASCAN = 4,   ///< Start Global Replication (all phases)
 * START_REQUESTOR = 5,  ///< Start Global Replication (all phases)
 * ABORT = 6,            ///< Immediate stop (removes subscription)
 * SLOW_STOP = 7,        ///< Stop after finishing applying current GCI epoch
 * FAST_STOP = 8,        ///< Stop after finishing applying all PS GCI epochs
 * START_TRANSFER = 9,   ///< Start SS-PS transfer
 * STOP_TRANSFER = 10,   ///< Stop SS-PS transfer
 * START_APPLY = 11,     ///< Start applying GCI epochs in SS
 * STOP_APPLY = 12,      ///< Stop applying GCI epochs in SS
 * STATUS = 13,           ///< Status
 * START_SUBSCR = 14,
 * REMOVE_BUFFERS = 15,
 * DROP_TABLE = 16

 *****************************************************************************/

void
CommandInterpreter::executeRep(char* parameters) 
{
  if (emptyString(parameters)) {
    ndbout << helpTextRep;
    return;
  }

1974 1975
  char * line = my_strdup(parameters,MYF(MY_WME));
  My_auto_ptr<char> ap1((char*)line);
1976 1977 1978 1979 1980 1981
  char * firstToken = strtok(line, " ");
  
  struct ndb_rep_reply  reply;
  unsigned int          repId;


1982
  if (!strcasecmp(firstToken, "CONNECT")) {
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
    char * host = strtok(NULL, "\0");
    for (unsigned int i = 0; i < strlen(host); ++i) {
      host[i] = tolower(host[i]);
    }
    
    if(host == NULL)
    {
      ndbout_c("host:port must be specified.");
      return;
    }
    
    if(rep_connected) {
      if(m_repserver != NULL) {
	ndb_rep_disconnect(m_repserver);
	rep_connected = false;
      }       
    }
          
    if(m_repserver == NULL)
      m_repserver = ndb_rep_create_handle();
    if(ndb_rep_connect(m_repserver, host) < 0)
      ndbout_c("Failed to connect to %s", host); 
    else
      rep_connected=true;
    return;
    
    if(!rep_connected) {
      ndbout_c("Not connected to REP server");
    }
  }
    
  /********
   * START 
   ********/
2017
  if (!strcasecmp(firstToken, "START")) {
2018 2019 2020 2021 2022 2023
    
    unsigned int          req;
    char *startType = strtok(NULL, "\0");
    
    if (startType == NULL) {                
      req = GrepReq::START;
2024
    } else if (!strcasecmp(startType, "SUBSCRIPTION")) {  
2025
      req = GrepReq::START_SUBSCR;
2026
    } else if (!strcasecmp(startType, "METALOG")) { 
2027
      req = GrepReq::START_METALOG;
2028
    } else if (!strcasecmp(startType, "METASCAN")) {
2029
      req = GrepReq::START_METASCAN;
2030
    } else if (!strcasecmp(startType, "DATALOG")) {
2031
      req = GrepReq::START_DATALOG;
2032
    } else if (!strcasecmp(startType, "DATASCAN")) {
2033
      req = GrepReq::START_DATASCAN;
2034
    } else if (!strcasecmp(startType, "REQUESTOR")) {
2035
      req = GrepReq::START_REQUESTOR;
2036
    } else if (!strcasecmp(startType, "TRANSFER")) {
2037
      req = GrepReq::START_TRANSFER;
2038
    } else if (!strcasecmp(startType, "APPLY")) {
2039
      req = GrepReq::START_APPLY;
2040
    } else if (!strcasecmp(startType, "DELETE")) {
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059
      req = GrepReq::START_DELETE;
    } else {
      ndbout_c("Illegal argument to command 'REPLICATION START'");
      return;
    }

    int result = ndb_rep_command(m_repserver, req, &repId, &reply);
    
    if (result != 0) {
      ndbout << "Start of Global Replication failed" << endl;
    } else {
      ndbout << "Start of Global Replication ordered" << endl;
    }
    return;
  }

  /********
   * STOP
   ********/
2060
  if (!strcasecmp(firstToken, "STOP")) {    
2061 2062 2063 2064 2065 2066 2067 2068 2069
    unsigned int          req;
    char *startType = strtok(NULL, " ");
    unsigned int epoch = 0;
    
    if (startType == NULL) {                 
      /**
       * Stop immediately
       */
      req = GrepReq::STOP;
2070
    } else if (!strcasecmp(startType, "EPOCH")) {  
2071 2072 2073 2074 2075 2076 2077
      char *strEpoch = strtok(NULL, "\0");
      if(strEpoch == NULL) {
	ndbout_c("Epoch expected!");
	return;
      }
      req = GrepReq::STOP;
      epoch=atoi(strEpoch);      
2078
    } else if (!strcasecmp(startType, "SUBSCRIPTION")) {  
2079
      req = GrepReq::STOP_SUBSCR;
2080
    } else if (!strcasecmp(startType, "METALOG")) { 
2081
      req = GrepReq::STOP_METALOG;
2082
    } else if (!strcasecmp(startType, "METASCAN")) {
2083
      req = GrepReq::STOP_METASCAN;
2084
    } else if (!strcasecmp(startType, "DATALOG")) {
2085
      req = GrepReq::STOP_DATALOG;
2086
    } else if (!strcasecmp(startType, "DATASCAN")) {
2087
      req = GrepReq::STOP_DATASCAN;
2088
    } else if (!strcasecmp(startType, "REQUESTOR")) {
2089
      req = GrepReq::STOP_REQUESTOR;
2090
    } else if (!strcasecmp(startType, "TRANSFER")) {
2091
      req = GrepReq::STOP_TRANSFER;
2092
    } else if (!strcasecmp(startType, "APPLY")) {
2093
      req = GrepReq::STOP_APPLY;
2094
    } else if (!strcasecmp(startType, "DELETE")) {
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
      req = GrepReq::STOP_DELETE;
    } else {
      ndbout_c("Illegal argument to command 'REPLICATION STOP'");
      return;
    }
    int result = ndb_rep_command(m_repserver, req, &repId, &reply, epoch);
    
    if (result != 0) {
      ndbout << "Stop command failed" << endl;
    } else {
      ndbout << "Stop ordered" << endl;
    }
    return;
  }

  /*********
   * STATUS
   *********/
2113
  if (!strcasecmp(firstToken, "STATUS")) {
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
    struct rep_state repstate;
    int result = 
      ndb_rep_get_status(m_repserver, &repId, &reply, &repstate);
    
    if (result != 0) {
      ndbout << "Status request of Global Replication failed" << endl;
    } else {
      ndbout << "Status request of Global Replication ordered" << endl;
      ndbout << "See printout at one of the DB nodes" << endl;
      ndbout << "(Better status report is under development.)" << endl;
      ndbout << " SubscriptionId " << repstate.subid 
	     << " SubscriptionKey " << repstate.subkey << endl;
    }
    return;
  }

  /*********
   * QUERY (see repapi.h for querable counters)
   *********/
2133
  if (!strcasecmp(firstToken, "QUERY")) {
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
    char *query = strtok(NULL, "\0");
    int queryCounter=-1;
    if(query != NULL) {
      queryCounter = atoi(query);
    }
    struct rep_state repstate;
    unsigned repId = 0;
    int result = ndb_rep_query(m_repserver, (QueryCounter)queryCounter,
			       &repId, &reply, &repstate);
    
    if (result != 0) {
      ndbout << "Query repserver failed" << endl;
    } else {
      ndbout << "Query repserver sucessful" << endl;
      ndbout_c("repstate : QueryCounter %d, f=%d l=%d"
	       " nodegroups %d" , 
	       repstate.queryCounter,
	       repstate.first[0], repstate.last[0],
	       repstate.no_of_nodegroups );
    }
    return;
  }
}
#endif // HAVE_GLOBAL_REPLICATION

2159
template class Vector<char const*>;