MgmtSrvr.cpp 79.1 KB
Newer Older
1 2 3 4
/* 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
5
   the Free Software Foundation; version 2 of the License.
6 7 8 9 10 11 12 13 14 15

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

16
#include <ndb_global.h>
17
#include <my_pthread.h>
18

19 20
#include "MgmtSrvr.hpp"
#include "MgmtErrorReporter.hpp"
21
#include <ConfigRetriever.hpp>
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

#include <NdbOut.hpp>
#include <NdbApiSignal.hpp>
#include <kernel_types.h>
#include <RefConvert.hpp>
#include <BlockNumbers.h>
#include <GlobalSignalNumbers.h>
#include <signaldata/TestOrd.hpp>
#include <signaldata/TamperOrd.hpp>
#include <signaldata/StartOrd.hpp>
#include <signaldata/ApiVersion.hpp>
#include <signaldata/ResumeReq.hpp>
#include <signaldata/SetLogLevelOrd.hpp>
#include <signaldata/EventSubscribeReq.hpp>
#include <signaldata/EventReport.hpp>
#include <signaldata/DumpStateOrd.hpp>
#include <signaldata/BackupSignalData.hpp>
#include <signaldata/ManagementServer.hpp>
40 41
#include <signaldata/NFCompleteRep.hpp>
#include <signaldata/NodeFailRep.hpp>
42
#include <signaldata/AllocNodeId.hpp>
43 44 45 46 47
#include <NdbSleep.h>
#include <EventLogger.hpp>
#include <DebuggerNames.hpp>
#include <ndb_version.h>

tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
48
#include <SocketServer.hpp>
49 50
#include <NdbConfig.h>

51 52
#include <NdbAutoPtr.hpp>

53 54
#include <ndberror.h>

55 56 57
#include <mgmapi.h>
#include <mgmapi_configuration.hpp>
#include <mgmapi_config_parameters.h>
joreland@mysql.com's avatar
joreland@mysql.com committed
58
#include <m_string.h>
59

60 61
#include <SignalSender.hpp>

62 63 64 65 66 67 68
//#define MGM_SRV_DEBUG
#ifdef MGM_SRV_DEBUG
#define DEBUG(x) do ndbout << x << endl; while(0)
#else
#define DEBUG(x)
#endif

69 70 71 72 73 74 75 76 77 78
#define INIT_SIGNAL_SENDER(ss,nodeId) \
  SignalSender ss(theFacade); \
  ss.lock(); /* lock will be released on exit */ \
  {\
    int result = okToSendTo(nodeId, true);\
    if (result != 0) {\
      return result;\
    }\
  }

79
extern int g_no_nodeid_checks;
80 81 82 83 84 85 86 87 88 89 90 91
extern my_bool opt_core;

static void require(bool v)
{
  if(!v)
  {
    if (opt_core)
      abort();
    else
      exit(-1);
  }
}
tomas@poseidon.(none)'s avatar
tomas@poseidon.(none) committed
92

93 94 95 96 97 98 99 100
void *
MgmtSrvr::logLevelThread_C(void* m)
{
  MgmtSrvr *mgm = (MgmtSrvr*)m;
  mgm->logLevelThreadRun();
  return 0;
}

101
extern EventLogger g_eventLogger;
102

103
#ifdef NOT_USED
joreland@mysql.com's avatar
joreland@mysql.com committed
104 105 106 107 108 109 110 111 112
static NdbOut&
operator<<(NdbOut& out, const LogLevel & ll)
{
  out << "[LogLevel: ";
  for(size_t i = 0; i<LogLevel::LOGLEVEL_CATEGORIES; i++)
    out << ll.getLogLevel((LogLevel::EventCategory)i) << " ";
  out << "]";
  return out;
}
113
#endif
joreland@mysql.com's avatar
joreland@mysql.com committed
114

115 116 117 118
void
MgmtSrvr::logLevelThreadRun() 
{
  while (!_isStopThread) {
joreland@mysql.com's avatar
joreland@mysql.com committed
119 120 121 122
    /**
     * Handle started nodes
     */
    m_started_nodes.lock();
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    if (m_started_nodes.size() > 0)
    {
      // calculate max log level
      EventSubscribeReq req;
      {
        LogLevel tmp;
        m_event_listner.lock();
        for(int i = m_event_listner.m_clients.size() - 1; i >= 0; i--)
          tmp.set_max(m_event_listner[i].m_logLevel);
        m_event_listner.unlock();
        req = tmp;
      }
      req.blockRef = _ownReference;
      while (m_started_nodes.size() > 0)
      {
        Uint32 node = m_started_nodes[0];
        m_started_nodes.erase(0, false);
        m_started_nodes.unlock();
141

tomas@poseidon.mysql.com's avatar
tomas@poseidon.mysql.com committed
142 143 144 145 146
        if (setEventReportingLevelImpl(node, req))
	{
	  ndbout_c("setEventReportingLevelImpl(%d): failed", node);
	}
	
147 148 149 150 151 152 153
        SetLogLevelOrd ord;
        ord = m_nodeLogLevel[node];
        setNodeLogLevelImpl(node, ord);

        m_started_nodes.lock();
      }
    }
joreland@mysql.com's avatar
joreland@mysql.com committed
154 155 156
    m_started_nodes.unlock();
    
    m_log_level_requests.lock();
157 158 159
    while (m_log_level_requests.size() > 0)
    {
      EventSubscribeReq req = m_log_level_requests[0];
joreland@mysql.com's avatar
joreland@mysql.com committed
160 161
      m_log_level_requests.erase(0, false);
      m_log_level_requests.unlock();
162

tomas@poseidon.mysql.com's avatar
tomas@poseidon.mysql.com committed
163 164
      if(req.blockRef == 0)
      {
joreland@mysql.com's avatar
joreland@mysql.com committed
165
	req.blockRef = _ownReference;
tomas@poseidon.mysql.com's avatar
tomas@poseidon.mysql.com committed
166 167 168 169 170 171 172
	if (setEventReportingLevelImpl(0, req))
	{
	  ndbout_c("setEventReportingLevelImpl: failed 2!");
	}
      } 
      else 
      {
173 174
        SetLogLevelOrd ord;
        ord = req;
joreland@mysql.com's avatar
joreland@mysql.com committed
175 176 177 178 179
	setNodeLogLevelImpl(req.blockRef, ord);
      }
      m_log_level_requests.lock();
    }      
    m_log_level_requests.unlock();
180
    NdbSleep_MilliSleep(_logLevelThreadSleep);  
joreland@mysql.com's avatar
joreland@mysql.com committed
181
  }
182 183 184 185 186
}

void
MgmtSrvr::startEventLog() 
{
187 188
  NdbMutex_Lock(m_configMutex);

189
  g_eventLogger.setCategory("MgmSrvr");
190

191 192 193 194 195 196
  ndb_mgm_configuration_iterator 
    iter(* _config->m_configValues, CFG_SECTION_NODE);

  if(iter.find(CFG_NODE_ID, _ownNodeId) != 0){
    NdbMutex_Unlock(m_configMutex);
    return;
197 198 199
  }
  
  const char * tmp;
200 201
  char errStr[100];
  int err= 0;
202
  BaseString logdest;
203 204 205
  char *clusterLog= NdbConfig_ClusterLogFileName(_ownNodeId);
  NdbAutoPtr<char> tmp_aptr(clusterLog);

206
  if(iter.get(CFG_LOG_DESTINATION, &tmp) == 0){
207 208
    logdest.assign(tmp);
  }
209
  NdbMutex_Unlock(m_configMutex);
210
  
211
  if(logdest.length() == 0 || logdest == "") {
212 213
    logdest.assfmt("FILE:filename=%s,maxsize=1000000,maxfiles=6", 
		   clusterLog);
214
  }
215 216
  errStr[0]='\0';
  if(!g_eventLogger.addHandler(logdest, &err, sizeof(errStr), errStr)) {
217
    ndbout << "Warning: could not add log destination \""
218 219 220 221 222 223 224 225
           << logdest.c_str() << "\". Reason: ";
    if(err)
      ndbout << strerror(err);
    if(err && errStr[0]!='\0')
      ndbout << ", ";
    if(errStr[0]!='\0')
      ndbout << errStr;
    ndbout << endl;
226 227 228 229 230 231 232 233 234 235 236 237 238
  }
}

void 
MgmtSrvr::stopEventLog() 
{
  // Nothing yet
}

class ErrorItem 
{
public:
  int _errorCode;
joreland@mysql.com's avatar
joreland@mysql.com committed
239
  const char * _errorText;
240 241 242
};

bool
243
MgmtSrvr::setEventLogFilter(int severity, int enable)
244 245
{
  Logger::LoggerLevel level = (Logger::LoggerLevel)severity;
246
  if (enable > 0) {
247
    g_eventLogger.enable(level);
248
  } else if (enable == 0) {
249 250 251
    g_eventLogger.disable(level);
  } else if (g_eventLogger.isEnable(level)) {
    g_eventLogger.disable(level);
252
  } else {
253
    g_eventLogger.enable(level);
254
  }
255
  return g_eventLogger.isEnable(level);
256 257 258 259 260
}

bool 
MgmtSrvr::isEventLogFilterEnabled(int severity) 
{
261
  return g_eventLogger.isEnable((Logger::LoggerLevel)severity);
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
}

static ErrorItem errorTable[] = 
{
  {MgmtSrvr::NO_CONTACT_WITH_PROCESS, "No contact with the process (dead ?)."},
  {MgmtSrvr::PROCESS_NOT_CONFIGURED, "The process is not configured."},
  {MgmtSrvr::WRONG_PROCESS_TYPE, 
   "The process has wrong type. Expected a DB process."},
  {MgmtSrvr::COULD_NOT_ALLOCATE_MEMORY, "Could not allocate memory."},
  {MgmtSrvr::SEND_OR_RECEIVE_FAILED, "Send to process or receive failed."},
  {MgmtSrvr::INVALID_LEVEL, "Invalid level. Should be between 1 and 30."},
  {MgmtSrvr::INVALID_ERROR_NUMBER, "Invalid error number. Should be >= 0."},
  {MgmtSrvr::INVALID_TRACE_NUMBER, "Invalid trace number."},
  {MgmtSrvr::NOT_IMPLEMENTED, "Not implemented."},
  {MgmtSrvr::INVALID_BLOCK_NAME, "Invalid block name"},

  {MgmtSrvr::CONFIG_PARAM_NOT_EXIST, 
   "The configuration parameter does not exist for the process type."},
  {MgmtSrvr::CONFIG_PARAM_NOT_UPDATEABLE, 
   "The configuration parameter is not possible to update."},
  {MgmtSrvr::VALUE_WRONG_FORMAT_INT_EXPECTED, 
   "Incorrect value. Expected integer."},
  {MgmtSrvr::VALUE_TOO_LOW, "Value is too low."},
  {MgmtSrvr::VALUE_TOO_HIGH, "Value is too high."},
  {MgmtSrvr::VALUE_WRONG_FORMAT_BOOL_EXPECTED, 
   "Incorrect value. Expected TRUE or FALSE."},

  {MgmtSrvr::CONFIG_FILE_OPEN_WRITE_ERROR, 
   "Could not open configuration file for writing."},
  {MgmtSrvr::CONFIG_FILE_OPEN_READ_ERROR, 
   "Could not open configuration file for reading."},
  {MgmtSrvr::CONFIG_FILE_WRITE_ERROR, 
   "Write error when writing configuration file."},
  {MgmtSrvr::CONFIG_FILE_READ_ERROR, 
   "Read error when reading configuration file."},
  {MgmtSrvr::CONFIG_FILE_CLOSE_ERROR, "Could not close configuration file."},

  {MgmtSrvr::CONFIG_CHANGE_REFUSED_BY_RECEIVER, 
   "The change was refused by the receiving process."},
  {MgmtSrvr::COULD_NOT_SYNC_CONFIG_CHANGE_AGAINST_PHYSICAL_MEDIUM, 
   "The change could not be synced against physical medium."},
  {MgmtSrvr::CONFIG_FILE_CHECKSUM_ERROR, 
   "The config file is corrupt. Checksum error."},
  {MgmtSrvr::NOT_POSSIBLE_TO_SEND_CONFIG_UPDATE_TO_PROCESS_TYPE, 
   "It is not possible to send an update of a configuration variable "
   "to this kind of process."},
308 309 310 311
  {MgmtSrvr::NODE_SHUTDOWN_IN_PROGESS, "Node shutdown in progress" },
  {MgmtSrvr::SYSTEM_SHUTDOWN_IN_PROGRESS, "System shutdown in progress" },
  {MgmtSrvr::NODE_SHUTDOWN_WOULD_CAUSE_SYSTEM_CRASH,
   "Node shutdown would cause system crash" },
312 313
  {MgmtSrvr::UNSUPPORTED_NODE_SHUTDOWN,
   "Unsupported multi node shutdown. Abort option required." },
314 315 316
  {MgmtSrvr::NODE_NOT_API_NODE, "The specified node is not an API node." },
  {MgmtSrvr::OPERATION_NOT_ALLOWED_START_STOP, 
   "Operation not allowed while nodes are starting or stopping."},
317 318 319 320 321 322 323
  {MgmtSrvr::NO_CONTACT_WITH_DB_NODES, "No contact with database nodes" }
};

int MgmtSrvr::translateStopRef(Uint32 errCode)
{
  switch(errCode){
  case StopRef::NodeShutdownInProgress:
324
    return NODE_SHUTDOWN_IN_PROGESS;
325 326
    break;
  case StopRef::SystemShutdownInProgress:
327
    return SYSTEM_SHUTDOWN_IN_PROGRESS;
328 329
    break;
  case StopRef::NodeShutdownWouldCauseSystemCrash:
330
    return NODE_SHUTDOWN_WOULD_CAUSE_SYSTEM_CRASH;
331
    break;
332 333 334
  case StopRef::UnsupportedNodeShutdown:
    return UNSUPPORTED_NODE_SHUTDOWN;
    break;
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
  }
  return 4999;
}

static int noOfErrorCodes = sizeof(errorTable) / sizeof(ErrorItem);

int 
MgmtSrvr::getNodeCount(enum ndb_mgm_node_type type) const 
{
  int count = 0;
  NodeId nodeId = 0;

  while (getNextNodeId(&nodeId, type)) {
    count++;
  }
  return count;
}

tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
353
int 
354 355 356
MgmtSrvr::getPort() const
{
  if(NdbMutex_Lock(m_configMutex))
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
357 358
    return 0;

359 360 361 362
  ndb_mgm_configuration_iterator 
    iter(* _config->m_configValues, CFG_SECTION_NODE);

  if(iter.find(CFG_NODE_ID, getOwnNodeId()) != 0){
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
363 364 365
    ndbout << "Could not retrieve configuration for Node " 
	   << getOwnNodeId() << " in config file." << endl 
	   << "Have you set correct NodeId for this node?" << endl;
366
    NdbMutex_Unlock(m_configMutex);
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
367 368 369 370
    return 0;
  }

  unsigned type;
371
  if(iter.get(CFG_TYPE_OF_SECTION, &type) != 0 ||
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
372 373 374 375
     type != NODE_TYPE_MGM){
    ndbout << "Local node id " << getOwnNodeId()
	   << " is not defined as management server" << endl
	   << "Have you set correct NodeId for this node?" << endl;
376
    NdbMutex_Unlock(m_configMutex);
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
377 378 379 380
    return 0;
  }
  
  Uint32 port = 0;
381
  if(iter.get(CFG_MGM_PORT, &port) != 0){
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
382
    ndbout << "Could not find PortNumber in the configuration file." << endl;
383
    NdbMutex_Unlock(m_configMutex);
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
384 385
    return 0;
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
386

387 388
  NdbMutex_Unlock(m_configMutex);

tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
389 390 391
  return port;
}

392
/* Constructor */
393 394 395 396 397 398 399 400 401 402
int MgmtSrvr::init()
{
  if ( _ownNodeId > 0)
    return 0;
  return -1;
}

MgmtSrvr::MgmtSrvr(SocketServer *socket_server,
		   const char *config_filename,
		   const char *connect_string) :
403 404
  _blockNumber(1), // Hard coded block number since it makes it easy to send
                   // signals to other management servers.
405
  m_socket_server(socket_server),
406 407 408
  _ownReference(0),
  theSignalIdleList(NULL),
  theWaitState(WAIT_SUBSCRIBE_CONF),
409
  m_local_mgm_handle(0),
410
  m_event_listner(this),
411
  m_master_node(0)
412
{
joreland@mysql.com's avatar
joreland@mysql.com committed
413
    
414 415
  DBUG_ENTER("MgmtSrvr::MgmtSrvr");

416 417
  _ownNodeId= 0;

418 419 420 421 422 423
  _config     = NULL;

  _isStopThread        = false;
  _logLevelThread      = NULL;
  _logLevelThreadSleep = 500;

tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
424 425
  theFacade = 0;

426
  m_newConfig = NULL;
427 428
  if (config_filename)
    m_configFilename.assign(config_filename);
429 430 431

  m_nextConfigGenerationNumber = 0;

432 433
  m_config_retriever= new ConfigRetriever(connect_string,
					  NDB_VERSION, NDB_MGM_NODE_TYPE_MGM);
434 435
  // if connect_string explicitly given or
  // no config filename is given then
436
  // first try to allocate nodeid from another management server
437 438
  if ((connect_string || config_filename == NULL) &&
      (m_config_retriever->do_connect(0,0,0) == 0))
439 440 441 442 443 444
  {
    int tmp_nodeid= 0;
    tmp_nodeid= m_config_retriever->allocNodeId(0 /*retry*/,0 /*delay*/);
    if (tmp_nodeid == 0)
    {
      ndbout_c(m_config_retriever->getErrorString());
445
      require(false);
446 447 448 449 450 451
    }
    // read config from other managent server
    _config= fetchConfig();
    if (_config == 0)
    {
      ndbout << m_config_retriever->getErrorString() << endl;
452
      require(false);
453 454 455 456 457 458 459 460 461
    }
    _ownNodeId= tmp_nodeid;
  }

  if (_ownNodeId == 0)
  {
    // read config locally
    _config= readConfig();
    if (_config == 0) {
462 463 464 465
      if (config_filename != NULL)
        ndbout << "Invalid configuration file: " << config_filename << endl;
      else
        ndbout << "Invalid configuration file" << endl;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
466
      exit(-1);
467 468 469
    }
  }

470 471 472 473 474 475 476
  theMgmtWaitForResponseCondPtr = NdbCondition_Create();

  m_configMutex = NdbMutex_Create();

  /**
   * Fill the nodeTypes array
   */
477
  for(Uint32 i = 0; i<MAX_NODES; i++) {
478
    nodeTypes[i] = (enum ndb_mgm_node_type)-1;
479 480
    m_connect_address[i].s_addr= 0;
  }
481

482
  {
483
    ndb_mgm_configuration_iterator
484 485 486
      iter(* _config->m_configValues, CFG_SECTION_NODE);

    for(iter.first(); iter.valid(); iter.next()){
487
      unsigned type, id;
488
      if(iter.get(CFG_TYPE_OF_SECTION, &type) != 0)
489 490
	continue;
      
491
      if(iter.get(CFG_NODE_ID, &id) != 0)
492
	continue;
493
      
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
      MGM_REQUIRE(id < MAX_NODES);
      
      switch(type){
      case NODE_TYPE_DB:
	nodeTypes[id] = NDB_MGM_NODE_TYPE_NDB;
	break;
      case NODE_TYPE_API:
	nodeTypes[id] = NDB_MGM_NODE_TYPE_API;
	break;
      case NODE_TYPE_MGM:
	nodeTypes[id] = NDB_MGM_NODE_TYPE_MGM;
	break;
      default:
	break;
      }
509 510
    }
  }
511

512
  _props = NULL;
513
  BaseString error_string;
514 515 516 517

  if ((m_node_id_mutex = NdbMutex_Create()) == 0)
  {
    ndbout << "mutex creation failed line = " << __LINE__ << endl;
518
    require(false);
519 520
  }

521 522 523
  if (_ownNodeId == 0) // we did not get node id from other server
  {
    NodeId tmp= m_config_retriever->get_configuration_nodeid();
524
    int error_code;
525 526

    if (!alloc_node_id(&tmp, NDB_MGM_NODE_TYPE_MGM,
527
		       0, 0, error_code, error_string)){
528 529
      ndbout << "Unable to obtain requested nodeid: "
	     << error_string.c_str() << endl;
530
      require(false);
531
    }
532
    _ownNodeId = tmp;
533
  }
534 535 536

  {
    DBUG_PRINT("info", ("verifyConfig"));
537 538 539 540
    if (!m_config_retriever->verifyConfig(_config->m_configValues,
					  _ownNodeId))
    {
      ndbout << m_config_retriever->getErrorString() << endl;
541
      require(false);
542 543 544
    }
  }

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
545
  // Setup clusterlog as client[0] in m_event_listner
joreland@mysql.com's avatar
joreland@mysql.com committed
546
  {
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
547
    Ndb_mgmd_event_service::Event_listener se;
joreland@mysql.com's avatar
joreland@mysql.com committed
548
    se.m_socket = NDB_INVALID_SOCKET;
joreland@mysql.com's avatar
joreland@mysql.com committed
549
    for(size_t t = 0; t<LogLevel::LOGLEVEL_CATEGORIES; t++){
joreland@mysql.com's avatar
joreland@mysql.com committed
550
      se.m_logLevel.setLogLevel((LogLevel::EventCategory)t, 7);
joreland@mysql.com's avatar
joreland@mysql.com committed
551
    }
joreland@mysql.com's avatar
joreland@mysql.com committed
552
    se.m_logLevel.setLogLevel(LogLevel::llError, 15);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
553
    se.m_logLevel.setLogLevel(LogLevel::llConnection, 8);
joreland@mysql.com's avatar
joreland@mysql.com committed
554
    se.m_logLevel.setLogLevel(LogLevel::llBackup, 15);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
555 556
    m_event_listner.m_clients.push_back(se);
    m_event_listner.m_logLevel = se.m_logLevel;
joreland@mysql.com's avatar
joreland@mysql.com committed
557
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
558
  
559
  DBUG_VOID_RETURN;
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
}


//****************************************************************************
//****************************************************************************
bool 
MgmtSrvr::check_start() 
{
  if (_config == 0) {
    DEBUG("MgmtSrvr.cpp: _config is NULL.");
    return false;
  }

  return true;
}

bool 
577
MgmtSrvr::start(BaseString &error_string)
578
{
579 580
  int mgm_connect_result;

581
  DBUG_ENTER("MgmtSrvr::start");
582
  if (_props == NULL) {
583 584
    if (!check_start()) {
      error_string.append("MgmtSrvr.cpp: check_start() failed.");
585
      DBUG_RETURN(false);
586
    }
587
  }
588
  theFacade= new TransporterFacade();
589 590 591
  
  if(theFacade == 0) {
    DEBUG("MgmtSrvr.cpp: theFacade is NULL.");
592
    error_string.append("MgmtSrvr.cpp: theFacade is NULL.");
593
    DBUG_RETURN(false);
594
  }  
595 596 597
  if ( theFacade->start_instance
       (_ownNodeId, (ndb_mgm_configuration*)_config->m_configValues) < 0) {
    DEBUG("MgmtSrvr.cpp: TransporterFacade::start_instance < 0.");
598
    DBUG_RETURN(false);
599
  }
600 601 602 603 604 605 606 607

  MGM_REQUIRE(_blockNumber == 1);

  // Register ourself at TransporterFacade to be able to receive signals
  // and to be notified when a database process has died.
  _blockNumber = theFacade->open(this,
				 signalReceivedNotification,
				 nodeStatusNotification);
608
  
609 610
  if(_blockNumber == -1){
    DEBUG("MgmtSrvr.cpp: _blockNumber is -1.");
611
    error_string.append("MgmtSrvr.cpp: _blockNumber is -1.");
612 613
    theFacade->stop_instance();
    theFacade = 0;
614
    DBUG_RETURN(false);
615
  }
616

617 618 619 620 621 622 623
  if((mgm_connect_result= connect_to_self()) < 0)
  {
    ndbout_c("Unable to connect to our own ndb_mgmd (Error %d)",
             mgm_connect_result);
    ndbout_c("This is probably a bug.");
  }

624 625 626
  TransporterRegistry *reg = theFacade->get_registry();
  for(unsigned int i=0;i<reg->m_transporter_interface.size();i++) {
    BaseString msg;
627
    DBUG_PRINT("info",("Setting dynamic port %d->%d : %d",
628 629
		       reg->get_localNodeId(),
		       reg->m_transporter_interface[i].m_remote_nodeId,
630
		       reg->m_transporter_interface[i].m_s_service_port
631 632 633 634 635 636
		       )
	       );
    int res = setConnectionDbParameter((int)reg->get_localNodeId(),
				       (int)reg->m_transporter_interface[i]
				            .m_remote_nodeId,
				       (int)CFG_CONNECTION_SERVER_PORT,
637 638
				       reg->m_transporter_interface[i]
				            .m_s_service_port,
639 640 641 642
					 msg);
    DBUG_PRINT("info",("Set result: %d: %s",res,msg.c_str()));
  }

643 644 645 646 647 648 649 650 651 652 653 654 655
  _ownReference = numberToRef(_blockNumber, _ownNodeId);
  
  startEventLog();
  // Set the initial confirmation count for subscribe requests confirm
  // from NDB nodes in the cluster.
  //
  // Loglevel thread
  _logLevelThread = NdbThread_Create(logLevelThread_C,
				     (void**)this,
				     32768,
				     "MgmtSrvr_Loglevel",
				     NDB_THREAD_PRIO_LOW);

656
  DBUG_RETURN(true);
657 658 659 660 661 662 663 664 665
}


//****************************************************************************
//****************************************************************************
MgmtSrvr::~MgmtSrvr() 
{
  if(theFacade != 0){
    theFacade->stop_instance();
666
    delete theFacade;
667 668 669 670 671
    theFacade = 0;
  }

  stopEventLog();

672 673 674
  NdbMutex_Destroy(m_node_id_mutex);
  NdbCondition_Destroy(theMgmtWaitForResponseCondPtr);
  NdbMutex_Destroy(m_configMutex);
675 676

  if(m_newConfig != NULL)
677 678 679 680 681
    free(m_newConfig);

  if(_config != NULL)
    delete _config;

682 683 684 685 686 687 688 689
  // End set log level thread
  void* res = 0;
  _isStopThread = true;

  if (_logLevelThread != NULL) {
    NdbThread_WaitFor(_logLevelThread, &res);
    NdbThread_Destroy(&_logLevelThread);
  }
joreland@mysql.com's avatar
joreland@mysql.com committed
690

691 692
  if (m_config_retriever)
    delete m_config_retriever;
693 694 695 696 697
}

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

698
int MgmtSrvr::okToSendTo(NodeId nodeId, bool unCond) 
699
{
700
  if(nodeId == 0 || getNodeType(nodeId) != NDB_MGM_NODE_TYPE_NDB)
701 702 703
    return WRONG_PROCESS_TYPE;
  // Check if we have contact with it
  if(unCond){
704
    if(theFacade->theClusterMgr->getNodeInfo(nodeId).m_api_reg_conf)
705 706
      return 0;
  }
707
  else if (theFacade->get_node_alive(nodeId) == true)
708
    return 0;
709
  return NO_CONTACT_WITH_PROCESS;
710 711
}

712 713 714 715 716 717 718 719 720
void report_unknown_signal(SimpleSignal *signal)
{
  g_eventLogger.error("Unknown signal received. SignalNumber: "
		      "%i from (%d, %x)",
		      signal->readSignalNumber(),
		      refToNode(signal->header.theSendersBlockRef),
		      refToBlock(signal->header.theSendersBlockRef));
}

721 722 723 724 725
/*****************************************************************************
 * Starting and stopping database nodes
 ****************************************************************************/

int 
726
MgmtSrvr::start(int nodeId)
727
{
728
  INIT_SIGNAL_SENDER(ss,nodeId);
729
  
730 731 732
  SimpleSignal ssig;
  StartOrd* const startOrd = CAST_PTR(StartOrd, ssig.getDataPtrSend());
  ssig.set(ss,TestOrd::TraceAPI, CMVMI, GSN_START_ORD, StartOrd::SignalLength);
733 734
  startOrd->restartInfo = 0;
  
735
  return ss.sendSignal(nodeId, &ssig) == SEND_OK ? 0 : SEND_OR_RECEIVE_FAILED;
736 737 738 739 740 741 742
}

/*****************************************************************************
 * Version handling
 *****************************************************************************/

int 
743
MgmtSrvr::versionNode(int nodeId, Uint32 &version, const char **address)
744
{
745 746
  version= 0;
  if (getOwnNodeId() == nodeId)
747
  {
748 749 750 751 752 753 754 755 756 757
    /**
     * If we're inquiring about our own node id,
     * We know what version we are (version implies connected for mgm)
     * but would like to find out from elsewhere what address they're using
     * to connect to us. This means that secondary mgm servers
     * can list ip addresses for mgm servers.
     *
     * If we don't get an address (i.e. no db nodes),
     * we get the address from the configuration.
     */
758
    sendVersionReq(nodeId, version, address);
759
    version= NDB_VERSION;
760 761 762 763 764 765 766 767 768 769 770 771 772 773
    if(!*address)
    {
      ndb_mgm_configuration_iterator
	iter(*_config->m_configValues, CFG_SECTION_NODE);
      unsigned tmp= 0;
      for(iter.first();iter.valid();iter.next())
      {
	if(iter.get(CFG_NODE_ID, &tmp)) require(false);
	if((unsigned)nodeId!=tmp)
	  continue;
	if(iter.get(CFG_NODE_HOST, address)) require(false);
	break;
      }
    }
774
  }
775
  else if (getNodeType(nodeId) == NDB_MGM_NODE_TYPE_NDB)
776
  {
777
    ClusterMgr::Node node= theFacade->theClusterMgr->getNodeInfo(nodeId);
778 779
    if(node.connected)
      version= node.m_info.m_version;
780
    *address= get_connect_address(nodeId);
781
  }
782 783
  else if (getNodeType(nodeId) == NDB_MGM_NODE_TYPE_API ||
	   getNodeType(nodeId) == NDB_MGM_NODE_TYPE_MGM)
784
  {
785
    return sendVersionReq(nodeId, version, address);
786
  }
787 788

  return 0;
789 790 791
}

int 
792
MgmtSrvr::sendVersionReq(int v_nodeId, Uint32 &version, const char **address)
793
{
794 795
  SignalSender ss(theFacade);
  ss.lock();
796

797 798 799 800 801 802
  SimpleSignal ssig;
  ApiVersionReq* req = CAST_PTR(ApiVersionReq, ssig.getDataPtrSend());
  req->senderRef = ss.getOwnRef();
  req->nodeId = v_nodeId;
  ssig.set(ss, TestOrd::TraceAPI, QMGR, GSN_API_VERSION_REQ, 
	   ApiVersionReq::SignalLength);
803

804 805
  int do_send = 1;
  NodeId nodeId;
806

807 808 809 810 811 812
  while (1)
  {
    if (do_send)
    {
      bool next;
      nodeId = 0;
813

814 815
      while((next = getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB)) == true &&
	    okToSendTo(nodeId, true) != 0);
816 817 818 819 820 821 822 823 824 825 826

      const ClusterMgr::Node &node=
	theFacade->theClusterMgr->getNodeInfo(nodeId);
      if(next && node.m_state.startLevel != NodeState::SL_STARTED)
      {
	NodeId tmp=nodeId;
	while((next = getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB)) == true &&
	      okToSendTo(nodeId, true) != 0);
	if(!next)
	  nodeId= tmp;
      }
827

828
      if(!next) return NO_CONTACT_WITH_DB_NODES;
829

830 831 832 833
      if (ss.sendSignal(nodeId, &ssig) != SEND_OK) {
	return SEND_OR_RECEIVE_FAILED;
      }
      do_send = 0;
834
    }
835 836 837 838 839 840 841 842

    SimpleSignal *signal = ss.waitFor();

    int gsn = signal->readSignalNumber();
    switch (gsn) {
    case GSN_API_VERSION_CONF: {
      const ApiVersionConf * const conf = 
	CAST_CONSTPTR(ApiVersionConf, signal->getDataPtr());
843
      assert((int) conf->nodeId == v_nodeId);
844
      version = conf->version;
845 846 847
      struct in_addr in;
      in.s_addr= conf->inet_addr;
      *address= inet_ntoa(in);
848
      return 0;
849
    }
850 851 852 853 854 855
    case GSN_NF_COMPLETEREP:{
      const NFCompleteRep * const rep =
	CAST_CONSTPTR(NFCompleteRep, signal->getDataPtr());
      if (rep->failedNodeId == nodeId)
	do_send = 1; // retry with other node
      continue;
856
    }
857 858 859
    case GSN_NODE_FAILREP:{
      const NodeFailRep * const rep =
	CAST_CONSTPTR(NodeFailRep, signal->getDataPtr());
860
      if (NodeBitmask::get(rep->theNodes,nodeId))
861 862 863 864 865 866 867 868 869 870
	do_send = 1; // retry with other node
      continue;
    }
    default:
      report_unknown_signal(signal);
      return SEND_OR_RECEIVE_FAILED;
    }
    break;
  } // while(1)

871 872 873
  return 0;
}

874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 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 939 940
int MgmtSrvr::sendStopMgmd(NodeId nodeId,
			   bool abort,
			   bool stop,
			   bool restart,
			   bool nostart,
			   bool initialStart)
{
  const char* hostname;
  Uint32 port;
  BaseString connect_string;

  {
    Guard g(m_configMutex);
    {
      ndb_mgm_configuration_iterator
        iter(* _config->m_configValues, CFG_SECTION_NODE);

      if(iter.first())                       return SEND_OR_RECEIVE_FAILED;
      if(iter.find(CFG_NODE_ID, nodeId))     return SEND_OR_RECEIVE_FAILED;
      if(iter.get(CFG_NODE_HOST, &hostname)) return SEND_OR_RECEIVE_FAILED;
    }
    {
      ndb_mgm_configuration_iterator
        iter(* _config->m_configValues, CFG_SECTION_NODE);

      if(iter.first())                   return SEND_OR_RECEIVE_FAILED;
      if(iter.find(CFG_NODE_ID, nodeId)) return SEND_OR_RECEIVE_FAILED;
      if(iter.get(CFG_MGM_PORT, &port))  return SEND_OR_RECEIVE_FAILED;
    }
    if( strlen(hostname) == 0 )
      return SEND_OR_RECEIVE_FAILED;
  }
  connect_string.assfmt("%s:%u",hostname,port);

  DBUG_PRINT("info",("connect string: %s",connect_string.c_str()));

  NdbMgmHandle h= ndb_mgm_create_handle();
  if ( h && connect_string.length() > 0 )
  {
    ndb_mgm_set_connectstring(h,connect_string.c_str());
    if(ndb_mgm_connect(h,1,0,0))
    {
      DBUG_PRINT("info",("failed ndb_mgm_connect"));
      return SEND_OR_RECEIVE_FAILED;
    }
    if(!restart)
    {
      if(ndb_mgm_stop(h, 1, (const int*)&nodeId) < 0)
      {
        return SEND_OR_RECEIVE_FAILED;
      }
    }
    else
    {
      int nodes[1];
      nodes[0]= (int)nodeId;
      if(ndb_mgm_restart2(h, 1, nodes, initialStart, nostart, abort) < 0)
      {
        return SEND_OR_RECEIVE_FAILED;
      }
    }
  }
  ndb_mgm_destroy_handle(&h);

  return 0;
}

941 942 943
/*
 * Common method for handeling all STOP_REQ signalling that
 * is used by Stopping, Restarting and Single user commands
944 945 946 947 948
 *
 * In the event that we need to stop a mgmd, we create a mgm
 * client connection to that mgmd and stop it that way.
 * This allows us to stop mgm servers when there isn't any real
 * distributed communication up.
949 950 951 952 953 954 955
 *
 * node_ids.size()==0 means to stop all DB nodes.
 *                    MGM nodes will *NOT* be stopped.
 *
 * If we work out we should be stopping or restarting ourselves,
 * we return <0 in stopSelf for restart, >0 for stop
 * and 0 for do nothing.
956
 */
957

958
int MgmtSrvr::sendSTOP_REQ(const Vector<NodeId> &node_ids,
959 960 961 962 963 964
			   NodeBitmask &stoppedNodes,
			   Uint32 singleUserNodeId,
			   bool abort,
			   bool stop,
			   bool restart,
			   bool nostart,
965 966
			   bool initialStart,
                           int* stopSelf)
967
{
968
  int error = 0;
969 970 971 972 973 974
  DBUG_ENTER("MgmtSrvr::sendSTOP_REQ");
  DBUG_PRINT("enter", ("no of nodes: %d  singleUseNodeId: %d  "
                       "abort: %d  stop: %d  restart: %d  "
                       "nostart: %d  initialStart: %d",
                       node_ids.size(), singleUserNodeId,
                       abort, stop, restart, nostart, initialStart));
975

976
  stoppedNodes.clear();
977

978 979
  SignalSender ss(theFacade);
  ss.lock(); // lock will be released on exit
980

981 982 983
  SimpleSignal ssig;
  StopReq* const stopReq = CAST_PTR(StopReq, ssig.getDataPtrSend());
  ssig.set(ss, TestOrd::TraceAPI, NDBCNTR, GSN_STOP_REQ, StopReq::SignalLength);
984

jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
985 986 987 988 989 990 991 992 993
  NdbNodeBitmask notstarted;
  for (Uint32 i = 0; i<node_ids.size(); i++)
  {
    Uint32 nodeId = node_ids[i];
    ClusterMgr::Node node = theFacade->theClusterMgr->getNodeInfo(nodeId);
    if (node.m_state.startLevel != NodeState::SL_STARTED)
      notstarted.set(nodeId);
  }
  
994 995 996 997 998 999
  stopReq->requestInfo = 0;
  stopReq->apiTimeout = 5000;
  stopReq->transactionTimeout = 1000;
  stopReq->readOperationTimeout = 1000;
  stopReq->operationTimeout = 1000;
  stopReq->senderData = 12;
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
  stopReq->senderRef = ss.getOwnRef();
  if (singleUserNodeId)
  {
    stopReq->singleuser = 1;
    stopReq->singleUserApi = singleUserNodeId;
    StopReq::setSystemStop(stopReq->requestInfo, false);
    StopReq::setPerformRestart(stopReq->requestInfo, false);
    StopReq::setStopAbort(stopReq->requestInfo, false);
  }
  else
  {
    stopReq->singleuser = 0;
    StopReq::setSystemStop(stopReq->requestInfo, stop);
    StopReq::setPerformRestart(stopReq->requestInfo, restart);
    StopReq::setStopAbort(stopReq->requestInfo, abort);
    StopReq::setNoStart(stopReq->requestInfo, nostart);
    StopReq::setInitialStart(stopReq->requestInfo, initialStart);
1017 1018
  }

1019 1020
  // send the signals
  NodeBitmask nodes;
1021
  NodeId nodeId= 0;
1022 1023
  int use_master_node= 0;
  int do_send= 0;
1024
  *stopSelf= 0;
1025
  NdbNodeBitmask nodes_to_stop;
1026
  {
1027
    for (unsigned i= 0; i < node_ids.size(); i++)
1028
    {
1029
      nodeId= node_ids[i];
1030
      ndbout << "asked to stop " << nodeId << endl;
1031 1032 1033 1034 1035

      if ((getNodeType(nodeId) != NDB_MGM_NODE_TYPE_MGM)
          &&(getNodeType(nodeId) != NDB_MGM_NODE_TYPE_NDB))
          return WRONG_PROCESS_TYPE;

1036 1037 1038
      if (getNodeType(nodeId) != NDB_MGM_NODE_TYPE_MGM)
        nodes_to_stop.set(nodeId);
      else if (nodeId != getOwnNodeId())
1039 1040 1041 1042 1043 1044
      {
        error= sendStopMgmd(nodeId, abort, stop, restart,
                            nostart, initialStart);
        if (error == 0)
          stoppedNodes.set(nodeId);
      }
1045
      else
1046 1047 1048 1049 1050
      {
        ndbout << "which is me" << endl;
        *stopSelf= (restart)? -1 : 1;
        stoppedNodes.set(nodeId);
      }
1051
    }
1052 1053 1054 1055 1056
  }
  int no_of_nodes_to_stop= nodes_to_stop.count();
  if (node_ids.size())
  {
    if (no_of_nodes_to_stop)
1057
    {
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
      do_send= 1;
      if (no_of_nodes_to_stop == 1)
      {
        nodeId= nodes_to_stop.find(0);
      }
      else // multi node stop, send to master
      {
        use_master_node= 1;
        nodes_to_stop.copyto(NdbNodeBitmask::Size, stopReq->nodes);
        StopReq::setStopNodes(stopReq->requestInfo, 1);
      }
1069
    }
1070
  }
1071
  else
1072
  {
1073
    nodeId= 0;
1074 1075 1076 1077 1078 1079 1080 1081 1082
    while(getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB))
    {
      if(okToSendTo(nodeId, true) == 0)
      {
	SendStatus result = ss.sendSignal(nodeId, &ssig);
	if (result == SEND_OK)
	  nodes.set(nodeId);
      }
    }
1083
  }
1084

1085
  // now wait for the replies
1086
  while (!nodes.isclear() || do_send)
1087
  {
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
    if (do_send)
    {
      int r;
      assert(nodes.count() == 0);
      if (use_master_node)
        nodeId= m_master_node;
      if ((r= okToSendTo(nodeId, true)) != 0)
      {
        bool next;
        if (!use_master_node)
          DBUG_RETURN(r);
        m_master_node= nodeId= 0;
        while((next= getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB)) == true &&
              (r= okToSendTo(nodeId, true)) != 0);
        if (!next)
          DBUG_RETURN(NO_CONTACT_WITH_DB_NODES);
      }
      if (ss.sendSignal(nodeId, &ssig) != SEND_OK)
        DBUG_RETURN(SEND_OR_RECEIVE_FAILED);
      nodes.set(nodeId);
      do_send= 0;
    }
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
    SimpleSignal *signal = ss.waitFor();
    int gsn = signal->readSignalNumber();
    switch (gsn) {
    case GSN_STOP_REF:{
      const StopRef * const ref = CAST_CONSTPTR(StopRef, signal->getDataPtr());
      const NodeId nodeId = refToNode(signal->header.theSendersBlockRef);
#ifdef VM_TRACE
      ndbout_c("Node %d refused stop", nodeId);
#endif
      assert(nodes.get(nodeId));
      nodes.clear(nodeId);
1121 1122 1123 1124 1125 1126 1127
      if (ref->errorCode == StopRef::MultiNodeShutdownNotMaster)
      {
        assert(use_master_node);
        m_master_node= ref->masterNodeId;
        do_send= 1;
        continue;
      }
1128 1129 1130 1131
      error = translateStopRef(ref->errorCode);
      break;
    }
    case GSN_STOP_CONF:{
1132 1133 1134
#ifdef NOT_USED
      const StopConf * const ref = CAST_CONSTPTR(StopConf, signal->getDataPtr());
#endif
1135 1136 1137 1138 1139
      const NodeId nodeId = refToNode(signal->header.theSendersBlockRef);
#ifdef VM_TRACE
      ndbout_c("Node %d single user mode", nodeId);
#endif
      assert(nodes.get(nodeId));
1140 1141 1142 1143 1144 1145
      if (singleUserNodeId != 0)
      {
        stoppedNodes.set(nodeId);
      }
      else
      {
1146
        assert(no_of_nodes_to_stop > 1);
1147 1148
        stoppedNodes.bitOR(nodes_to_stop);
      }
1149 1150 1151 1152 1153 1154 1155
      nodes.clear(nodeId);
      break;
    }
    case GSN_NF_COMPLETEREP:{
      const NFCompleteRep * const rep =
	CAST_CONSTPTR(NFCompleteRep, signal->getDataPtr());
#ifdef VM_TRACE
1156
      ndbout_c("sendSTOP_REQ Node %d fail completed", rep->failedNodeId);
1157
#endif
1158 1159 1160
      nodes.clear(rep->failedNodeId); // clear the failed node
      if (singleUserNodeId == 0)
        stoppedNodes.set(rep->failedNodeId);
1161 1162 1163
      break;
    }
    case GSN_NODE_FAILREP:{
1164 1165
      const NodeFailRep * const rep =
	CAST_CONSTPTR(NodeFailRep, signal->getDataPtr());
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
1166 1167 1168 1169 1170 1171 1172
      NdbNodeBitmask mask;
      mask.assign(NdbNodeBitmask::Size, rep->theNodes);
      mask.bitAND(notstarted);
      nodes.bitANDC(mask);
      
      if (singleUserNodeId == 0)
	stoppedNodes.bitOR(mask);
1173 1174 1175 1176 1177 1178 1179
      break;
    }
    default:
      report_unknown_signal(signal);
#ifdef VM_TRACE
      ndbout_c("Unknown signal %d", gsn);
#endif
1180
      DBUG_RETURN(SEND_OR_RECEIVE_FAILED);
1181
    }
1182
  }
1183
  if (error && *stopSelf)
1184
  {
1185
    *stopSelf= 0;
1186
  }
1187
  DBUG_RETURN(error);
1188 1189
}

1190
/*
1191
 * Stop one nodes
1192 1193
 */

1194
int MgmtSrvr::stopNodes(const Vector<NodeId> &node_ids,
1195
                        int *stopCount, bool abort, int* stopSelf)
1196
{
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
  if (!abort)
  {
    NodeId nodeId = 0;
    ClusterMgr::Node node;
    while(getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB))
    {
      node = theFacade->theClusterMgr->getNodeInfo(nodeId);
      if((node.m_state.startLevel != NodeState::SL_STARTED) && 
	 (node.m_state.startLevel != NodeState::SL_NOTHING))
	return OPERATION_NOT_ALLOWED_START_STOP;
    }
  }
1209
  NodeBitmask nodes;
1210 1211 1212 1213 1214 1215 1216
  int ret= sendSTOP_REQ(node_ids,
                        nodes,
                        0,
                        abort,
                        false,
                        false,
                        false,
1217 1218
                        false,
                        stopSelf);
1219 1220 1221
  if (stopCount)
    *stopCount= nodes.count();
  return ret;
1222
}
1223

1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
int MgmtSrvr::shutdownMGM(int *stopCount, bool abort, int *stopSelf)
{
  NodeId nodeId = 0;
  int error;

  while(getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_MGM))
  {
    if(nodeId==getOwnNodeId())
      continue;
    error= sendStopMgmd(nodeId, abort, true, false,
                        false, false);
    if (error == 0)
      *stopCount++;
  }

  *stopSelf= 1;
  *stopCount++;

  return 0;
}

1245
/*
1246 1247
 * Perform DB nodes shutdown.
 * MGM servers are left in their current state
1248
 */
1249

1250
int MgmtSrvr::shutdownDB(int * stopCount, bool abort)
1251 1252
{
  NodeBitmask nodes;
1253
  Vector<NodeId> node_ids;
1254 1255 1256

  int tmp;

1257
  int ret = sendSTOP_REQ(node_ids,
1258 1259 1260 1261 1262 1263
			 nodes,
			 0,
			 abort,
			 true,
			 false,
			 false,
1264 1265
			 false,
                         &tmp);
1266 1267 1268 1269 1270 1271 1272 1273
  if (stopCount)
    *stopCount = nodes.count();
  return ret;
}

/*
 * Enter single user mode on all live nodes
 */
1274

1275 1276 1277
int MgmtSrvr::enterSingleUser(int * stopCount, Uint32 singleUserNodeId)
{
  if (getNodeType(singleUserNodeId) != NDB_MGM_NODE_TYPE_API)
1278
    return NODE_NOT_API_NODE;
1279 1280 1281 1282 1283 1284 1285
  NodeId nodeId = 0;
  ClusterMgr::Node node;
  while(getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB))
  {
    node = theFacade->theClusterMgr->getNodeInfo(nodeId);
    if((node.m_state.startLevel != NodeState::SL_STARTED) && 
       (node.m_state.startLevel != NodeState::SL_NOTHING))
1286
      return OPERATION_NOT_ALLOWED_START_STOP;
1287
  }
1288
  NodeBitmask nodes;
1289
  Vector<NodeId> node_ids;
1290
  int stopSelf;
1291
  int ret = sendSTOP_REQ(node_ids,
1292 1293 1294 1295 1296 1297
			 nodes,
			 singleUserNodeId,
			 false,
			 false,
			 false,
			 false,
1298 1299
			 false,
                         &stopSelf);
1300 1301 1302
  if (stopCount)
    *stopCount = nodes.count();
  return ret;
1303 1304
}

1305 1306 1307
/*
 * Perform node restart
 */
1308

1309 1310
int MgmtSrvr::restartNodes(const Vector<NodeId> &node_ids,
                           int * stopCount, bool nostart,
1311 1312
                           bool initialStart, bool abort,
                           int *stopSelf)
1313
{
1314
  NodeBitmask nodes;
1315 1316 1317 1318 1319 1320
  int ret= sendSTOP_REQ(node_ids,
                        nodes,
                        0,
                        abort,
                        false,
                        true,
1321
                        true,
1322 1323
                        initialStart,
                        stopSelf);
1324 1325 1326 1327

  if (ret)
    return ret;

1328 1329
  if (stopCount)
    *stopCount = nodes.count();
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
  
  // start up the nodes again
  int waitTime = 12000;
  NDB_TICKS maxTime = NdbTick_CurrentMillisecond() + waitTime;
  for (unsigned i = 0; i < node_ids.size(); i++)
  {
    NodeId nodeId= node_ids[i];
    enum ndb_mgm_node_status s;
    s = NDB_MGM_NODE_STATUS_NO_CONTACT;
#ifdef VM_TRACE
    ndbout_c("Waiting for %d not started", nodeId);
#endif
    while (s != NDB_MGM_NODE_STATUS_NOT_STARTED && waitTime > 0)
    {
      Uint32 startPhase = 0, version = 0, dynamicId = 0, nodeGroup = 0;
      Uint32 connectCount = 0;
      bool system;
      const char *address;
      status(nodeId, &s, &version, &startPhase, 
             &system, &dynamicId, &nodeGroup, &connectCount, &address);
      NdbSleep_MilliSleep(100);  
      waitTime = (maxTime - NdbTick_CurrentMillisecond());
    }
  }

  if (nostart)
    return 0;

  for (unsigned i = 0; i < node_ids.size(); i++)
  {
1360
    (void) start(node_ids[i]);
1361 1362
  }
  return 0;
1363
}
1364

1365
/*
1366
 * Perform restart of all DB nodes
1367
 */
1368

1369 1370
int MgmtSrvr::restartDB(bool nostart, bool initialStart,
                        bool abort, int * stopCount)
1371
{
1372
  NodeBitmask nodes;
1373
  Vector<NodeId> node_ids;
1374 1375
  int tmp;

1376
  int ret = sendSTOP_REQ(node_ids,
1377 1378 1379 1380 1381 1382
			 nodes,
			 0,
			 abort,
			 true,
			 true,
			 true,
1383 1384
			 initialStart,
                         &tmp);
1385

1386 1387
  if (ret)
    return ret;
1388

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
  if (stopCount)
    *stopCount = nodes.count();

#ifdef VM_TRACE
    ndbout_c("Stopped %d nodes", nodes.count());
#endif
  /**
   * Here all nodes were correctly stopped,
   * so we wait for all nodes to be contactable
   */
  int waitTime = 12000;
  NodeId nodeId = 0;
  NDB_TICKS maxTime = NdbTick_CurrentMillisecond() + waitTime;

  while(getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB)) {
    if (!nodes.get(nodeId))
      continue;
    enum ndb_mgm_node_status s;
    s = NDB_MGM_NODE_STATUS_NO_CONTACT;
#ifdef VM_TRACE
    ndbout_c("Waiting for %d not started", nodeId);
#endif
    while (s != NDB_MGM_NODE_STATUS_NOT_STARTED && waitTime > 0) {
      Uint32 startPhase = 0, version = 0, dynamicId = 0, nodeGroup = 0;
      Uint32 connectCount = 0;
      bool system;
1415
      const char *address;
1416
      status(nodeId, &s, &version, &startPhase, 
1417
	     &system, &dynamicId, &nodeGroup, &connectCount, &address);
1418 1419
      NdbSleep_MilliSleep(100);  
      waitTime = (maxTime - NdbTick_CurrentMillisecond());
1420 1421 1422
    }
  }
  
1423 1424
  if(nostart)
    return 0;
1425
  
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
  /**
   * Now we start all database nodes (i.e. we make them non-idle)
   * We ignore the result we get from the start command.
   */
  nodeId = 0;
  while(getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB)) {
    if (!nodes.get(nodeId))
      continue;
    int result;
    result = start(nodeId);
    DEBUG("Starting node " << nodeId << " with result " << result);
    /**
     * Errors from this call are deliberately ignored.
     * Maybe the user only wanted to restart a subset of the nodes.
     * It is also easy for the user to check which nodes have 
     * started and which nodes have not.
     */
1443
  }
1444 1445
  
  return 0;
1446 1447 1448
}

int
1449
MgmtSrvr::exitSingleUser(int * stopCount, bool abort)
1450 1451
{
  NodeId nodeId = 0;
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
  int count = 0;

  SignalSender ss(theFacade);
  ss.lock(); // lock will be released on exit

  SimpleSignal ssig;
  ResumeReq* const resumeReq = 
    CAST_PTR(ResumeReq, ssig.getDataPtrSend());
  ssig.set(ss,TestOrd::TraceAPI, NDBCNTR, GSN_RESUME_REQ, 
	   ResumeReq::SignalLength);
  resumeReq->senderData = 12;
  resumeReq->senderRef = ss.getOwnRef();

1465 1466
  while(getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB)){
    if(okToSendTo(nodeId, true) == 0){
1467 1468 1469
      SendStatus result = ss.sendSignal(nodeId, &ssig);
      if (result == SEND_OK)
	count++;
1470 1471 1472 1473
    }
  }

  if(stopCount != 0)
1474
    * stopCount = count;
1475

1476
  return 0;
1477 1478 1479 1480 1481 1482 1483 1484
}

/*****************************************************************************
 * Status
 ****************************************************************************/

#include <ClusterMgr.hpp>

1485
void
stewart@willster.(none)'s avatar
stewart@willster.(none) committed
1486
MgmtSrvr::updateStatus()
1487
{
stewart@willster.(none)'s avatar
stewart@willster.(none) committed
1488
  theFacade->theClusterMgr->forceHB();
1489 1490
}

1491
int 
1492
MgmtSrvr::status(int nodeId, 
1493 1494 1495 1496 1497
                 ndb_mgm_node_status * _status, 
		 Uint32 * version,
		 Uint32 * _phase, 
		 bool * _system,
		 Uint32 * dynamic,
1498
		 Uint32 * nodegroup,
1499 1500
		 Uint32 * connectCount,
		 const char **address)
1501
{
1502 1503
  if (getNodeType(nodeId) == NDB_MGM_NODE_TYPE_API ||
      getNodeType(nodeId) == NDB_MGM_NODE_TYPE_MGM) {
1504 1505 1506
    versionNode(nodeId, *version, address);
  } else {
    *address= get_connect_address(nodeId);
1507 1508 1509
  }

  const ClusterMgr::Node node = 
1510
    theFacade->theClusterMgr->getNodeInfo(nodeId);
1511 1512 1513 1514 1515 1516

  if(!node.connected){
    * _status = NDB_MGM_NODE_STATUS_NO_CONTACT;
    return 0;
  }
  
1517
  if (getNodeType(nodeId) == NDB_MGM_NODE_TYPE_NDB) {
1518 1519 1520 1521 1522
    * version = node.m_info.m_version;
  }

  * dynamic = node.m_state.dynamicId;
  * nodegroup = node.m_state.nodeGroup;
1523 1524
  * connectCount = node.m_info.m_connectCount;
  
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
  switch(node.m_state.startLevel){
  case NodeState::SL_CMVMI:
    * _status = NDB_MGM_NODE_STATUS_NOT_STARTED;
    * _phase = 0;
    return 0;
    break;
  case NodeState::SL_STARTING:
    * _status     = NDB_MGM_NODE_STATUS_STARTING;
    * _phase = node.m_state.starting.startPhase;
    return 0;
    break;
  case NodeState::SL_STARTED:
    * _status = NDB_MGM_NODE_STATUS_STARTED;
    * _phase = 0;
    return 0;
    break;
  case NodeState::SL_STOPPING_1:
    * _status = NDB_MGM_NODE_STATUS_SHUTTING_DOWN;
    * _phase = 1;
    * _system = node.m_state.stopping.systemShutdown != 0;
    return 0;
    break;
  case NodeState::SL_STOPPING_2:
    * _status = NDB_MGM_NODE_STATUS_SHUTTING_DOWN;
    * _phase = 2;
    * _system = node.m_state.stopping.systemShutdown != 0;
    return 0;
    break;
  case NodeState::SL_STOPPING_3:
    * _status = NDB_MGM_NODE_STATUS_SHUTTING_DOWN;
    * _phase = 3;
    * _system = node.m_state.stopping.systemShutdown != 0;
    return 0;
    break;
  case NodeState::SL_STOPPING_4:
    * _status = NDB_MGM_NODE_STATUS_SHUTTING_DOWN;
    * _phase = 4;
    * _system = node.m_state.stopping.systemShutdown != 0;
    return 0;
    break;
  case NodeState::SL_SINGLEUSER:
    * _status = NDB_MGM_NODE_STATUS_SINGLEUSER;
    * _phase  = 0;
    return 0;
    break;
  default:
    * _status = NDB_MGM_NODE_STATUS_UNKNOWN;
    * _phase = 0;
    return 0;
  }
1575
  
1576 1577 1578 1579
  return -1;
}

int 
1580
MgmtSrvr::setEventReportingLevelImpl(int nodeId_arg, 
joreland@mysql.com's avatar
joreland@mysql.com committed
1581
				     const EventSubscribeReq& ll)
1582
{
1583
  SignalSender ss(theFacade);
1584 1585
  NdbNodeBitmask nodes;
  int retries = 30;
1586
  nodes.clear();
1587
  while (1)
1588
  {
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
    Uint32 nodeId, max;
    ss.lock();
    SimpleSignal ssig;
    EventSubscribeReq * dst = 
      CAST_PTR(EventSubscribeReq, ssig.getDataPtrSend());
    ssig.set(ss,TestOrd::TraceAPI, CMVMI, GSN_EVENT_SUBSCRIBE_REQ,
             EventSubscribeReq::SignalLength);
    *dst = ll;

    if (nodeId_arg == 0)
1599
    {
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
      // all nodes
      nodeId = 1;
      max = MAX_NDB_NODES;
    }
    else
    {
      // only one node
      max = nodeId = nodeId_arg;
    }
    // first make sure nodes are sendable
    for(; nodeId <= max; nodeId++)
    {
      if (nodeTypes[nodeId] != NODE_TYPE_DB)
        continue;
      if (okToSendTo(nodeId, true))
      {
        if (theFacade->theClusterMgr->getNodeInfo(nodeId).connected  == false)
        {
          // node not connected we can safely skip this one
          continue;
        }
        // api_reg_conf not recevied yet, need to retry
        break;
      }
1624
    }
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
    if (nodeId <= max)
    {
      if (--retries)
      {
        ss.unlock();
        NdbSleep_MilliSleep(100);  
        continue;
      }
      return SEND_OR_RECEIVE_FAILED;
    }

    if (nodeId_arg == 0)
    {
      // all nodes
      nodeId = 1;
      max = MAX_NDB_NODES;
    }
    else
    {
      // only one node
      max = nodeId = nodeId_arg;
    }
    // now send to all sendable nodes nodes
    // note, lock is held, so states have not changed
    for(; (Uint32) nodeId <= max; nodeId++)
    {
      if (nodeTypes[nodeId] != NODE_TYPE_DB)
        continue;
      if (theFacade->theClusterMgr->getNodeInfo(nodeId).connected  == false)
        continue; // node is not connected, skip
      if (ss.sendSignal(nodeId, &ssig) == SEND_OK)
        nodes.set(nodeId);
    }
    break;
1659
  }
1660

tomas@poseidon.mysql.com's avatar
tomas@poseidon.mysql.com committed
1661 1662 1663 1664 1665
  if (nodes.isclear())
  {
    return SEND_OR_RECEIVE_FAILED;
  }
  
1666 1667
  int error = 0;
  while (!nodes.isclear())
1668
  {
1669
    Uint32 nodeId;
1670 1671
    SimpleSignal *signal = ss.waitFor();
    int gsn = signal->readSignalNumber();
1672 1673
    nodeId = refToNode(signal->header.theSendersBlockRef);
    switch (gsn) {
1674
    case GSN_EVENT_SUBSCRIBE_CONF:{
1675
      nodes.clear(nodeId);
1676 1677 1678
      break;
    }
    case GSN_EVENT_SUBSCRIBE_REF:{
1679 1680 1681
      nodes.clear(nodeId);
      error = 1;
      break;
1682
    }
tomas@poseidon.mysql.com's avatar
tomas@poseidon.mysql.com committed
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
      // Since sending okToSend(true), 
      // there is no guarantee that NF_COMPLETEREP will come
      // i.e listen also to NODE_FAILREP
    case GSN_NODE_FAILREP: {
      const NodeFailRep * const rep =
	CAST_CONSTPTR(NodeFailRep, signal->getDataPtr());
      NdbNodeBitmask mask;
      mask.assign(NdbNodeBitmask::Size, rep->theNodes);
      nodes.bitANDC(mask);
      break;
    }
      
1695 1696 1697
    case GSN_NF_COMPLETEREP:{
      const NFCompleteRep * const rep =
	CAST_CONSTPTR(NFCompleteRep, signal->getDataPtr());
1698
      nodes.clear(rep->failedNodeId);
1699 1700 1701 1702 1703 1704 1705
      break;
    }
    default:
      report_unknown_signal(signal);
      return SEND_OR_RECEIVE_FAILED;
    }
  }
1706 1707
  if (error)
    return SEND_OR_RECEIVE_FAILED;
1708 1709 1710 1711 1712 1713
  return 0;
}

//****************************************************************************
//****************************************************************************
int 
1714
MgmtSrvr::setNodeLogLevelImpl(int nodeId, const SetLogLevelOrd & ll)
1715
{
1716
  INIT_SIGNAL_SENDER(ss,nodeId);
1717

1718 1719 1720 1721 1722
  SimpleSignal ssig;
  ssig.set(ss,TestOrd::TraceAPI, CMVMI, GSN_SET_LOGLEVELORD,
	   SetLogLevelOrd::SignalLength);
  SetLogLevelOrd* const dst = CAST_PTR(SetLogLevelOrd, ssig.getDataPtrSend());
  *dst = ll;
joreland@mysql.com's avatar
joreland@mysql.com committed
1723
  
1724
  return ss.sendSignal(nodeId, &ssig) == SEND_OK ? 0 : SEND_OR_RECEIVE_FAILED;
joreland@mysql.com's avatar
joreland@mysql.com committed
1725
}
1726 1727 1728 1729 1730

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

int 
1731
MgmtSrvr::insertError(int nodeId, int errorNo) 
1732 1733 1734 1735 1736
{
  if (errorNo < 0) {
    return INVALID_ERROR_NUMBER;
  }

1737
  INIT_SIGNAL_SENDER(ss,nodeId);
1738
  
1739 1740 1741 1742
  SimpleSignal ssig;
  ssig.set(ss,TestOrd::TraceAPI, CMVMI, GSN_TAMPER_ORD, 
	   TamperOrd::SignalLength);
  TamperOrd* const tamperOrd = CAST_PTR(TamperOrd, ssig.getDataPtrSend());
1743 1744
  tamperOrd->errorNo = errorNo;

1745
  return ss.sendSignal(nodeId, &ssig) == SEND_OK ? 0 : SEND_OR_RECEIVE_FAILED;
1746 1747 1748 1749 1750 1751 1752 1753
}



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

int 
1754
MgmtSrvr::setTraceNo(int nodeId, int traceNo)
1755 1756 1757 1758 1759
{
  if (traceNo < 0) {
    return INVALID_TRACE_NUMBER;
  }

1760
  INIT_SIGNAL_SENDER(ss,nodeId);
1761

1762 1763 1764
  SimpleSignal ssig;
  ssig.set(ss,TestOrd::TraceAPI, CMVMI, GSN_TEST_ORD, TestOrd::SignalLength);
  TestOrd* const testOrd = CAST_PTR(TestOrd, ssig.getDataPtrSend());
1765 1766 1767 1768 1769
  testOrd->clear();
  // Assume TRACE command causes toggling. Not really defined... ? TODO
  testOrd->setTraceCommand(TestOrd::Toggle, 
			   (TestOrd::TraceSpecification)traceNo);

1770
  return ss.sendSignal(nodeId, &ssig) == SEND_OK ? 0 : SEND_OR_RECEIVE_FAILED;
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
}

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

int 
MgmtSrvr::getBlockNumber(const BaseString &blockName) 
{
  short bno = getBlockNo(blockName.c_str());
  if(bno != 0)
    return bno;
  return -1;
}

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

int 
1789
MgmtSrvr::setSignalLoggingMode(int nodeId, LogMode mode, 
1790 1791
			       const Vector<BaseString>& blocks)
{
1792
  INIT_SIGNAL_SENDER(ss,nodeId);
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820

  // Convert from MgmtSrvr format...

  TestOrd::Command command;
  if (mode == Off) {
    command = TestOrd::Off;
  }
  else {
    command = TestOrd::On;
  }

  TestOrd::SignalLoggerSpecification logSpec;
  switch (mode) {
  case In:
    logSpec = TestOrd::InputSignals;
    break;
  case Out:
    logSpec = TestOrd::OutputSignals;
    break;
  case InOut:
    logSpec = TestOrd::InputOutputSignals;
    break;
  case Off:
    // In MgmtSrvr interface it's just possible to switch off all logging, both
    // "in" and "out" (this should probably be changed).
    logSpec = TestOrd::InputOutputSignals;
    break;
  default:
1821 1822 1823 1824
    ndbout_c("Unexpected value %d, MgmtSrvr::setSignalLoggingMode, line %d",
	     (unsigned)mode, __LINE__);
    assert(false);
    return -1;
1825 1826
  }

1827 1828
  SimpleSignal ssig;
  ssig.set(ss,TestOrd::TraceAPI, CMVMI, GSN_TEST_ORD, TestOrd::SignalLength);
1829

1830
  TestOrd* const testOrd = CAST_PTR(TestOrd, ssig.getDataPtrSend());
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
  testOrd->clear();
  
  if (blocks.size() == 0 || blocks[0] == "ALL") {
    // Logg command for all blocks
    testOrd->addSignalLoggerCommand(command, logSpec);
  } else {
    for(unsigned i = 0; i < blocks.size(); i++){
      int blockNumber = getBlockNumber(blocks[i]);
      if (blockNumber == -1) {
        return INVALID_BLOCK_NAME;
      }
      testOrd->addSignalLoggerCommand(blockNumber, command, logSpec);
    } // for
  } // else

1846
  return ss.sendSignal(nodeId, &ssig) == SEND_OK ? 0 : SEND_OR_RECEIVE_FAILED;
1847 1848 1849 1850 1851
}

/*****************************************************************************
 * Signal tracing
 *****************************************************************************/
1852
int MgmtSrvr::startSignalTracing(int nodeId)
1853
{
1854
  INIT_SIGNAL_SENDER(ss,nodeId);
1855
  
1856 1857 1858 1859
  SimpleSignal ssig;
  ssig.set(ss,TestOrd::TraceAPI, CMVMI, GSN_TEST_ORD, TestOrd::SignalLength);

  TestOrd* const testOrd = CAST_PTR(TestOrd, ssig.getDataPtrSend());
1860 1861 1862
  testOrd->clear();
  testOrd->setTestCommand(TestOrd::On);

1863
  return ss.sendSignal(nodeId, &ssig) == SEND_OK ? 0 : SEND_OR_RECEIVE_FAILED;
1864 1865 1866
}

int 
1867
MgmtSrvr::stopSignalTracing(int nodeId) 
1868
{
1869
  INIT_SIGNAL_SENDER(ss,nodeId);
1870

1871 1872 1873
  SimpleSignal ssig;
  ssig.set(ss,TestOrd::TraceAPI, CMVMI, GSN_TEST_ORD, TestOrd::SignalLength);
  TestOrd* const testOrd = CAST_PTR(TestOrd, ssig.getDataPtrSend());
1874 1875 1876
  testOrd->clear();
  testOrd->setTestCommand(TestOrd::Off);

1877
  return ss.sendSignal(nodeId, &ssig) == SEND_OK ? 0 : SEND_OR_RECEIVE_FAILED;
1878 1879 1880 1881 1882 1883 1884 1885
}


/*****************************************************************************
 * Dump state
 *****************************************************************************/

int
1886
MgmtSrvr::dumpState(int nodeId, const char* args)
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
{
  // Convert the space separeted args 
  // string to an int array
  Uint32 args_array[25];
  Uint32 numArgs = 0;

  char buf[10];  
  int b  = 0;
  memset(buf, 0, 10);
  for (size_t i = 0; i <= strlen(args); i++){
    if (args[i] == ' ' || args[i] == 0){
      args_array[numArgs] = atoi(buf);
      numArgs++;
      memset(buf, 0, 10);
      b = 0;
    } else {
      buf[b] = args[i];
      b++;
    }    
  }
  
1908
  return dumpState(nodeId, args_array, numArgs);
1909 1910 1911
}

int
1912
MgmtSrvr::dumpState(int nodeId, const Uint32 args[], Uint32 no)
1913
{
1914
  INIT_SIGNAL_SENDER(ss,nodeId);
1915 1916 1917

  const Uint32 len = no > 25 ? 25 : no;
  
1918
  SimpleSignal ssig;
1919
  DumpStateOrd * const dumpOrd = 
1920 1921
    CAST_PTR(DumpStateOrd, ssig.getDataPtrSend());
  ssig.set(ss,TestOrd::TraceAPI, CMVMI, GSN_DUMP_STATE_ORD, len);
1922 1923 1924 1925 1926 1927 1928
  for(Uint32 i = 0; i<25; i++){
    if (i < len)
      dumpOrd->args[i] = args[i];
    else
      dumpOrd->args[i] = 0;
  }
  
1929
  return ss.sendSignal(nodeId, &ssig) == SEND_OK ? 0 : SEND_OR_RECEIVE_FAILED;
1930 1931 1932 1933 1934 1935
}


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

1936
const char* MgmtSrvr::getErrorText(int errorCode, char *buf, int buf_sz)
1937 1938 1939 1940
{

  for (int i = 0; i < noOfErrorCodes; ++i) {
    if (errorCode == errorTable[i]._errorCode) {
1941 1942 1943
      BaseString::snprintf(buf, buf_sz, errorTable[i]._errorText);
      buf[buf_sz-1]= 0;
      return buf;
1944 1945
    }
  }
1946 1947 1948 1949 1950

  ndb_error_string(errorCode, buf, buf_sz);
  buf[buf_sz-1]= 0;

  return buf;
1951 1952 1953 1954 1955 1956 1957
}

void 
MgmtSrvr::handleReceivedSignal(NdbApiSignal* signal)
{
  // The way of handling a received signal is taken from the Ndb class.
  int gsn = signal->readSignalNumber();
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
1958

1959 1960 1961
  switch (gsn) {
  case GSN_EVENT_SUBSCRIBE_CONF:
    break;
1962 1963
  case GSN_EVENT_SUBSCRIBE_REF:
    break;
1964
  case GSN_EVENT_REP:
1965
  {
1966
    eventReport(signal->getDataPtr());
1967
    break;
1968
  }
1969

1970
  case GSN_NF_COMPLETEREP:
1971
    break;
1972
  case GSN_NODE_FAILREP:
1973 1974 1975
    break;

  default:
1976
    g_eventLogger.error("Unknown signal received. SignalNumber: "
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
			"%i from (%d, %x)",
			gsn,
			refToNode(signal->theSendersBlockRef),
			refToBlock(signal->theSendersBlockRef));
  }
  
  if (theWaitState == NO_WAIT) {
    NdbCondition_Signal(theMgmtWaitForResponseCondPtr);
  }
}

void
joreland@mysql.com's avatar
joreland@mysql.com committed
1989
MgmtSrvr::handleStatus(NodeId nodeId, bool alive, bool nfComplete)
1990
{
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1991 1992
  DBUG_ENTER("MgmtSrvr::handleStatus");
  Uint32 theData[25];
1993 1994
  EventReport *rep = (EventReport *)theData;

tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
1995
  theData[1] = nodeId;
1996
  if (alive) {
tomas@poseidon.mysql.com's avatar
tomas@poseidon.mysql.com committed
1997 1998 1999 2000
    if (nodeTypes[nodeId] == NODE_TYPE_DB)
    {
      m_started_nodes.push_back(nodeId);
    }
2001
    rep->setEventType(NDB_LE_Connected);
2002
  } else {
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2003
    rep->setEventType(NDB_LE_Disconnected);
joreland@mysql.com's avatar
joreland@mysql.com committed
2004 2005
    if(nfComplete)
    {
2006
      DBUG_VOID_RETURN;
joreland@mysql.com's avatar
joreland@mysql.com committed
2007
    }
2008
  }
2009 2010
  rep->setNodeId(_ownNodeId);
  eventReport(theData);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2011
  DBUG_VOID_RETURN;
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
}

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

void 
MgmtSrvr::signalReceivedNotification(void* mgmtSrvr, 
                                     NdbApiSignal* signal,
				     LinearSectionPtr ptr[3]) 
{
  ((MgmtSrvr*)mgmtSrvr)->handleReceivedSignal(signal);
}


//****************************************************************************
//****************************************************************************
void 
2029
MgmtSrvr::nodeStatusNotification(void* mgmSrv, Uint32 nodeId, 
2030 2031
				 bool alive, bool nfComplete)
{
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2032 2033
  DBUG_ENTER("MgmtSrvr::nodeStatusNotification");
  DBUG_PRINT("enter",("nodeid= %d, alive= %d, nfComplete= %d", nodeId, alive, nfComplete));
joreland@mysql.com's avatar
joreland@mysql.com committed
2034
  ((MgmtSrvr*)mgmSrv)->handleStatus(nodeId, alive, nfComplete);
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2035
  DBUG_VOID_RETURN;
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046
}

enum ndb_mgm_node_type 
MgmtSrvr::getNodeType(NodeId nodeId) const 
{
  if(nodeId >= MAX_NODES)
    return (enum ndb_mgm_node_type)-1;
  
  return nodeTypes[nodeId];
}

2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
const char *MgmtSrvr::get_connect_address(Uint32 node_id)
{
  if (m_connect_address[node_id].s_addr == 0 &&
      theFacade && theFacade->theTransporterRegistry &&
      theFacade->theClusterMgr &&
      getNodeType(node_id) == NDB_MGM_NODE_TYPE_NDB) 
  {
    const ClusterMgr::Node &node=
      theFacade->theClusterMgr->getNodeInfo(node_id);
    if (node.connected)
    {
      m_connect_address[node_id]=
	theFacade->theTransporterRegistry->get_connect_address(node_id);
    }
  }
  return inet_ntoa(m_connect_address[node_id]);  
}

2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
void
MgmtSrvr::get_connected_nodes(NodeBitmask &connected_nodes) const
{
  if (theFacade && theFacade->theClusterMgr) 
  {
    for(Uint32 i = 0; i < MAX_NODES; i++)
    {
      if (getNodeType(i) == NDB_MGM_NODE_TYPE_NDB)
      {
	const ClusterMgr::Node &node= theFacade->theClusterMgr->getNodeInfo(i);
2075
	connected_nodes.bitOR(node.m_state.m_connected_nodes);
2076 2077 2078 2079 2080
      }
    }
  }
}

2081
int
2082
MgmtSrvr::alloc_node_id_req(NodeId free_node_id, enum ndb_mgm_node_type type)
2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
{
  SignalSender ss(theFacade);
  ss.lock(); // lock will be released on exit

  SimpleSignal ssig;
  AllocNodeIdReq* req = CAST_PTR(AllocNodeIdReq, ssig.getDataPtrSend());
  ssig.set(ss, TestOrd::TraceAPI, QMGR, GSN_ALLOC_NODEID_REQ,
	   AllocNodeIdReq::SignalLength);
  
  req->senderRef = ss.getOwnRef();
  req->senderData = 19;
  req->nodeId = free_node_id;
2095
  req->nodeType = type;
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123

  int do_send = 1;
  NodeId nodeId = 0;
  while (1)
  {
    if (nodeId == 0)
    {
      bool next;
      while((next = getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB)) == true &&
            theFacade->get_node_alive(nodeId) == false);
      if (!next)
        return NO_CONTACT_WITH_DB_NODES;
      do_send = 1;
    }
    if (do_send)
    {
      if (ss.sendSignal(nodeId, &ssig) != SEND_OK) {
        return SEND_OR_RECEIVE_FAILED;
      }
      do_send = 0;
    }
    
    SimpleSignal *signal = ss.waitFor();

    int gsn = signal->readSignalNumber();
    switch (gsn) {
    case GSN_ALLOC_NODEID_CONF:
    {
2124
#ifdef NOT_USED
2125 2126
      const AllocNodeIdConf * const conf =
        CAST_CONSTPTR(AllocNodeIdConf, signal->getDataPtr());
2127
#endif
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138
      return 0;
    }
    case GSN_ALLOC_NODEID_REF:
    {
      const AllocNodeIdRef * const ref =
        CAST_CONSTPTR(AllocNodeIdRef, signal->getDataPtr());
      if (ref->errorCode == AllocNodeIdRef::NotMaster ||
          ref->errorCode == AllocNodeIdRef::Busy)
      {
        do_send = 1;
        nodeId = refToNode(ref->masterRef);
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2139 2140
	if (!theFacade->get_node_alive(nodeId))
	  nodeId = 0;
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
        continue;
      }
      return ref->errorCode;
    }
    case GSN_NF_COMPLETEREP:
    {
      const NFCompleteRep * const rep =
        CAST_CONSTPTR(NFCompleteRep, signal->getDataPtr());
#ifdef VM_TRACE
      ndbout_c("Node %d fail completed", rep->failedNodeId);
#endif
      if (rep->failedNodeId == nodeId)
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2153 2154
      {
	do_send = 1;
2155
        nodeId = 0;
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2156
      }
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
      continue;
    }
    case GSN_NODE_FAILREP:{
      // ignore NF_COMPLETEREP will come
      continue;
    }
    default:
      report_unknown_signal(signal);
      return SEND_OR_RECEIVE_FAILED;
    }
  }
  return 0;
}

tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2171
bool
joreland@mysql.com's avatar
joreland@mysql.com committed
2172 2173 2174
MgmtSrvr::alloc_node_id(NodeId * nodeId, 
			enum ndb_mgm_node_type type,
			struct sockaddr *client_addr, 
2175
			SOCKET_SIZE_TYPE *client_addr_len,
2176 2177
			int &error_code, BaseString &error_string,
                        int log_event)
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2178
{
2179
  DBUG_ENTER("MgmtSrvr::alloc_node_id");
2180 2181
  DBUG_PRINT("enter", ("nodeid: %d  type: %d  client_addr: 0x%ld",
		       *nodeId, type, (long) client_addr));
2182 2183
  if (g_no_nodeid_checks) {
    if (*nodeId == 0) {
2184
      error_string.appfmt("no-nodeid-checks set in management server.\n"
2185
			  "node id must be set explicitly in connectstring");
2186
      error_code = NDB_MGM_ALLOCID_CONFIG_MISMATCH;
2187 2188 2189 2190
      DBUG_RETURN(false);
    }
    DBUG_RETURN(true);
  }
2191
  Guard g(m_node_id_mutex);
2192
  int no_mgm= 0;
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2193
  NodeBitmask connected_nodes(m_reserved_nodes);
2194
  get_connected_nodes(connected_nodes);
2195
  {
2196 2197 2198
    for(Uint32 i = 0; i < MAX_NODES; i++)
      if (getNodeType(i) == NDB_MGM_NODE_TYPE_MGM)
	no_mgm++;
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2199
  }
2200 2201 2202
  bool found_matching_id= false;
  bool found_matching_type= false;
  bool found_free_node= false;
2203 2204
  unsigned id_found= 0;
  const char *config_hostname= 0;
2205 2206
  struct in_addr config_addr= {0};
  int r_config_addr= -1;
2207 2208
  unsigned type_c= 0;

2209 2210
  if(NdbMutex_Lock(m_configMutex))
  {
2211
    // should not happen
2212
    error_string.appfmt("unable to lock configuration mutex");
2213 2214
    error_code = NDB_MGM_ALLOCID_ERROR;
    DBUG_RETURN(false);
2215
  }
2216
  ndb_mgm_configuration_iterator
2217
    iter(* _config->m_configValues, CFG_SECTION_NODE);
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2218 2219
  for(iter.first(); iter.valid(); iter.next()) {
    unsigned tmp= 0;
2220
    if(iter.get(CFG_NODE_ID, &tmp)) require(false);
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2221 2222
    if (*nodeId && *nodeId != tmp)
      continue;
2223
    found_matching_id= true;
2224
    if(iter.get(CFG_TYPE_OF_SECTION, &type_c)) require(false);
joreland@mysql.com's avatar
joreland@mysql.com committed
2225
    if(type_c != (unsigned)type)
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2226
      continue;
2227 2228 2229 2230
    found_matching_type= true;
    if (connected_nodes.get(tmp))
      continue;
    found_free_node= true;
2231
    if(iter.get(CFG_NODE_HOST, &config_hostname)) require(false);
2232 2233 2234
    if (config_hostname && config_hostname[0] == 0)
      config_hostname= 0;
    else if (client_addr) {
2235
      // check hostname compatability
2236 2237 2238
      const void *tmp_in= &(((sockaddr_in*)client_addr)->sin_addr);
      if((r_config_addr= Ndb_getInAddr(&config_addr, config_hostname)) != 0
	 || memcmp(&config_addr, tmp_in, sizeof(config_addr)) != 0) {
2239 2240
	struct in_addr tmp_addr;
	if(Ndb_getInAddr(&tmp_addr, "localhost") != 0
2241
	   || memcmp(&tmp_addr, tmp_in, sizeof(config_addr)) != 0) {
2242
	  // not localhost
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2243
#if 0
2244 2245 2246
	  ndbout << "MgmtSrvr::getFreeNodeId compare failed for \""
		 << config_hostname
		 << "\" id=" << tmp << endl;
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2247
#endif
2248 2249 2250
	  continue;
	}
	// connecting through localhost
2251 2252 2253 2254 2255 2256 2257 2258
	// check if config_hostname is local
	if (!SocketServer::tryBind(0,config_hostname)) {
	  continue;
	}
      }
    } else { // client_addr == 0
      if (!SocketServer::tryBind(0,config_hostname)) {
	continue;
2259
      }
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2260
    }
2261 2262 2263
    if (*nodeId != 0 ||
	type != NDB_MGM_NODE_TYPE_MGM ||
	no_mgm == 1) { // any match is ok
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275

      if (config_hostname == 0 &&
	  *nodeId == 0 &&
	  type != NDB_MGM_NODE_TYPE_MGM)
      {
	if (!id_found) // only set if not set earlier
	  id_found= tmp;
	continue; /* continue looking for a nodeid with specified
		   * hostname
		   */
      }
      assert(id_found == 0);
2276 2277 2278 2279 2280 2281 2282 2283
      id_found= tmp;
      break;
    }
    if (id_found) { // mgmt server may only have one match
      error_string.appfmt("Ambiguous node id's %d and %d.\n"
			  "Suggest specifying node id in connectstring,\n"
			  "or specifying unique host names in config file.",
			  id_found, tmp);
2284
      NdbMutex_Unlock(m_configMutex);
2285
      error_code = NDB_MGM_ALLOCID_CONFIG_MISMATCH;
2286 2287 2288 2289 2290
      DBUG_RETURN(false);
    }
    if (config_hostname == 0) {
      error_string.appfmt("Ambiguity for node id %d.\n"
			  "Suggest specifying node id in connectstring,\n"
2291
			  "or specifying unique host names in config file,\n"
2292 2293
			  "or specifying just one mgmt server in config file.",
			  tmp);
2294
      error_code = NDB_MGM_ALLOCID_CONFIG_MISMATCH;
2295 2296 2297 2298
      DBUG_RETURN(false);
    }
    id_found= tmp; // mgmt server matched, check for more matches
  }
2299
  NdbMutex_Unlock(m_configMutex);
2300

2301 2302
  if (id_found && client_addr != 0)
  {
2303
    int res = alloc_node_id_req(id_found, type);
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
    unsigned save_id_found = id_found;
    switch (res)
    {
    case 0:
      // ok continue
      break;
    case NO_CONTACT_WITH_DB_NODES:
      // ok continue
      break;
    default:
      // something wrong
      id_found = 0;
      break;

    }
    if (id_found == 0)
    {
      char buf[128];
      ndb_error_string(res, buf, sizeof(buf));
      error_string.appfmt("Cluster refused allocation of id %d. Error: %d (%s).",
			  save_id_found, res, buf);
      g_eventLogger.warning("Cluster refused allocation of id %d. "
                            "Connection from ip %s. "
                            "Returned error string \"%s\"", save_id_found,
                            inet_ntoa(((struct sockaddr_in *)(client_addr))->sin_addr),
                            error_string.c_str());
      DBUG_RETURN(false);
    }
  }

2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
  if (id_found)
  {
    *nodeId= id_found;
    DBUG_PRINT("info", ("allocating node id %d",*nodeId));
    {
      int r= 0;
      if (client_addr)
	m_connect_address[id_found]=
	  ((struct sockaddr_in *)client_addr)->sin_addr;
      else if (config_hostname)
	r= Ndb_getInAddr(&(m_connect_address[id_found]), config_hostname);
      else {
	char name[256];
	r= gethostname(name, sizeof(name));
	if (r == 0) {
	  name[sizeof(name)-1]= 0;
	  r= Ndb_getInAddr(&(m_connect_address[id_found]), name);
	}
      }
      if (r)
	m_connect_address[id_found].s_addr= 0;
    }
    m_reserved_nodes.set(id_found);
2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
    if (theFacade && id_found != theFacade->ownId())
    {
      /**
       * Make sure we're ready to accept connections from this node
       */
      theFacade->lock_mutex();
      theFacade->doConnect(id_found);
      theFacade->unlock_mutex();
    }
    
2367 2368
    char tmp_str[128];
    m_reserved_nodes.getText(tmp_str);
2369 2370 2371
    g_eventLogger.info("Mgmt server state: nodeid %d reserved for ip %s, "
                       "m_reserved_nodes %s.",
                       id_found, get_connect_address(id_found), tmp_str);
2372
    DBUG_RETURN(true);
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2373
  }
2374 2375

  if (found_matching_type && !found_free_node) {
2376 2377
    // we have a temporary error which might be due to that 
    // we have got the latest connect status from db-nodes.  Force update.
stewart@willster.(none)'s avatar
stewart@willster.(none) committed
2378
    updateStatus();
2379 2380
  }

2381 2382 2383 2384 2385
  BaseString type_string, type_c_string;
  {
    const char *alias, *str;
    alias= ndb_mgm_get_node_type_alias_string(type, &str);
    type_string.assfmt("%s(%s)", alias, str);
2386 2387
    alias= ndb_mgm_get_node_type_alias_string((enum ndb_mgm_node_type)type_c,
					      &str);
2388 2389 2390
    type_c_string.assfmt("%s(%s)", alias, str);
  }

2391 2392
  if (*nodeId == 0)
  {
2393
    if (found_matching_id)
2394
    {
2395
      if (found_matching_type)
2396
      {
2397
	if (found_free_node)
2398
        {
2399
	  error_string.appfmt("Connection done from wrong host ip %s.",
2400
			      (client_addr)?
2401
                              inet_ntoa(((struct sockaddr_in *)
2402
					 (client_addr))->sin_addr):"");
2403 2404
          error_code = NDB_MGM_ALLOCID_ERROR;
        }
2405
	else
2406
        {
2407 2408
	  error_string.appfmt("No free node id found for %s.",
			      type_string.c_str());
2409 2410 2411
          error_code = NDB_MGM_ALLOCID_ERROR;
        }
      }
2412
      else
2413
      {
2414 2415
	error_string.appfmt("No %s node defined in config file.",
			    type_string.c_str());
2416 2417 2418
        error_code = NDB_MGM_ALLOCID_CONFIG_MISMATCH;
      }
    }
2419
    else
2420
    {
2421
      error_string.append("No nodes defined in config file.");
2422 2423 2424 2425 2426
      error_code = NDB_MGM_ALLOCID_CONFIG_MISMATCH;
    }
  }
  else
  {
2427
    if (found_matching_id)
2428
    {
2429
      if (found_matching_type)
2430 2431 2432
      {
	if (found_free_node)
        {
2433 2434
	  // have to split these into two since inet_ntoa overwrites itself
	  error_string.appfmt("Connection with id %d done from wrong host ip %s,",
2435 2436
			      *nodeId, inet_ntoa(((struct sockaddr_in *)
						  (client_addr))->sin_addr));
2437
	  error_string.appfmt(" expected %s(%s).", config_hostname,
2438 2439
			      r_config_addr ?
			      "lookup failed" : inet_ntoa(config_addr));
2440 2441 2442 2443
          error_code = NDB_MGM_ALLOCID_CONFIG_MISMATCH;
	}
        else
        {
2444 2445
	  error_string.appfmt("Id %d already allocated by another node.",
			      *nodeId);
2446 2447 2448
          error_code = NDB_MGM_ALLOCID_ERROR;
        }
      }
2449
      else
2450
      {
2451
	error_string.appfmt("Id %d configured as %s, connect attempted as %s.",
2452 2453
			    *nodeId, type_c_string.c_str(),
			    type_string.c_str());
2454 2455 2456
        error_code = NDB_MGM_ALLOCID_CONFIG_MISMATCH;
      }
    }
2457
    else
2458
    {
2459 2460
      error_string.appfmt("No node defined with id=%d in config file.",
			  *nodeId);
2461 2462
      error_code = NDB_MGM_ALLOCID_CONFIG_MISMATCH;
    }
2463
  }
2464

2465
  if (log_event || error_code == NDB_MGM_ALLOCID_CONFIG_MISMATCH)
2466
  {
2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477
    g_eventLogger.warning("Allocate nodeid (%d) failed. Connection from ip %s."
                          " Returned error string \"%s\"",
                          *nodeId,
                          client_addr != 0
                          ? inet_ntoa(((struct sockaddr_in *)
                                       (client_addr))->sin_addr)
                          : "<none>",
                          error_string.c_str());

    NodeBitmask connected_nodes2;
    get_connected_nodes(connected_nodes2);
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491
    BaseString tmp_connected, tmp_not_connected;
    for(Uint32 i = 0; i < MAX_NODES; i++)
    {
      if (connected_nodes2.get(i))
      {
	if (!m_reserved_nodes.get(i))
	  tmp_connected.appfmt(" %d", i);
      }
      else if (m_reserved_nodes.get(i))
      {
	tmp_not_connected.appfmt(" %d", i);
      }
    }
    if (tmp_connected.length() > 0)
2492
      g_eventLogger.info("Mgmt server state: node id's %s connected but not reserved", 
2493 2494
			 tmp_connected.c_str());
    if (tmp_not_connected.length() > 0)
2495
      g_eventLogger.info("Mgmt server state: node id's %s not connected but reserved",
2496 2497
			 tmp_not_connected.c_str());
  }
2498
  DBUG_RETURN(false);
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2499 2500
}

2501 2502 2503 2504 2505 2506 2507 2508 2509
bool
MgmtSrvr::getNextNodeId(NodeId * nodeId, enum ndb_mgm_node_type type) const 
{
  NodeId tmp = * nodeId;

  tmp++;
  while(nodeTypes[tmp] != type && tmp < MAX_NODES)
    tmp++;
  
2510
  if(tmp == MAX_NODES){
2511
    return false;
2512
  }
2513 2514 2515 2516 2517

  * nodeId = tmp;
  return true;
}

joreland@mysql.com's avatar
joreland@mysql.com committed
2518 2519
#include "Services.hpp"

2520
void
2521
MgmtSrvr::eventReport(const Uint32 * theData)
2522 2523
{
  const EventReport * const eventReport = (EventReport *)&theData[0];
joreland@mysql.com's avatar
joreland@mysql.com committed
2524
  
2525
  NodeId nodeId = eventReport->getNodeId();
2526
  Ndb_logevent_type type = eventReport->getEventType();
2527
  // Log event
2528
  g_eventLogger.log(type, theData, nodeId, 
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2529 2530
		    &m_event_listner[0].m_logLevel);  
  m_event_listner.log(type, theData, nodeId);
2531 2532 2533 2534 2535
}

/***************************************************************************
 * Backup
 ***************************************************************************/
2536

2537
int
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
2538
MgmtSrvr::startBackup(Uint32& backupId, int waitCompleted)
2539
{
2540 2541 2542
  SignalSender ss(theFacade);
  ss.lock(); // lock will be released on exit

2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
  NodeId nodeId = m_master_node;
  if (okToSendTo(nodeId, false) != 0)
  {
    bool next;
    nodeId = m_master_node = 0;
    while((next = getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB)) == true &&
          okToSendTo(nodeId, false) != 0);
    if(!next)
      return NO_CONTACT_WITH_DB_NODES;
  }
2553

2554 2555 2556 2557
  SimpleSignal ssig;
  BackupReq* req = CAST_PTR(BackupReq, ssig.getDataPtrSend());
  ssig.set(ss, TestOrd::TraceAPI, BACKUP, GSN_BACKUP_REQ, 
	   BackupReq::SignalLength);
2558 2559 2560
  
  req->senderData = 19;
  req->backupDataLen = 0;
2561 2562
  assert(waitCompleted < 3);
  req->flags = waitCompleted & 0x3;
2563

2564 2565 2566 2567 2568
  BackupEvent event;
  int do_send = 1;
  while (1) {
    if (do_send)
    {
2569
      if (ss.sendSignal(nodeId, &ssig) != SEND_OK) {
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593
	return SEND_OR_RECEIVE_FAILED;
      }
      if (waitCompleted == 0)
	return 0;
      do_send = 0;
    }
    SimpleSignal *signal = ss.waitFor();

    int gsn = signal->readSignalNumber();
    switch (gsn) {
    case GSN_BACKUP_CONF:{
      const BackupConf * const conf = 
	CAST_CONSTPTR(BackupConf, signal->getDataPtr());
      event.Event = BackupEvent::BackupStarted;
      event.Started.BackupId = conf->backupId;
      event.Nodes = conf->nodes;
#ifdef VM_TRACE
      ndbout_c("Backup(%d) master is %d", conf->backupId,
	       refToNode(signal->header.theSendersBlockRef));
#endif
      backupId = conf->backupId;
      if (waitCompleted == 1)
	return 0;
      // wait for next signal
2594
      break;
2595 2596 2597 2598 2599
    }
    case GSN_BACKUP_COMPLETE_REP:{
      const BackupCompleteRep * const rep = 
	CAST_CONSTPTR(BackupCompleteRep, signal->getDataPtr());
#ifdef VM_TRACE
2600
      ndbout_c("Backup(%d) completed", rep->backupId);
2601 2602 2603 2604
#endif
      event.Event = BackupEvent::BackupCompleted;
      event.Completed.BackupId = rep->backupId;
    
2605
      event.Completed.NoOfBytes = rep->noOfBytesLow;
2606
      event.Completed.NoOfLogBytes = rep->noOfLogBytes;
2607
      event.Completed.NoOfRecords = rep->noOfRecordsLow;
2608 2609 2610 2611 2612
      event.Completed.NoOfLogRecords = rep->noOfLogRecords;
      event.Completed.stopGCP = rep->stopGCP;
      event.Completed.startGCP = rep->startGCP;
      event.Nodes = rep->nodes;

2613 2614 2615 2616 2617 2618
      if (signal->header.theLength >= BackupCompleteRep::SignalLength)
      {
        event.Completed.NoOfBytes += ((Uint64)rep->noOfBytesHigh) << 32;
        event.Completed.NoOfRecords += ((Uint64)rep->noOfRecordsHigh) << 32;
      }

2619 2620 2621 2622 2623 2624 2625
      backupId = rep->backupId;
      return 0;
    }
    case GSN_BACKUP_REF:{
      const BackupRef * const ref = 
	CAST_CONSTPTR(BackupRef, signal->getDataPtr());
      if(ref->errorCode == BackupRef::IAmNotMaster){
2626
	m_master_node = nodeId = refToNode(ref->masterRef);
2627 2628 2629 2630
#ifdef VM_TRACE
	ndbout_c("I'm not master resending to %d", nodeId);
#endif
	do_send = 1; // try again
jonas@perch.ndb.mysql.com's avatar
jonas@perch.ndb.mysql.com committed
2631 2632
	if (!theFacade->get_node_alive(nodeId))
	  m_master_node = nodeId = 0;
2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661
	continue;
      }
      event.Event = BackupEvent::BackupFailedToStart;
      event.FailedToStart.ErrorCode = ref->errorCode;
      return ref->errorCode;
    }
    case GSN_BACKUP_ABORT_REP:{
      const BackupAbortRep * const rep = 
	CAST_CONSTPTR(BackupAbortRep, signal->getDataPtr());
      event.Event = BackupEvent::BackupAborted;
      event.Aborted.Reason = rep->reason;
      event.Aborted.BackupId = rep->backupId;
      event.Aborted.ErrorCode = rep->reason;
#ifdef VM_TRACE
      ndbout_c("Backup %d aborted", rep->backupId);
#endif
      return rep->reason;
    }
    case GSN_NF_COMPLETEREP:{
      const NFCompleteRep * const rep =
	CAST_CONSTPTR(NFCompleteRep, signal->getDataPtr());
#ifdef VM_TRACE
      ndbout_c("Node %d fail completed", rep->failedNodeId);
#endif
      if (rep->failedNodeId == nodeId ||
	  waitCompleted == 1)
	return 1326;
      // wait for next signal
      // master node will report aborted backup
2662
      break;
2663 2664 2665 2666
    }
    case GSN_NODE_FAILREP:{
      const NodeFailRep * const rep =
	CAST_CONSTPTR(NodeFailRep, signal->getDataPtr());
2667
      if (NodeBitmask::get(rep->theNodes,nodeId) ||
2668
	  waitCompleted == 1)
2669
	return 1326;
2670 2671
      // wait for next signal
      // master node will report aborted backup
2672 2673
      break;
    }
2674 2675 2676 2677
    default:
      report_unknown_signal(signal);
      return SEND_OR_RECEIVE_FAILED;
    }
2678 2679 2680 2681 2682 2683
  }
}

int 
MgmtSrvr::abortBackup(Uint32 backupId)
{
2684
  SignalSender ss(theFacade);
2685
  ss.lock(); // lock will be released on exit
2686

2687 2688 2689 2690 2691 2692 2693 2694 2695
  bool next;
  NodeId nodeId = 0;
  while((next = getNextNodeId(&nodeId, NDB_MGM_NODE_TYPE_NDB)) == true &&
	theFacade->get_node_alive(nodeId) == false);
  
  if(!next){
    return NO_CONTACT_WITH_DB_NODES;
  }
  
2696
  SimpleSignal ssig;
2697

2698 2699 2700
  AbortBackupOrd* ord = CAST_PTR(AbortBackupOrd, ssig.getDataPtrSend());
  ssig.set(ss, TestOrd::TraceAPI, BACKUP, GSN_ABORT_BACKUP_ORD, 
	   AbortBackupOrd::SignalLength);
2701 2702 2703 2704 2705
  
  ord->requestType = AbortBackupOrd::ClientAbort;
  ord->senderData = 19;
  ord->backupId = backupId;
  
2706
  return ss.sendSignal(nodeId, &ssig) == SEND_OK ? 0 : SEND_OR_RECEIVE_FAILED;
2707
}
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2708 2709 2710 2711 2712


MgmtSrvr::Allocated_resources::Allocated_resources(MgmtSrvr &m)
  : m_mgmsrv(m)
{
2713 2714
  m_reserved_nodes.clear();
  m_alloc_timeout= 0;
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2715 2716 2717 2718
}

MgmtSrvr::Allocated_resources::~Allocated_resources()
{
2719
  Guard g(m_mgmsrv.m_node_id_mutex);
2720
  if (!m_reserved_nodes.isclear()) {
2721
    m_mgmsrv.m_reserved_nodes.bitANDC(m_reserved_nodes); 
2722
    // node has been reserved, force update signal to ndb nodes
stewart@willster.(none)'s avatar
stewart@willster.(none) committed
2723
    m_mgmsrv.updateStatus();
2724 2725 2726

    char tmp_str[128];
    m_mgmsrv.m_reserved_nodes.getText(tmp_str);
2727
    g_eventLogger.info("Mgmt server state: nodeid %d freed, m_reserved_nodes %s.",
2728
		       get_nodeid(), tmp_str);
2729
  }
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2730 2731 2732
}

void
2733
MgmtSrvr::Allocated_resources::reserve_node(NodeId id, NDB_TICKS timeout)
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2734 2735
{
  m_reserved_nodes.set(id);
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
  m_alloc_timeout= NdbTick_CurrentMillisecond() + timeout;
}

bool
MgmtSrvr::Allocated_resources::is_timed_out(NDB_TICKS tick)
{
  if (m_alloc_timeout && tick > m_alloc_timeout)
  {
    g_eventLogger.info("Mgmt server state: nodeid %d timed out.",
                       get_nodeid());
    return true;
  }
  return false;
tomas@poseidon.bredbandsbolaget.se's avatar
tomas@poseidon.bredbandsbolaget.se committed
2749 2750
}

2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
NodeId
MgmtSrvr::Allocated_resources::get_nodeid() const
{
  for(Uint32 i = 0; i < MAX_NODES; i++)
  {
    if (m_reserved_nodes.get(i))
      return i;
  }
  return 0;
}

2762 2763 2764
int
MgmtSrvr::setDbParameter(int node, int param, const char * value,
			 BaseString& msg){
2765 2766 2767 2768

  if(NdbMutex_Lock(m_configMutex))
    return -1;

2769 2770 2771
  /**
   * Check parameter
   */
2772 2773
  ndb_mgm_configuration_iterator
    iter(* _config->m_configValues, CFG_SECTION_NODE);
2774 2775
  if(iter.first() != 0){
    msg.assign("Unable to find node section (iter.first())");
2776
    NdbMutex_Unlock(m_configMutex);
2777 2778 2779 2780 2781 2782 2783
    return -1;
  }
  
  Uint32 type = NODE_TYPE_DB + 1;
  if(node != 0){
    if(iter.find(CFG_NODE_ID, node) != 0){
      msg.assign("Unable to find node (iter.find())");
2784
      NdbMutex_Unlock(m_configMutex);
2785 2786 2787 2788
      return -1;
    }
    if(iter.get(CFG_TYPE_OF_SECTION, &type) != 0){
      msg.assign("Unable to get node type(iter.get(CFG_TYPE_OF_SECTION))");
2789
      NdbMutex_Unlock(m_configMutex);
2790 2791 2792 2793 2794 2795
      return -1;
    }
  } else {
    do {
      if(iter.get(CFG_TYPE_OF_SECTION, &type) != 0){
	msg.assign("Unable to get node type(iter.get(CFG_TYPE_OF_SECTION))");
2796
	NdbMutex_Unlock(m_configMutex);
2797 2798 2799 2800 2801 2802 2803 2804 2805 2806
	return -1;
      }
      if(type == NODE_TYPE_DB)
	break;
    } while(iter.next() == 0);
  }
  
  if(type != NODE_TYPE_DB){
    msg.assfmt("Invalid node type or no such node (%d %d)", 
	       type, NODE_TYPE_DB);
2807
    NdbMutex_Unlock(m_configMutex);
2808 2809 2810 2811 2812
    return -1;
  }

  int p_type;
  unsigned val_32;
joreland@mysql.com's avatar
joreland@mysql.com committed
2813
  Uint64 val_64;
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
  const char * val_char;
  do {
    p_type = 0;
    if(iter.get(param, &val_32) == 0){
      val_32 = atoi(value);
      break;
    }
    
    p_type++;
    if(iter.get(param, &val_64) == 0){
2824
      val_64 = strtoll(value, 0, 10);
2825 2826 2827 2828 2829 2830 2831 2832
      break;
    }
    p_type++;
    if(iter.get(param, &val_char) == 0){
      val_char = value;
      break;
    }
    msg.assign("Could not get parameter");
2833
    NdbMutex_Unlock(m_configMutex);
2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853
    return -1;
  } while(0);
  
  bool res = false;
  do {
    int ret = iter.get(CFG_TYPE_OF_SECTION, &type);
    assert(ret == 0);
    
    if(type != NODE_TYPE_DB)
      continue;
    
    Uint32 node;
    ret = iter.get(CFG_NODE_ID, &node);
    assert(ret == 0);
    
    ConfigValues::Iterator i2(_config->m_configValues->m_config, 
			      iter.m_config);
    switch(p_type){
    case 0:
      res = i2.set(param, val_32);
2854
      ndbout_c("Updating node %d param: %d to %d",  node, param, val_32);
2855 2856 2857
      break;
    case 1:
      res = i2.set(param, val_64);
2858
      ndbout_c("Updating node %d param: %d to %u",  node, param, val_32);
2859 2860 2861
      break;
    case 2:
      res = i2.set(param, val_char);
2862
      ndbout_c("Updating node %d param: %d to %s",  node, param, val_char);
2863 2864
      break;
    default:
2865
      require(false);
2866 2867 2868 2869 2870
    }
    assert(res);
  } while(node == 0 && iter.next() == 0);

  msg.assign("Success");
2871
  NdbMutex_Unlock(m_configMutex);
2872 2873
  return 0;
}
2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
int
MgmtSrvr::setConnectionDbParameter(int node1, 
				   int node2,
				   int param,
				   int value,
				   BaseString& msg){
  Uint32 current_value,new_value;

  DBUG_ENTER("MgmtSrvr::setConnectionDbParameter");

2884 2885 2886 2887 2888 2889 2890
  if(NdbMutex_Lock(m_configMutex))
  {
    DBUG_RETURN(-1);
  }

  ndb_mgm_configuration_iterator 
    iter(* _config->m_configValues, CFG_SECTION_CONNECTION);
2891 2892 2893

  if(iter.first() != 0){
    msg.assign("Unable to find connection section (iter.first())");
2894 2895
    NdbMutex_Unlock(m_configMutex);
    DBUG_RETURN(-1);
2896 2897 2898 2899 2900 2901
  }

  for(;iter.valid();iter.next()) {
    Uint32 n1,n2;
    iter.get(CFG_CONNECTION_NODE_1, &n1);
    iter.get(CFG_CONNECTION_NODE_2, &n2);
2902 2903
    if((n1 == (unsigned)node1 && n2 == (unsigned)node2)
       || (n1 == (unsigned)node2 && n2 == (unsigned)node1))
2904 2905 2906 2907
      break;
  }
  if(!iter.valid()) {
    msg.assign("Unable to find connection between nodes");
2908
    NdbMutex_Unlock(m_configMutex);
2909
    DBUG_RETURN(-2);
2910 2911
  }
  
2912
  if(iter.get(param, &current_value) != 0) {
2913
    msg.assign("Unable to get current value of parameter");
2914
    NdbMutex_Unlock(m_configMutex);
2915
    DBUG_RETURN(-3);
2916 2917 2918 2919 2920
  }

  ConfigValues::Iterator i2(_config->m_configValues->m_config, 
			    iter.m_config);

tulin@build.mysql.com's avatar
tulin@build.mysql.com committed
2921
  if(i2.set(param, (unsigned)value) == false) {
2922
    msg.assign("Unable to set new value of parameter");
2923
    NdbMutex_Unlock(m_configMutex);
2924
    DBUG_RETURN(-4);
2925 2926
  }
  
2927
  if(iter.get(param, &new_value) != 0) {
2928
    msg.assign("Unable to get parameter after setting it.");
2929
    NdbMutex_Unlock(m_configMutex);
2930
    DBUG_RETURN(-5);
2931 2932 2933
  }

  msg.assfmt("%u -> %u",current_value,new_value);
2934
  NdbMutex_Unlock(m_configMutex);
2935
  DBUG_RETURN(1);
2936 2937 2938
}


2939 2940 2941 2942
int
MgmtSrvr::getConnectionDbParameter(int node1, 
				   int node2,
				   int param,
2943
				   int *value,
2944 2945 2946
				   BaseString& msg){
  DBUG_ENTER("MgmtSrvr::getConnectionDbParameter");

2947 2948 2949 2950 2951 2952 2953
  if(NdbMutex_Lock(m_configMutex))
  {
    DBUG_RETURN(-1);
  }

  ndb_mgm_configuration_iterator
    iter(* _config->m_configValues, CFG_SECTION_CONNECTION);
2954 2955 2956

  if(iter.first() != 0){
    msg.assign("Unable to find connection section (iter.first())");
2957 2958
    NdbMutex_Unlock(m_configMutex);
    DBUG_RETURN(-1);
2959 2960 2961
  }

  for(;iter.valid();iter.next()) {
2962
    Uint32 n1=0,n2=0;
2963 2964
    iter.get(CFG_CONNECTION_NODE_1, &n1);
    iter.get(CFG_CONNECTION_NODE_2, &n2);
2965 2966
    if((n1 == (unsigned)node1 && n2 == (unsigned)node2)
       || (n1 == (unsigned)node2 && n2 == (unsigned)node1))
2967 2968 2969 2970
      break;
  }
  if(!iter.valid()) {
    msg.assign("Unable to find connection between nodes");
2971 2972
    NdbMutex_Unlock(m_configMutex);
    DBUG_RETURN(-1);
2973 2974
  }
  
2975
  if(iter.get(param, (Uint32*)value) != 0) {
2976
    msg.assign("Unable to get current value of parameter");
2977 2978
    NdbMutex_Unlock(m_configMutex);
    DBUG_RETURN(-1);
2979 2980
  }

2981
  msg.assfmt("%d",*value);
2982
  NdbMutex_Unlock(m_configMutex);
2983
  DBUG_RETURN(1);
2984
}
2985

2986 2987
void MgmtSrvr::transporter_connect(NDB_SOCKET_TYPE sockfd)
{
2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999
  if (theFacade->get_registry()->connect_server(sockfd))
  {
    /**
     * Force an update_connections() so that the
     * ClusterMgr and TransporterFacade is up to date
     * with the new connection.
     * Important for correct node id reservation handling
     */
    NdbMutex_Lock(theFacade->theMutexPtr);
    theFacade->get_registry()->update_connections();
    NdbMutex_Unlock(theFacade->theMutexPtr);
  }
3000 3001
}

3002
int MgmtSrvr::connect_to_self(void)
3003
{
3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018
  int r= 0;
  m_local_mgm_handle= ndb_mgm_create_handle();
  snprintf(m_local_mgm_connect_string,sizeof(m_local_mgm_connect_string),
           "localhost:%u",getPort());
  ndb_mgm_set_connectstring(m_local_mgm_handle, m_local_mgm_connect_string);

  if((r= ndb_mgm_connect(m_local_mgm_handle, 0, 0, 0)) < 0)
  {
    ndb_mgm_destroy_handle(&m_local_mgm_handle);
    return r;
  }
  // TransporterRegistry now owns this NdbMgmHandle and will destroy it.
  theFacade->get_registry()->set_mgm_handle(m_local_mgm_handle);

  return 0;
3019 3020 3021
}


joreland@mysql.com's avatar
joreland@mysql.com committed
3022 3023

template class MutexVector<unsigned short>;
tomas@poseidon.ndb.mysql.com's avatar
tomas@poseidon.ndb.mysql.com committed
3024
template class MutexVector<Ndb_mgmd_event_service::Event_listener>;
joreland@mysql.com's avatar
joreland@mysql.com committed
3025
template class MutexVector<EventSubscribeReq>;