CommandInterpreter.cpp 59.9 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
#include <ndb_global.h>
#include <my_sys.h>
19 20
#include <Vector.hpp>
#include <mgmapi.h>
21
#include <util/BaseString.hpp>
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

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
   */
unknown's avatar
unknown committed
41
  CommandInterpreter(const char *, int verbose);
42 43 44 45 46 47 48 49 50
  ~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
   */
51
  int execute(const char *_line, int _try_reconnect=-1, int *error= 0);
52 53 54

private:
  void printError();
55
  int execute_impl(const char *_line);
56 57 58 59 60 61 62 63 64 65 66

  /**
   *   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);

67 68 69
  void executeCommand(Vector<BaseString> &command_list,
                      unsigned command_pos,
                      int *node_ids, int no_of_nodes);
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
  /**
   *   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);
unknown's avatar
unknown committed
95
  void executeConnect(char* parameters);
96
  void executePurge(char* parameters);
unknown's avatar
unknown committed
97
  int  executeShutdown(char* parameters);
98 99 100 101 102 103
  void executeRun(char* parameters);
  void executeInfo(char* parameters);
  void executeClusterLog(char* parameters);

public:
  void executeStop(int processId, const char* parameters, bool all);
104 105
  void executeStop(Vector<BaseString> &command_list, unsigned command_pos,
                   int *node_ids, int no_of_nodes);
106 107 108 109
  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);
110 111
  void executeRestart(Vector<BaseString> &command_list, unsigned command_pos,
                      int *node_ids, int no_of_nodes);
112 113 114 115 116 117 118 119 120 121 122 123 124
  void executeLogLevel(int processId, const char* parameters, bool all);
  void executeError(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
  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;
unknown's avatar
unknown committed
157
  NdbMgmHandle m_mgmsrv2;
158
  const char *m_constr;
unknown's avatar
unknown committed
159
  bool m_connected;
unknown's avatar
unknown committed
160
  int m_verbose;
161
  int try_reconnect;
162
  int m_error;
unknown's avatar
unknown committed
163
  struct NdbThread* m_event_thread;
164
  NdbMutex *m_print_mutex;
165 166
};

167 168 169 170 171 172
struct event_thread_param {
  NdbMgmHandle *m;
  NdbMutex **p;
};

NdbMutex* print_mutex;
173 174 175 176 177 178

/*
 * Facade object for CommandInterpreter
 */

#include "ndb_mgmclient.hpp"
179
#include "ndb_mgmclient.h"
180

unknown's avatar
unknown committed
181
Ndb_mgmclient::Ndb_mgmclient(const char *host,int verbose)
182
{
unknown's avatar
unknown committed
183
  m_cmd= new CommandInterpreter(host,verbose);
184 185 186 187 188
}
Ndb_mgmclient::~Ndb_mgmclient()
{
  delete m_cmd;
}
189
int Ndb_mgmclient::execute(const char *_line, int _try_reconnect, int *error)
190
{
191
  return m_cmd->execute(_line,_try_reconnect,error);
192 193 194 195 196 197 198
}
int
Ndb_mgmclient::disconnect()
{
  return m_cmd->disconnect();
}

199 200 201 202 203
extern "C" {
  Ndb_mgmclient_handle ndb_mgmclient_handle_create(const char *connect_string)
  {
    return (Ndb_mgmclient_handle) new Ndb_mgmclient(connect_string);
  }
204
  int ndb_mgmclient_execute(Ndb_mgmclient_handle h, int argc, char** argv)
205 206 207 208 209 210
  {
    return ((Ndb_mgmclient*)h)->execute(argc, argv, 1);
  }
  int ndb_mgmclient_handle_destroy(Ndb_mgmclient_handle h)
  {
    delete (Ndb_mgmclient*)h;
unknown's avatar
unknown committed
211
    return 0;
212 213
  }
}
214 215 216
/*
 * The CommandInterpreter
 */
217 218 219 220

#include <mgmapi.h>
#include <mgmapi_debug.h>
#include <version.h>
unknown's avatar
unknown committed
221
#include <NdbAutoPtr.hpp>
222 223
#include <NdbOut.hpp>
#include <NdbSleep.h>
224
#include <NdbMem.h>
225 226 227
#include <EventLogger.hpp>
#include <signaldata/SetLogLevelOrd.hpp>
#include "MgmtErrorReporter.hpp"
228 229 230 231
#include <Parser.hpp>
#include <SocketServer.hpp>
#include <util/InputStream.hpp>
#include <util/OutputStream.hpp>
232

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

/*****************************************************************************
 * 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 VM_TRACE // DEBUG ONLY
"HELP DEBUG                             Help for debug compiled version\n"
#endif
"SHOW                                   Print information about cluster\n"
unknown's avatar
unknown committed
258
#if 0
259 260
"SHOW CONFIG                            Print configuration\n"
"SHOW PARAMETERS                        Print configuration parameters\n"
unknown's avatar
unknown committed
261
#endif
unknown's avatar
unknown committed
262 263
"START BACKUP [NOWAIT | WAIT STARTED | WAIT COMPLETED]\n"
"                                       Start backup (default WAIT COMPLETED)\n"
264
"ABORT BACKUP <backup id>               Abort backup\n"
unknown's avatar
unknown committed
265
"SHUTDOWN                               Shutdown all processes in cluster\n"
unknown's avatar
unknown committed
266 267 268
"CLUSTERLOG ON [<severity>] ...         Enable Cluster logging\n"
"CLUSTERLOG OFF [<severity>] ...        Disable Cluster logging\n"
"CLUSTERLOG TOGGLE [<severity>] ...     Toggle severity filter on/off\n"
269 270 271 272 273 274 275 276
"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"
277
"PURGE STALE SESSIONS                   Reset reserved nodeid's in the mgmt server\n"
278
"CONNECT [<connectstring>]              Connect to management server (reconnect if already connected)\n"
279 280 281 282 283 284 285 286 287
"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" 
unknown's avatar
unknown committed
288
#if 0
289 290
"SHOW CONFIG        Print configuration (in initial config file format)\n" 
"SHOW PARAMETERS    Print information about configuration parameters\n\n"
unknown's avatar
unknown committed
291
#endif
292 293 294 295 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
;

#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> 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
 */
unknown's avatar
unknown committed
343 344
CommandInterpreter::CommandInterpreter(const char *_host,int verbose) 
  : m_verbose(verbose)
345
{
346
  m_constr= _host;
unknown's avatar
unknown committed
347 348
  m_connected= false;
  m_event_thread= 0;
349
  try_reconnect = 0;
350
  m_print_mutex= NdbMutex_Create();
351 352 353 354 355 356 357
}

/*
 * Destructor
 */
CommandInterpreter::~CommandInterpreter() 
{
unknown's avatar
unknown committed
358
  disconnect();
359
  NdbMutex_Destroy(m_print_mutex);
360 361
}

362
static bool 
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
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() 
{
  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));
385 386 387 388
  if (ndb_mgm_check_connection(m_mgmsrv))
  {
    disconnect();
  }
389 390 391 392 393
}

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

unknown's avatar
unknown committed
394 395
static int do_event_thread;
static void*
396
event_thread_run(void* p)
unknown's avatar
unknown committed
397
{
398 399
  DBUG_ENTER("event_thread_run");

400 401 402
  struct event_thread_param param= *(struct event_thread_param*)p;
  NdbMgmHandle handle= *(param.m);
  NdbMutex* printmutex= *(param.p);
unknown's avatar
unknown committed
403

unknown's avatar
unknown committed
404 405 406
  int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_BACKUP,
		   1, NDB_MGM_EVENT_CATEGORY_STARTUP,
		   0 };
unknown's avatar
unknown committed
407
  int fd = ndb_mgm_listen_event(handle, filter);
408
  if (fd != NDB_INVALID_SOCKET)
unknown's avatar
unknown committed
409
  {
410
    do_event_thread= 1;
unknown's avatar
unknown committed
411 412 413 414 415 416
    char *tmp= 0;
    char buf[1024];
    SocketInputStream in(fd,10);
    do {
      if (tmp == 0) NdbSleep_MilliSleep(10);
      if((tmp = in.gets(buf, 1024)))
417 418 419
      {
	const char ping_token[]= "<PING>";
	if (memcmp(ping_token,tmp,sizeof(ping_token)-1))
420 421 422 423 424
	  if(tmp && strlen(tmp))
          {
            Guard g(printmutex);
            ndbout << tmp;
          }
425
      }
unknown's avatar
unknown committed
426
    } while(do_event_thread);
427
    NDB_CLOSE_SOCKET(fd);
unknown's avatar
unknown committed
428
  }
429 430 431 432
  else
  {
    do_event_thread= -1;
  }
unknown's avatar
unknown committed
433

434
  DBUG_RETURN(NULL);
unknown's avatar
unknown committed
435 436 437
}

bool
438
CommandInterpreter::connect()
439
{
440
  DBUG_ENTER("CommandInterpreter::connect");
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

  if(m_connected)
    DBUG_RETURN(m_connected);

  m_mgmsrv = ndb_mgm_create_handle();
  if(m_mgmsrv == NULL) {
    ndbout_c("Cannot create handle to management server.");
    exit(-1);
  }
  m_mgmsrv2 = ndb_mgm_create_handle();
  if(m_mgmsrv2 == NULL) {
    ndbout_c("Cannot create 2:nd handle to management server.");
    exit(-1);
  }

  if (ndb_mgm_set_connectstring(m_mgmsrv, m_constr))
unknown's avatar
unknown committed
457
  {
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
    printError();
    exit(-1);
  }

  if(ndb_mgm_connect(m_mgmsrv, try_reconnect-1, 5, 1))
    DBUG_RETURN(m_connected); // couldn't connect, always false

  const char *host= ndb_mgm_get_connected_host(m_mgmsrv);
  unsigned port= ndb_mgm_get_connected_port(m_mgmsrv);
  BaseString constr;
  constr.assfmt("%s:%d",host,port);
  if(!ndb_mgm_set_connectstring(m_mgmsrv2, constr.c_str()) &&
     !ndb_mgm_connect(m_mgmsrv2, try_reconnect-1, 5, 1))
  {
    DBUG_PRINT("info",("2:ndb connected to Management Server ok at: %s:%d",
                       host, port));
    assert(m_event_thread == 0);
    assert(do_event_thread == 0);
    do_event_thread= 0;
477 478 479
    struct event_thread_param p;
    p.m= &m_mgmsrv2;
    p.p= &m_print_mutex;
480
    m_event_thread = NdbThread_Create(event_thread_run,
481
                                      (void**)&p,
482 483 484 485
                                      32768,
                                      "CommandInterpreted_event_thread",
                                      NDB_THREAD_PRIO_LOW);
    if (m_event_thread != 0)
unknown's avatar
unknown committed
486
    {
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
      DBUG_PRINT("info",("Thread created ok, waiting for started..."));
      int iter= 1000; // try for 30 seconds
      while(do_event_thread == 0 &&
            iter-- > 0)
        NdbSleep_MilliSleep(30);
    }
    if (m_event_thread == 0 ||
        do_event_thread == 0 ||
        do_event_thread == -1)
    {
      DBUG_PRINT("info",("Warning, event thread startup failed, "
                         "degraded printouts as result, errno=%d",
                         errno));
      printf("Warning, event thread startup failed, "
             "degraded printouts as result, errno=%d\n", errno);
      do_event_thread= 0;
      if (m_event_thread)
504
      {
505 506 507
        void *res;
        NdbThread_WaitFor(m_event_thread, &res);
        NdbThread_Destroy(&m_event_thread);
unknown's avatar
unknown committed
508
      }
509
      ndb_mgm_disconnect(m_mgmsrv2);
unknown's avatar
unknown committed
510
    }
511
  }
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
  else
  {
    DBUG_PRINT("warning",
               ("Could not do 2:nd connect to mgmtserver for event listening"));
    DBUG_PRINT("info", ("code: %d, msg: %s",
                        ndb_mgm_get_latest_error(m_mgmsrv2),
                        ndb_mgm_get_latest_error_msg(m_mgmsrv2)));
    printf("Warning, event connect failed, degraded printouts as result\n");
    printf("code: %d, msg: %s\n",
           ndb_mgm_get_latest_error(m_mgmsrv2),
           ndb_mgm_get_latest_error_msg(m_mgmsrv2));
  }
  m_connected= true;
  DBUG_PRINT("info",("Connected to Management Server at: %s:%d", host, port));
  if (m_verbose)
  {
    printf("Connected to Management Server at: %s:%d\n",
           host, port);
  }

532
  DBUG_RETURN(m_connected);
533 534 535 536 537
}

bool 
CommandInterpreter::disconnect() 
{
538
  DBUG_ENTER("CommandInterpreter::disconnect");
539

unknown's avatar
unknown committed
540 541 542 543 544 545
  if (m_event_thread) {
    void *res;
    do_event_thread= 0;
    NdbThread_WaitFor(m_event_thread, &res);
    NdbThread_Destroy(&m_event_thread);
    m_event_thread= 0;
546
    ndb_mgm_destroy_handle(&m_mgmsrv2);
unknown's avatar
unknown committed
547 548 549
  }
  if (m_connected)
  {
550
    ndb_mgm_destroy_handle(&m_mgmsrv);
unknown's avatar
unknown committed
551
    m_connected= false;
552
  }
553
  DBUG_RETURN(true);
554 555 556 557 558
}

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

559
int 
560 561
CommandInterpreter::execute(const char *_line, int _try_reconnect,
			    int *error) 
562 563 564
{
  if (_try_reconnect >= 0)
    try_reconnect=_try_reconnect;
565 566 567
  int result= execute_impl(_line);
  if (error)
    *error= m_error;
568

569 570 571
  return result;
}

572 573 574 575 576 577 578
static void
invalid_command(const char *cmd)
{
  ndbout << "Invalid command: " << cmd << endl;
  ndbout << "Type HELP for help." << endl << endl;
}

579 580 581 582 583 584 585
int 
CommandInterpreter::execute_impl(const char *_line) 
{
  DBUG_ENTER("CommandInterpreter::execute_impl");
  DBUG_PRINT("enter",("line=\"%s\"",_line));
  m_error= 0;

586 587
  char * line;
  if(_line == NULL) {
unknown's avatar
unknown committed
588
    DBUG_RETURN(false);
589
  }
590 591
  line = my_strdup(_line,MYF(MY_WME));
  My_auto_ptr<char> ptr(line);
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

  int do_continue;
  do {
    do_continue= 0;
    BaseString::trim(line," \t");
    if (line[0] == 0 ||
	line[0] == '#')
    {
      DBUG_RETURN(true);
    }
    // for mysql client compatability remove trailing ';'
    {
      unsigned last= strlen(line)-1;
      if (line[last] == ';')
      {
	line[last]= 0;
	do_continue= 1;
      }
    }
  } while (do_continue);
612
  // if there is anything in the line proceed
613 614 615 616 617 618 619
  Vector<BaseString> command_list;
  {
    BaseString tmp(line);
    tmp.split(command_list);
    for (unsigned i= 0; i < command_list.size();)
      command_list[i].c_str()[0] ? i++ : (command_list.erase(i),0);
  }
620 621
  char* firstToken = strtok(line, " ");
  char* allAfterFirstToken = strtok(NULL, "");
622

623 624
  if (strcasecmp(firstToken, "HELP") == 0 ||
      strcasecmp(firstToken, "?") == 0) {
625
    executeHelp(allAfterFirstToken);
unknown's avatar
unknown committed
626 627
    DBUG_RETURN(true);
  }
628
  else if (strcasecmp(firstToken, "CONNECT") == 0) {
unknown's avatar
unknown committed
629 630
    executeConnect(allAfterFirstToken);
    DBUG_RETURN(true);
631
  }
632 633 634 635 636
  else if (strcasecmp(firstToken, "SLEEP") == 0) {
    if (allAfterFirstToken)
      sleep(atoi(allAfterFirstToken));
    DBUG_RETURN(true);
  }
unknown's avatar
unknown committed
637 638 639 640 641 642
  else if((strcasecmp(firstToken, "QUIT") == 0 ||
	  strcasecmp(firstToken, "EXIT") == 0 ||
	  strcasecmp(firstToken, "BYE") == 0) && 
	  allAfterFirstToken == NULL){
    DBUG_RETURN(false);
  }
unknown's avatar
unknown committed
643 644 645 646

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

647
  if (strcasecmp(firstToken, "SHOW") == 0) {
unknown's avatar
unknown committed
648
    Guard g(m_print_mutex);
649
    executeShow(allAfterFirstToken);
unknown's avatar
unknown committed
650
    DBUG_RETURN(true);
651
  }
652
  else if (strcasecmp(firstToken, "SHUTDOWN") == 0) {
unknown's avatar
unknown committed
653
    m_error= executeShutdown(allAfterFirstToken);
unknown's avatar
unknown committed
654
    DBUG_RETURN(true);
unknown's avatar
unknown committed
655
  }
656
  else if (strcasecmp(firstToken, "CLUSTERLOG") == 0){
657
    executeClusterLog(allAfterFirstToken);
unknown's avatar
unknown committed
658
    DBUG_RETURN(true);
659
  }
660
  else if(strcasecmp(firstToken, "START") == 0 &&
661
	  allAfterFirstToken != NULL &&
662 663
	  strncasecmp(allAfterFirstToken, "BACKUP", sizeof("BACKUP") - 1) == 0){
    m_error= executeStartBackup(allAfterFirstToken);
unknown's avatar
unknown committed
664
    DBUG_RETURN(true);
665
  }
666
  else if(strcasecmp(firstToken, "ABORT") == 0 &&
667
	  allAfterFirstToken != NULL &&
668
	  strncasecmp(allAfterFirstToken, "BACKUP", sizeof("BACKUP") - 1) == 0){
669
    executeAbortBackup(allAfterFirstToken);
unknown's avatar
unknown committed
670
    DBUG_RETURN(true);
671
  }
672
  else if (strcasecmp(firstToken, "PURGE") == 0) {
673
    executePurge(allAfterFirstToken);
unknown's avatar
unknown committed
674
    DBUG_RETURN(true);
675
  } 
676
  else if(strcasecmp(firstToken, "ENTER") == 0 &&
677
	  allAfterFirstToken != NULL &&
678
	  strncasecmp(allAfterFirstToken, "SINGLE USER MODE ", 
679 680
		  sizeof("SINGLE USER MODE") - 1) == 0){
    executeEnterSingleUser(allAfterFirstToken);
unknown's avatar
unknown committed
681
    DBUG_RETURN(true);
682
  }
683
  else if(strcasecmp(firstToken, "EXIT") == 0 &&
684
	  allAfterFirstToken != NULL &&
685
	  strncasecmp(allAfterFirstToken, "SINGLE USER MODE ", 
686 687
		  sizeof("SINGLE USER MODE") - 1) == 0){
    executeExitSingleUser(allAfterFirstToken);
unknown's avatar
unknown committed
688
    DBUG_RETURN(true);
689
  }
690
  else if (strcasecmp(firstToken, "ALL") == 0) {
691 692 693
    analyseAfterFirstToken(-1, allAfterFirstToken);
  } else {
    /**
694
     * First tokens should be digits, node ID's
695
     */
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
    int node_ids[MAX_NODES];
    unsigned pos;
    for (pos= 0; pos < command_list.size(); pos++)
    {
      int node_id;
      if (convert(command_list[pos].c_str(), node_id))
      {
        if (node_id <= 0) {
          ndbout << "Invalid node ID: " << command_list[pos].c_str()
                 << "." << endl;
          DBUG_RETURN(true);
        }
        node_ids[pos]= node_id;
        continue;
      }
      break;
    }
    int no_of_nodes= pos;
    if (no_of_nodes == 0)
    {
      /* No digit found */
717
      invalid_command(_line);
unknown's avatar
unknown committed
718
      DBUG_RETURN(true);
719
    }
720 721 722 723
    if (pos == command_list.size())
    {
      /* No command found */
      invalid_command(_line);
unknown's avatar
unknown committed
724
      DBUG_RETURN(true);
725
    }
726 727 728 729 730 731 732
    if (no_of_nodes == 1)
    {
      analyseAfterFirstToken(node_ids[0], allAfterFirstToken);
      DBUG_RETURN(true);
    }
    executeCommand(command_list, pos, node_ids, no_of_nodes);
    DBUG_RETURN(true);
733
  }
unknown's avatar
unknown committed
734
  DBUG_RETURN(true);
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
}


/**
 * 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
  ,{ "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)) {
770 771
    ndbout << "Expected a command after "
	   << ((processId == -1) ? "ALL." : "node ID.") << endl;
772 773 774 775 776 777 778 779 780 781
    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++){
782
    if(strcasecmp(secondToken, commands[i].command) == 0){
783 784 785 786 787 788 789
      fun = commands[i].executeFunction;
      command = commands[i].command;
      break;
    }
  }
  
  if(fun == 0){
790
    invalid_command(secondToken);
791 792 793 794 795 796 797 798
    return;
  }
  
  if(processId == -1){
    executeForAll(command, fun, allAfterSecondToken);
  } else {
    (this->*fun)(processId, allAfterSecondToken, false);
  }
unknown's avatar
unknown committed
799
  ndbout << endl;
800 801
}

802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
void
CommandInterpreter::executeCommand(Vector<BaseString> &command_list,
                                   unsigned command_pos,
                                   int *node_ids, int no_of_nodes)
{
  const char *cmd= command_list[command_pos].c_str();
  if (strcasecmp("STOP", cmd) == 0)
  {
    executeStop(command_list, command_pos+1, node_ids, no_of_nodes);
    return;
  }
  if (strcasecmp("RESTART", cmd) == 0)
  {
    executeRestart(command_list, command_pos+1, node_ids, no_of_nodes);
    return;
  }
  ndbout_c("Invalid command: '%s' after multi node id list. "
           "Expected STOP or RESTART.", cmd);
  return;
}

823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
/**
 * 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;
866
  if(strcasecmp(cmd, "STOP") == 0) {
867 868
    ndbout_c("Executing STOP on all nodes.");
    (this->*fun)(nodeId, allAfterSecondToken, true);
869
  } else if(strcasecmp(cmd, "RESTART") == 0) {
870 871 872 873 874 875
    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 {
876
    Guard g(m_print_mutex);
877
    struct ndb_mgm_cluster_state *cl= ndb_mgm_get_status(m_mgmsrv);
878 879 880 881 882
    if(cl == 0){
      ndbout_c("Unable get status from management server");
      printError();
      return;
    }
883
    NdbAutoPtr<char> ap1((char*)cl);
unknown's avatar
unknown committed
884
    while(get_next_nodeid(cl, &nodeId, NDB_MGM_NODE_TYPE_NDB))
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
      (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  
902 903
  char* newAllAfterLog = my_strdup(allAfterLog,MYF(MY_WME));
  My_auto_ptr<char> ap1(newAllAfterLog);
904 905 906 907 908
  char* firstTokenAfterLog = strtok(newAllAfterLog, " ");
  for (unsigned int i = 0; i < strlen(firstTokenAfterLog); ++i) {
    firstTokenAfterLog[i] = toupper(firstTokenAfterLog[i]);
  }
  
909
  if (strcasecmp(firstTokenAfterLog, "BLOCK") != 0) {
910 911 912 913 914 915 916 917 918 919 920 921
    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, " ");
922
  if (strcasecmp(secondTokenAfterLog, "=") != 0) {
923 924 925 926 927 928 929
    ndbout << "Unexpected value: " << secondTokenAfterLog 
	   << ". Expected =." << endl;
    return false;
  }

  char* blockName = strtok(NULL, " ");
  bool all = false;
930
  if (blockName != NULL && (strcasecmp(blockName, "ALL") == 0)) {
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
    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> = ";
unknown's avatar
unknown committed
968 969 970 971 972 973
    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;
974 975 976 977 978 979 980
      }
    }
    ndbout << endl;

    ndbout << "<level>    = " << "0 - 15" << endl;
    ndbout << "<id>       = " << "ALL | Any database node id" << endl;
    ndbout << endl;
981
  } else if (strcasecmp(parameters, "SHOW") == 0) {
982 983
    ndbout << helpTextShow;
#ifdef VM_TRACE // DEBUG ONLY
984
  } else if (strcasecmp(parameters, "DEBUG") == 0) {
985 986 987
    ndbout << helpTextDebug;
#endif
  } else {
988
    invalid_command(parameters);
989 990 991 992
  }
}


unknown's avatar
unknown committed
993 994 995 996
/*****************************************************************************
 * SHUTDOWN
 *****************************************************************************/

unknown's avatar
unknown committed
997
int
unknown's avatar
unknown committed
998 999 1000 1001 1002 1003
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();
unknown's avatar
unknown committed
1004
    return 1;
unknown's avatar
unknown committed
1005
  }
1006
  NdbAutoPtr<char> ap1((char*)state);
unknown's avatar
unknown committed
1007 1008

  int result = 0;
1009 1010
  int need_disconnect;
  result = ndb_mgm_stop3(m_mgmsrv, -1, 0, 0, &need_disconnect);
unknown's avatar
unknown committed
1011
  if (result < 0) {
1012
    ndbout << "Shutdown of NDB Cluster node(s) failed." << endl;
unknown's avatar
unknown committed
1013
    printError();
unknown's avatar
unknown committed
1014
    return result;
unknown's avatar
unknown committed
1015 1016
  }

1017
  ndbout << result << " NDB Cluster node(s) have shutdown." << endl;
unknown's avatar
unknown committed
1018

1019
  if(need_disconnect) {
1020
    ndbout << "Disconnecting to allow management server to shutdown."
1021
           << endl;
1022
    disconnect();
unknown's avatar
unknown committed
1023
  }
unknown's avatar
unknown committed
1024
  return 0;
unknown's avatar
unknown committed
1025 1026
}

1027 1028 1029 1030
/*****************************************************************************
 * SHOW
 *****************************************************************************/

unknown's avatar
unknown committed
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

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,
1057 1058
	    const char *proc_name, int no_proc, ndb_mgm_node_type type,
	    int master_id)
unknown's avatar
unknown committed
1059 1060 1061
{ 
  int i;
  ndbout << "[" << proc_name
1062 1063
	 << "(" << ndb_mgm_get_node_type_string(type) << ")]\t"
	 << no_proc << " node(s)" << endl;
unknown's avatar
unknown committed
1064 1065 1066 1067 1068 1069 1070
  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;
1071 1072
	if (hostname == 0
	    || strlen(hostname) == 0
1073
	    || strcasecmp(hostname,"0.0.0.0") == 0)
unknown's avatar
unknown committed
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
	  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;
1087
	    if (master_id && node_state->dynamic_id == master_id)
unknown's avatar
unknown committed
1088 1089 1090 1091 1092
	      ndbout << ", Master";
	  }
	}
	ndbout << ")" << endl;
      } else {
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
	ndb_mgm_first(it);
	if(ndb_mgm_find(it, CFG_NODE_ID, node_id) == 0){
	  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";
	  ndbout_c(" (not connected, accepting connect from %s)",
		   config_hostname);
	}
	else
	{
unknown's avatar
unknown committed
1104 1105 1106 1107 1108 1109 1110 1111
	  ndbout_c("Unable to find node with id: %d", node_id);
	}
      }
    }
  }
  ndbout << endl;
}

1112 1113 1114 1115 1116 1117 1118 1119 1120
void
CommandInterpreter::executePurge(char* parameters) 
{ 
  int command_ok= 0;
  do {
    if (emptyString(parameters))
      break;
    char* firstToken = strtok(parameters, " ");
    char* nextToken = strtok(NULL, " \0");
1121
    if (strcasecmp(firstToken,"STALE") == 0 &&
1122
	nextToken &&
1123
	strcasecmp(nextToken, "SESSIONS") == 0) {
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
      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");
  }
}

1151 1152
void
CommandInterpreter::executeShow(char* parameters) 
unknown's avatar
unknown committed
1153 1154
{ 
  int i;
1155 1156 1157 1158 1159 1160 1161
  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;
    }
1162
    NdbAutoPtr<char> ap1((char*)state);
1163

unknown's avatar
unknown committed
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
    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");
1176
      ndb_mgm_destroy_configuration(conf);
unknown's avatar
unknown committed
1177 1178 1179 1180
      return;
    }
    NdbAutoPtr<ndb_mgm_configuration_iterator> ptr(it);

1181
    int
1182 1183 1184 1185
      master_id= 0,
      ndb_nodes= 0,
      api_nodes= 0,
      mgm_nodes= 0;
1186

unknown's avatar
unknown committed
1187 1188 1189 1190 1191 1192 1193 1194
    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;
      }
    }
    
unknown's avatar
unknown committed
1195
    for(i=0; i < state->no_of_nodes; i++) {
1196 1197 1198 1199 1200
      switch(state->node_states[i].node_type) {
      case NDB_MGM_NODE_TYPE_API:
	api_nodes++;
	break;
      case NDB_MGM_NODE_TYPE_NDB:
unknown's avatar
unknown committed
1201 1202
	if (state->node_states[i].dynamic_id &&
	    state->node_states[i].dynamic_id < master_id)
1203
	  master_id= state->node_states[i].dynamic_id;
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
	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;
      }
    }

1215 1216
    ndbout << "Cluster Configuration" << endl
	   << "---------------------" << endl;
unknown's avatar
unknown committed
1217 1218 1219
    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);
1220
    //    ndbout << helpTextShow;
1221
    ndb_mgm_destroy_configuration(conf);
1222
    return;
1223 1224
  } else if (strcasecmp(parameters, "PROPERTIES") == 0 ||
	     strcasecmp(parameters, "PROP") == 0) {
1225 1226
    ndbout << "SHOW PROPERTIES is not yet implemented." << endl;
    //  ndbout << "_mgmtSrvr.getConfig()->print();" << endl; /* XXX */
1227 1228
  } else if (strcasecmp(parameters, "CONFIGURATION") == 0 ||
	     strcasecmp(parameters, "CONFIG") == 0){
1229 1230
    ndbout << "SHOW CONFIGURATION is not yet implemented." << endl;
    //nbout << "_mgmtSrvr.getConfig()->printConfigFile();" << endl; /* XXX */
1231 1232 1233
  } else if (strcasecmp(parameters, "PARAMETERS") == 0 ||
	     strcasecmp(parameters, "PARAMS") == 0 ||
	     strcasecmp(parameters, "PARAM") == 0) {
1234 1235 1236 1237 1238 1239 1240 1241
    ndbout << "SHOW PARAMETERS is not yet implemented." << endl;
    //    ndbout << "_mgmtSrvr.getConfig()->getConfigInfo()->print();" 
    //           << endl; /* XXX */
  } else {
    ndbout << "Invalid argument." << endl;
  }
}

unknown's avatar
unknown committed
1242 1243 1244 1245
void
CommandInterpreter::executeConnect(char* parameters) 
{
  disconnect();
1246
  if (!emptyString(parameters)) {
1247
    m_constr= BaseString(parameters).trim().c_str();
1248
  }
unknown's avatar
unknown committed
1249 1250
  connect();
}
1251 1252 1253 1254 1255 1256

//*****************************************************************************
//*****************************************************************************
void 
CommandInterpreter::executeClusterLog(char* parameters) 
{
unknown's avatar
unknown committed
1257
  DBUG_ENTER("CommandInterpreter::executeClusterLog");
unknown's avatar
unknown committed
1258
  int i;
unknown's avatar
unknown committed
1259 1260 1261 1262 1263 1264
  if (emptyString(parameters))
  {
    ndbout << "Missing argument." << endl;
    DBUG_VOID_RETURN;
  }

unknown's avatar
unknown committed
1265
  enum ndb_mgm_event_severity severity = NDB_MGM_EVENT_SEVERITY_ALL;
1266
    
unknown's avatar
unknown committed
1267 1268 1269 1270 1271
  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;
1272

unknown's avatar
unknown committed
1273
  const unsigned int *enabled= ndb_mgm_get_logfilter(m_mgmsrv);
unknown's avatar
unknown committed
1274 1275 1276 1277 1278
  if(enabled == NULL) {
    ndbout << "Couldn't get status" << endl;
    printError();
    DBUG_VOID_RETURN;
  }
1279

unknown's avatar
unknown committed
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
  /********************
   * 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: ";
unknown's avatar
unknown committed
1295 1296
    for(i = 1; i < (int)NDB_MGM_EVENT_SEVERITY_ALL; i++) {
      const char *str= ndb_mgm_get_event_severity_string((ndb_mgm_event_severity)i);
unknown's avatar
unknown committed
1297 1298 1299 1300
      if (str == 0)
      {
	DBUG_ASSERT(false);
	continue;
1301
      }
unknown's avatar
unknown committed
1302 1303
      if(enabled[i])
	ndbout << BaseString(str).ndb_toupper() << " ";
1304
    }
unknown's avatar
unknown committed
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
    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;
1322
  } else {
unknown's avatar
unknown committed
1323 1324
    ndbout << "Invalid argument." << endl;
    DBUG_VOID_RETURN;
1325
  }
unknown's avatar
unknown committed
1326 1327 1328 1329

  int res_enable;
  item = strtok_r(NULL, " ", &tmpPtr);
  if (item == NULL) {
unknown's avatar
unknown committed
1330 1331 1332 1333
    res_enable=
      ndb_mgm_set_clusterlog_severity_filter(m_mgmsrv,
					     NDB_MGM_EVENT_SEVERITY_ON,
					     enable, NULL);
unknown's avatar
unknown committed
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    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 {
unknown's avatar
unknown committed
1345
    severity= NDB_MGM_ILLEGAL_EVENT_SEVERITY;
unknown's avatar
unknown committed
1346
    if (strcasecmp(item, "ALL") == 0) {
unknown's avatar
unknown committed
1347
      severity = NDB_MGM_EVENT_SEVERITY_ALL;	
unknown's avatar
unknown committed
1348
    } else if (strcasecmp(item, "ALERT") == 0) {
unknown's avatar
unknown committed
1349
      severity = NDB_MGM_EVENT_SEVERITY_ALERT;
unknown's avatar
unknown committed
1350
    } else if (strcasecmp(item, "CRITICAL") == 0) { 
unknown's avatar
unknown committed
1351
      severity = NDB_MGM_EVENT_SEVERITY_CRITICAL;
unknown's avatar
unknown committed
1352
    } else if (strcasecmp(item, "ERROR") == 0) {
unknown's avatar
unknown committed
1353
      severity = NDB_MGM_EVENT_SEVERITY_ERROR;
unknown's avatar
unknown committed
1354
    } else if (strcasecmp(item, "WARNING") == 0) {
unknown's avatar
unknown committed
1355
      severity = NDB_MGM_EVENT_SEVERITY_WARNING;
unknown's avatar
unknown committed
1356
    } else if (strcasecmp(item, "INFO") == 0) {
unknown's avatar
unknown committed
1357
      severity = NDB_MGM_EVENT_SEVERITY_INFO;
unknown's avatar
unknown committed
1358
    } else if (strcasecmp(item, "DEBUG") == 0) {
unknown's avatar
unknown committed
1359
      severity = NDB_MGM_EVENT_SEVERITY_DEBUG;
unknown's avatar
unknown committed
1360 1361 1362
    } else if (strcasecmp(item, "OFF") == 0 ||
	       strcasecmp(item, "ON") == 0) {
      if (enable < 0) // only makes sense with toggle
unknown's avatar
unknown committed
1363
	severity = NDB_MGM_EVENT_SEVERITY_ON;
unknown's avatar
unknown committed
1364
    }
unknown's avatar
unknown committed
1365
    if (severity == NDB_MGM_ILLEGAL_EVENT_SEVERITY) {
unknown's avatar
unknown committed
1366 1367 1368 1369
      ndbout << "Invalid severity level: " << item << endl;
      DBUG_VOID_RETURN;
    }

unknown's avatar
unknown committed
1370 1371
    res_enable= ndb_mgm_set_clusterlog_severity_filter(m_mgmsrv, severity,
						       enable, NULL);
unknown's avatar
unknown committed
1372 1373 1374 1375 1376 1377
    if (res_enable < 0)
    {
      ndbout << "Couldn't set filter" << endl;
      printError();
      DBUG_VOID_RETURN;
    }
1378
    ndbout << BaseString(item).ndb_toupper().c_str() << " " << (res_enable ? "enabled":"disabled") << endl;
unknown's avatar
unknown committed
1379 1380 1381 1382 1383

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

  DBUG_VOID_RETURN;
1384 1385 1386 1387 1388 1389
} 

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

void
1390 1391
CommandInterpreter::executeStop(int processId, const char *parameters,
                                bool all) 
1392
{
1393 1394 1395 1396 1397 1398 1399
  Vector<BaseString> command_list;
  if (parameters)
  {
    BaseString tmp(parameters);
    tmp.split(command_list);
    for (unsigned i= 0; i < command_list.size();)
      command_list[i].c_str()[0] ? i++ : (command_list.erase(i),0);
1400
  }
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
  if (all)
    executeStop(command_list, 0, 0, 0);
  else
    executeStop(command_list, 0, &processId, 1);
}

void
CommandInterpreter::executeStop(Vector<BaseString> &command_list,
                                unsigned command_pos,
                                int *node_ids, int no_of_nodes)
{
1412
  int need_disconnect;
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
  int abort= 0;
  for (; command_pos < command_list.size(); command_pos++)
  {
    const char *item= command_list[command_pos].c_str();
    if (strcasecmp(item, "-A") == 0)
    {
      abort= 1;
      continue;
    }
    ndbout_c("Invalid option: %s. Expecting -A after STOP",
             item);
    return;
  }

1427 1428
  int result= ndb_mgm_stop3(m_mgmsrv, no_of_nodes, node_ids, abort,
                            &need_disconnect);
1429 1430 1431
  if (result < 0)
  {
    ndbout_c("Shutdown failed.");
1432
    printError();
1433 1434 1435 1436 1437 1438
  }
  else
  {
    if (node_ids == 0)
      ndbout_c("NDB Cluster has shutdown.");
    else
1439
    {
1440 1441
      ndbout << "Node";
      for (int i= 0; i < no_of_nodes; i++)
1442
          ndbout << " " << node_ids[i];
1443
      ndbout_c(" has shutdown.");
1444
    }
1445
  }
1446 1447 1448 1449 1450 1451 1452

  if(need_disconnect)
  {
    ndbout << "Disconnecting to allow Management Server to shutdown" << endl;
    disconnect();
  }

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
}

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 {
1475 1476
    ndbout_c("Single user mode entered");
    ndbout_c("Access is granted for API node %d only.", nodeId);
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
  }
}

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.");
1489
    ndbout_c("Use ALL STATUS or SHOW to see when single user mode has been exited.");
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
  }
}

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,
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
				   bool all)
{
  Vector<BaseString> command_list;
  if (parameters)
  {
    BaseString tmp(parameters);
    tmp.split(command_list);
    for (unsigned i= 0; i < command_list.size();)
      command_list[i].c_str()[0] ? i++ : (command_list.erase(i),0);
  }
  if (all)
    executeRestart(command_list, 0, 0, 0);
  else
    executeRestart(command_list, 0, &processId, 1);
}

void
CommandInterpreter::executeRestart(Vector<BaseString> &command_list,
                                   unsigned command_pos,
                                   int *node_ids, int no_of_nodes)
1538 1539
{
  int result;
1540 1541 1542
  int nostart= 0;
  int initialstart= 0;
  int abort= 0;
1543
  int need_disconnect= 0;
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561

  for (; command_pos < command_list.size(); command_pos++)
  {
    const char *item= command_list[command_pos].c_str();
    if (strcasecmp(item, "-N") == 0)
    {
      nostart= 1;
      continue;
    }
    if (strcasecmp(item, "-I") == 0)
    {
      initialstart= 1;
      continue;
    }
    if (strcasecmp(item, "-A") == 0)
    {
      abort= 1;
      continue;
1562
    }
1563 1564 1565
    ndbout_c("Invalid option: %s. Expecting -A,-N or -I after RESTART",
             item);
    return;
1566 1567
  }

1568 1569 1570
  result= ndb_mgm_restart3(m_mgmsrv, no_of_nodes, node_ids,
                           initialstart, nostart, abort, &need_disconnect);

1571
  if (result <= 0) {
1572
    ndbout_c("Restart failed.");
1573
    printError();
1574 1575 1576 1577 1578 1579
  }
  else
  {
    if (node_ids == 0)
      ndbout_c("NDB Cluster is being restarted.");
    else
1580
    {
1581 1582 1583 1584
      ndbout << "Node";
      for (int i= 0; i < no_of_nodes; i++)
        ndbout << " " << node_ids[i];
      ndbout_c(" is being restarted");
1585
    }
1586 1587
    if(need_disconnect)
      disconnect();
1588
  }
1589 1590 1591 1592 1593 1594
}

void
CommandInterpreter::executeDumpState(int processId, const char* parameters,
				     bool all) 
{
unknown's avatar
unknown committed
1595
  if(emptyString(parameters)){
1596 1597 1598 1599 1600 1601 1602
    ndbout << "Expected argument" << endl;
    return;
  }

  Uint32 no = 0;
  int pars[25];
  
1603 1604
  char * tmpString = my_strdup(parameters,MYF(MY_WME));
  My_auto_ptr<char> ap1(tmpString);
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
  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)) {
unknown's avatar
unknown committed
1634
    ndbout_c("No parameters expected to this command.");
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
    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;
  }
1649
  NdbAutoPtr<char> ap1((char*)cl);
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661

  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;

unknown's avatar
unknown committed
1662
  ndbout << "Node " << processId << ": " << status_string(status);
1663 1664
  switch(status){
  case NDB_MGM_NODE_STATUS_STARTING:
unknown's avatar
unknown committed
1665
    ndbout << " (Phase " << startPhase << ")";
1666 1667
    break;
  case NDB_MGM_NODE_STATUS_SHUTTING_DOWN:
unknown's avatar
unknown committed
1668
    ndbout << " (Phase " << startPhase << ")";
1669 1670 1671 1672 1673 1674 1675 1676 1677
    break;
  default:
    break;
  }
  if(status != NDB_MGM_NODE_STATUS_NO_CONTACT)
    ndbout_c(" (Version %d.%d.%d)", 
	     getMajor(version) ,
	     getMinor(version),
	     getBuild(version));
unknown's avatar
unknown committed
1678 1679
  else
    ndbout << endl;
1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
}


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

void 
CommandInterpreter::executeLogLevel(int processId, const char* parameters, 
				    bool all) 
{
  (void) all;
unknown's avatar
unknown committed
1691 1692 1693 1694
  if (emptyString(parameters)) {
    ndbout << "Expected argument" << endl;
    return;
  } 
1695 1696 1697 1698 1699 1700 1701
  BaseString tmp(parameters);
  Vector<BaseString> spec;
  tmp.split(spec, "=");
  if(spec.size() != 2){
    ndbout << "Invalid loglevel specification: " << parameters << endl;
    return;
  }
1702

1703 1704 1705 1706 1707 1708 1709 1710
  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;
1711 1712
    }
  }
1713 1714 1715 1716 1717 1718 1719
  
  int level = atoi(spec[1].c_str());
  if(level < 0 || level > 15){
    ndbout << "Invalid level: " << spec[1].c_str() << endl;
    return;
  }
  
unknown's avatar
unknown committed
1720 1721
  ndbout << "Executing LOGLEVEL on node " << processId << flush;

1722 1723 1724
  struct ndb_mgm_reply reply;
  int result;
  result = ndb_mgm_set_loglevel_node(m_mgmsrv, 
1725 1726
				     processId,
				     (ndb_mgm_event_category)category,
1727 1728
				     level, 
				     &reply);
1729
  
1730
  if (result < 0) {
unknown's avatar
unknown committed
1731
    ndbout_c(" failed.");
1732 1733
    printError();
  } else {
unknown's avatar
unknown committed
1734
    ndbout_c(" OK!");
1735
  }  
1736
  
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
}

//*****************************************************************************
//*****************************************************************************
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
1750 1751
  char* newpar = my_strdup(parameters,MYF(MY_WME)); 
  My_auto_ptr<char> ap1(newpar);
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
  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::executeLog(int processId,
			       const char* parameters, bool all) 
{
  struct ndb_mgm_reply reply;
  Vector<const char *> blocks;
  if (! parseBlockSpecification(parameters, blocks)) {
    return;
  }
1781
  int len=1;
unknown's avatar
unknown committed
1782 1783
  Uint32 i;
  for(i=0; i<blocks.size(); i++) {
1784
    len += strlen(blocks[i]) + 1;
1785
  }
1786 1787
  char * blockNames = (char*)my_malloc(len,MYF(MY_WME));
  My_auto_ptr<char> ap1(blockNames);
1788
  
1789
  blockNames[0] = 0;
unknown's avatar
unknown committed
1790
  for(i=0; i<blocks.size(); i++) {
1791 1792 1793 1794
    strcat(blockNames, blocks[i]);
    strcat(blockNames, "|");
  }
  
1795
  int result = ndb_mgm_log_signals(m_mgmsrv,
1796 1797 1798 1799 1800
				   processId, 
				   NDB_MGM_SIGNAL_LOG_MODE_INOUT, 
				   blockNames,
				   &reply);
  if (result != 0) {
1801 1802
    ndbout_c("Execute LOG on node %d failed.", processId);
    printError();
1803 1804 1805 1806 1807 1808 1809 1810 1811
  }
}

//*****************************************************************************
//*****************************************************************************
void 
CommandInterpreter::executeLogIn(int /* processId */,
				 const char* parameters, bool /* all */) 
{
1812
  ndbout << "Command LOGIN not implemented." << endl;
1813 1814 1815 1816 1817 1818 1819 1820
}

//*****************************************************************************
//*****************************************************************************
void 
CommandInterpreter::executeLogOut(int /*processId*/, 
				  const char* parameters, bool /*all*/) 
{
1821
  ndbout << "Command LOGOUT not implemented." << endl;
1822 1823 1824 1825 1826 1827 1828 1829
}

//*****************************************************************************
//*****************************************************************************
void 
CommandInterpreter::executeLogOff(int /*processId*/,
				  const char* parameters, bool /*all*/) 
{
1830
  ndbout << "Command LOGOFF not implemented." << endl;
1831 1832 1833 1834 1835
}

//*****************************************************************************
//*****************************************************************************
void 
1836
CommandInterpreter::executeTestOn(int processId,
1837 1838 1839 1840 1841 1842
				  const char* parameters, bool /*all*/) 
{
  if (! emptyString(parameters)) {
    ndbout << "No parameters expected to this command." << endl;
    return;
  }
1843 1844
  struct ndb_mgm_reply reply;
  int result = ndb_mgm_start_signallog(m_mgmsrv, processId, &reply);
1845
  if (result != 0) {
1846 1847
    ndbout_c("Execute TESTON failed.");
    printError();
1848 1849 1850 1851 1852 1853
  }
}

//*****************************************************************************
//*****************************************************************************
void 
1854
CommandInterpreter::executeTestOff(int processId,
1855 1856 1857 1858 1859 1860
				   const char* parameters, bool /*all*/) 
{
  if (! emptyString(parameters)) {
    ndbout << "No parameters expected to this command." << endl;
    return;
  }
1861 1862
  struct ndb_mgm_reply reply;
  int result = ndb_mgm_stop_signallog(m_mgmsrv, processId, &reply);
1863
  if (result != 0) {
1864 1865
    ndbout_c("Execute TESTOFF failed.");
    printError();
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881
  }
}


//*****************************************************************************
//*****************************************************************************
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
1882 1883
  char* newpar = my_strdup(parameters,MYF(MY_WME));
  My_auto_ptr<char> ap1(newpar);
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
  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 {
unknown's avatar
unknown committed
1920
      assert(false);
1921 1922 1923
    }
  }
  else {
1924
    ndbout << get_error_text(result) << endl;
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
    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
unknown's avatar
unknown committed
1939
      abort();
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
    }
  }
#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) {
1959
    ndbout << get_error_text(result) << endl;
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
    return;
  }
#endif
  // Print statistic...
  /*
  ndbout << "Number of GETSTAT commands: " 
  << statistics._test1 << endl;
  */
}

//*****************************************************************************
//*****************************************************************************
				 
void 
CommandInterpreter::executeEventReporting(int processId,
					  const char* parameters, 
					  bool all) 
{
unknown's avatar
unknown committed
1978 1979 1980 1981
  if (emptyString(parameters)) {
    ndbout << "Expected argument" << endl;
    return;
  }
1982
  BaseString tmp(parameters);
1983 1984
  Vector<BaseString> specs;
  tmp.split(specs, " ");
1985

1986 1987 1988 1989 1990 1991 1992
  for (int i=0; i < specs.size(); i++)
  {
    Vector<BaseString> spec;
    specs[i].split(spec, "=");
    if(spec.size() != 2){
      ndbout << "Invalid loglevel specification: " << specs[i] << endl;
      continue;
1993
    }
unknown's avatar
unknown committed
1994

1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
    spec[0].trim().ndb_toupper();
    int category = ndb_mgm_match_event_category(spec[0].c_str());
    if(category == NDB_MGM_ILLEGAL_EVENT_CATEGORY){
      if(!convert(spec[0].c_str(), category) ||
	 category < NDB_MGM_MIN_EVENT_CATEGORY ||
	 category > NDB_MGM_MAX_EVENT_CATEGORY){
	ndbout << "Unknown category: \"" << spec[0].c_str() << "\"" << endl;
	continue;
      }
    }
unknown's avatar
unknown committed
2005

2006 2007 2008 2009 2010 2011
    int level;
    if (!convert(spec[1].c_str(),level))
    {
      ndbout << "Invalid level: " << spec[1].c_str() << endl;
      continue;
    }
2012

2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
    ndbout << "Executing CLUSTERLOG " << spec[0] << "=" << spec[1]
	   << " on node " << processId << flush;

    struct ndb_mgm_reply reply;
    int result;
    result = ndb_mgm_set_loglevel_clusterlog(m_mgmsrv, 
					     processId,
					     (ndb_mgm_event_category)category,
					     level, 
					     &reply);
2023
  
2024 2025 2026 2027 2028 2029 2030
    if (result != 0) {
      ndbout_c(" failed."); 
      printError();
    } else {
      ndbout_c(" OK!"); 
    }
  }
2031 2032 2033 2034 2035
}

/*****************************************************************************
 * Backup
 *****************************************************************************/
2036
int
unknown's avatar
unknown committed
2037
CommandInterpreter::executeStartBackup(char* parameters)
2038 2039 2040
{
  struct ndb_mgm_reply reply;
  unsigned int backupId;
unknown's avatar
unknown committed
2041
#if 0
unknown's avatar
unknown committed
2042 2043
  int filter[] = { 15, NDB_MGM_EVENT_CATEGORY_BACKUP, 0 };
  int fd = ndb_mgm_listen_event(m_mgmsrv, filter);
unknown's avatar
unknown committed
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
  if (fd < 0)
  {
    ndbout << "Initializing start of backup failed" << endl;
    printError();
    return fd;
  }
#endif
  Vector<BaseString> args;
  {
    BaseString(parameters).split(args);
    for (unsigned i= 0; i < args.size(); i++)
      if (args[i].length() == 0)
	args.erase(i--);
      else
	args[i].ndb_toupper();
  }
  int sz= args.size();

  int result;
  if (sz == 2 &&
      args[1] == "NOWAIT")
  {
    result = ndb_mgm_start_backup(m_mgmsrv, 0, &backupId, &reply);
  }
  else if (sz == 1 ||
	   (sz == 3 &&
	    args[1] == "WAIT" &&
	    args[2] == "COMPLETED"))
  {
    ndbout_c("Waiting for completed, this may take several minutes");
    result = ndb_mgm_start_backup(m_mgmsrv, 2, &backupId, &reply);
  }
  else if (sz == 3 &&
	   args[1] == "WAIT" &&
	   args[2] == "STARTED")
  {
    ndbout_c("Waiting for started, this may take several minutes");
    result = ndb_mgm_start_backup(m_mgmsrv, 1, &backupId, &reply);
  }
  else
  {
    invalid_command(parameters);
    return -1;
  }

2089 2090 2091
  if (result != 0) {
    ndbout << "Start of backup failed" << endl;
    printError();
unknown's avatar
unknown committed
2092
#if 0
unknown's avatar
unknown committed
2093
    close(fd);
unknown's avatar
unknown committed
2094
#endif
2095
    return result;
2096
  }
unknown's avatar
unknown committed
2097 2098
#if 0
  ndbout_c("Waiting for completed, this may take several minutes");
unknown's avatar
unknown committed
2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
  char *tmp;
  char buf[1024];
  {
    SocketInputStream in(fd);
    int count = 0;
    do {
      tmp = in.gets(buf, 1024);
      if(tmp)
      {
	ndbout << tmp;
unknown's avatar
unknown committed
2109
	unsigned int id;
unknown's avatar
unknown committed
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
	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);
unknown's avatar
unknown committed
2125

unknown's avatar
unknown committed
2126
  close(fd);
unknown's avatar
unknown committed
2127
#endif  
2128
  return 0;
2129 2130 2131 2132 2133 2134
}

void
CommandInterpreter::executeAbortBackup(char* parameters) 
{
  int bid = -1;
unknown's avatar
unknown committed
2135 2136 2137 2138 2139 2140 2141 2142 2143
  struct ndb_mgm_reply reply;
  if (emptyString(parameters))
    goto executeAbortBackupError1;

  {
    strtok(parameters, " ");
    char* id = strtok(NULL, "\0");
    if(id == 0 || sscanf(id, "%d", &bid) != 1)
      goto executeAbortBackupError1;
2144
  }
unknown's avatar
unknown committed
2145 2146 2147 2148 2149 2150 2151 2152
  {
    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;
    }
2153
  }
unknown's avatar
unknown committed
2154 2155 2156 2157
  return;
 executeAbortBackupError1:
  ndbout << "Invalid arguments: expected <BackupId>" << endl;
  return;
2158 2159
}

unknown's avatar
unknown committed
2160
template class Vector<char const*>;