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

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

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

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

17
#include <ndb_global.h>
unknown's avatar
unknown committed
18
#include <my_pthread.h>
19

unknown's avatar
unknown committed
20
#include <TransporterRegistry.hpp>
21 22 23
#include "TransporterInternalDefinitions.hpp"

#include "Transporter.hpp"
unknown's avatar
unknown committed
24
#include <SocketAuthenticator.hpp>
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

#ifdef NDB_TCP_TRANSPORTER
#include "TCP_Transporter.hpp"
#endif

#ifdef NDB_OSE_TRANSPORTER
#include "OSE_Receiver.hpp"
#include "OSE_Transporter.hpp"
#endif

#ifdef NDB_SCI_TRANSPORTER
#include "SCI_Transporter.hpp"
#endif

#ifdef NDB_SHM_TRANSPORTER
#include "SHM_Transporter.hpp"
41
extern int g_ndb_shm_signum;
42 43 44 45 46 47
#endif

#include "TransporterCallback.hpp"
#include "NdbOut.hpp"
#include <NdbSleep.h>
#include <NdbTick.h>
unknown's avatar
unknown committed
48 49 50
#include <InputStream.hpp>
#include <OutputStream.hpp>

51
#include <mgmapi/mgmapi.h>
52 53
#include <mgmapi/mgmapi_debug.h>

54 55 56
#include <EventLogger.hpp>
extern EventLogger g_eventLogger;

unknown's avatar
unknown committed
57 58
SocketServer::Session * TransporterService::newSession(NDB_SOCKET_TYPE sockfd)
{
unknown's avatar
unknown committed
59
  DBUG_ENTER("SocketServer::Session * TransporterService::newSession");
unknown's avatar
unknown committed
60 61
  if (m_auth && !m_auth->server_authenticate(sockfd)){
    NDB_CLOSE_SOCKET(sockfd);
unknown's avatar
unknown committed
62
    DBUG_RETURN(0);
unknown's avatar
unknown committed
63 64
  }

65
  if (!m_transporter_registry->connect_server(sockfd))
unknown's avatar
unknown committed
66
  {
67 68
    NDB_CLOSE_SOCKET(sockfd);
    DBUG_RETURN(0);
unknown's avatar
unknown committed
69 70
  }

unknown's avatar
unknown committed
71
  DBUG_RETURN(0);
unknown's avatar
unknown committed
72
}
73

74
TransporterRegistry::TransporterRegistry(void * callback,
75 76 77 78 79 80
					 unsigned _maxTransporters,
					 unsigned sizeOfLongSignalMemory) {

  nodeIdSpecified = false;
  maxTransporters = _maxTransporters;
  sendCounter = 1;
81
  m_mgm_handle= 0;
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
  
  callbackObj=callback;

  theTCPTransporters  = new TCP_Transporter * [maxTransporters];
  theSCITransporters  = new SCI_Transporter * [maxTransporters];
  theSHMTransporters  = new SHM_Transporter * [maxTransporters];
  theOSETransporters  = new OSE_Transporter * [maxTransporters];
  theTransporterTypes = new TransporterType   [maxTransporters];
  theTransporters     = new Transporter     * [maxTransporters];
  performStates       = new PerformState      [maxTransporters];
  ioStates            = new IOState           [maxTransporters]; 
  
  // Initialize member variables
  nTransporters    = 0;
  nTCPTransporters = 0;
  nSCITransporters = 0;
  nSHMTransporters = 0;
  nOSETransporters = 0;
  
  // Initialize the transporter arrays
  for (unsigned i=0; i<maxTransporters; i++) {
    theTCPTransporters[i] = NULL;
    theSCITransporters[i] = NULL;
    theSHMTransporters[i] = NULL;
    theOSETransporters[i] = NULL;
    theTransporters[i]    = NULL;
unknown's avatar
unknown committed
108
    performStates[i]      = DISCONNECTED;
109 110 111 112 113 114 115
    ioStates[i]           = NoHalt;
  }
  theOSEReceiver = 0;
  theOSEJunkSocketSend = 0;
  theOSEJunkSocketRecv = 0;
}

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
void TransporterRegistry::set_mgm_handle(NdbMgmHandle h)
{
  DBUG_ENTER("TransporterRegistry::set_mgm_handle");
  if (m_mgm_handle)
    ndb_mgm_destroy_handle(&m_mgm_handle);
  m_mgm_handle= h;
#ifndef DBUG_OFF
  if (h)
  {
    char buf[256];
    DBUG_PRINT("info",("handle set with connectstring: %s",
		       ndb_mgm_get_connectstring(h,buf, sizeof(buf))));
  }
  else
  {
    DBUG_PRINT("info",("handle set to NULL"));
  }
#endif
  DBUG_VOID_RETURN;
135
}
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
TransporterRegistry::~TransporterRegistry() {
  
  removeAll();
  
  delete[] theTCPTransporters;
  delete[] theSCITransporters;
  delete[] theSHMTransporters;
  delete[] theOSETransporters;
  delete[] theTransporterTypes;
  delete[] theTransporters;
  delete[] performStates;
  delete[] ioStates;

#ifdef NDB_OSE_TRANSPORTER
  if(theOSEReceiver != NULL){
    theOSEReceiver->destroyPhantom();
    delete theOSEReceiver;
    theOSEReceiver = 0;
  }
#endif
157 158
  if (m_mgm_handle)
    ndb_mgm_destroy_handle(&m_mgm_handle);
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
}

void
TransporterRegistry::removeAll(){
  for(unsigned i = 0; i<maxTransporters; i++){
    if(theTransporters[i] != NULL)
      removeTransporter(theTransporters[i]->getRemoteNodeId());
  }
}

void
TransporterRegistry::disconnectAll(){
  for(unsigned i = 0; i<maxTransporters; i++){
    if(theTransporters[i] != NULL)
      theTransporters[i]->doDisconnect();
  }
}

bool
TransporterRegistry::init(NodeId nodeId) {
179
  DBUG_ENTER("TransporterRegistry::init");
180 181 182 183 184
  nodeIdSpecified = true;
  localNodeId = nodeId;
  
  DEBUG("TransporterRegistry started node: " << localNodeId);
  
185
  DBUG_RETURN(true);
186 187
}

188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
bool
TransporterRegistry::connect_server(NDB_SOCKET_TYPE sockfd)
{
  DBUG_ENTER("TransporterRegistry::connect_server");

  // read node id from client
  // read transporter type
  int nodeId, remote_transporter_type= -1;
  SocketInputStream s_input(sockfd);
  char buf[256];
  if (s_input.gets(buf, 256) == 0) {
    DBUG_PRINT("error", ("Could not get node id from client"));
    DBUG_RETURN(false);
  }
  int r= sscanf(buf, "%d %d", &nodeId, &remote_transporter_type);
  switch (r) {
  case 2:
    break;
  case 1:
    // we're running version prior to 4.1.9
    // ok, but with no checks on transporter configuration compatability
    break;
  default:
    DBUG_PRINT("error", ("Error in node id from client"));
    DBUG_RETURN(false);
  }

  DBUG_PRINT("info", ("nodeId=%d remote_transporter_type=%d",
		      nodeId,remote_transporter_type));

  //check that nodeid is valid and that there is an allocated transporter
  if ( nodeId < 0 || nodeId >= (int)maxTransporters) {
    DBUG_PRINT("error", ("Node id out of range from client"));
    DBUG_RETURN(false);
  }
  if (theTransporters[nodeId] == 0) {
      DBUG_PRINT("error", ("No transporter for this node id from client"));
      DBUG_RETURN(false);
  }

  //check that the transporter should be connected
  if (performStates[nodeId] != TransporterRegistry::CONNECTING) {
    DBUG_PRINT("error", ("Transporter in wrong state for this node id from client"));
    DBUG_RETURN(false);
  }

  Transporter *t= theTransporters[nodeId];

  // send info about own id (just as response to acknowledge connection)
  // send info on own transporter type
  SocketOutputStream s_output(sockfd);
  s_output.println("%d %d", t->getLocalNodeId(), t->m_type);

  if (remote_transporter_type != -1)
  {
    if (remote_transporter_type != t->m_type)
    {
      DBUG_PRINT("error", ("Transporter types mismatch this=%d remote=%d",
			   t->m_type, remote_transporter_type));
      g_eventLogger.error("Incompatible configuration: Transporter type "
			  "mismatch with node %d", nodeId);

      // wait for socket close for 1 second to let message arrive at client
      {
	fd_set a_set;
	FD_ZERO(&a_set);
	FD_SET(sockfd, &a_set);
	struct timeval timeout;
	timeout.tv_sec  = 1; timeout.tv_usec = 0;
	select(sockfd+1, &a_set, 0, 0, &timeout);
      }
      DBUG_RETURN(false);
    }
  }
  else if (t->m_type == tt_SHM_TRANSPORTER)
  {
    g_eventLogger.warning("Unable to verify transporter compatability with node %d", nodeId);
  }

  // setup transporter (transporter responsible for closing sockfd)
  t->connect_server(sockfd);

  DBUG_RETURN(true);
}

273
bool
274
TransporterRegistry::createTCPTransporter(TransporterConfiguration *config) {
275 276 277 278 279 280 281 282 283 284 285
#ifdef NDB_TCP_TRANSPORTER

  if(!nodeIdSpecified){
    init(config->localNodeId);
  }
  
  if(config->localNodeId != localNodeId) 
    return false;
  
  if(theTransporters[config->remoteNodeId] != NULL)
    return false;
unknown's avatar
unknown committed
286
   
unknown's avatar
unknown committed
287
  TCP_Transporter * t = new TCP_Transporter(*this,
288 289
					    config->tcp.sendBufferSize,
					    config->tcp.maxReceiveSize,
290
					    config->localHostName,
unknown's avatar
unknown committed
291 292
					    config->remoteHostName,
					    config->port,
293
					    config->isMgmConnection,
294
					    localNodeId,
unknown's avatar
unknown committed
295
					    config->remoteNodeId,
296
					    config->serverNodeId,
297 298 299 300 301 302 303 304 305 306 307 308 309
					    config->checksum,
					    config->signalId);
  if (t == NULL) 
    return false;
  else if (!t->initTransporter()) {
    delete t;
    return false;
  }

  // Put the transporter in the transporter arrays
  theTCPTransporters[nTCPTransporters]      = t;
  theTransporters[t->getRemoteNodeId()]     = t;
  theTransporterTypes[t->getRemoteNodeId()] = tt_TCP_TRANSPORTER;
unknown's avatar
unknown committed
310
  performStates[t->getRemoteNodeId()]       = DISCONNECTED;
311 312 313 314 315 316 317 318 319 320 321 322 323 324
  nTransporters++;
  nTCPTransporters++;

#if defined NDB_OSE || defined NDB_SOFTOSE
  t->theReceiverPid = theReceiverPid;
#endif
  
  return true;
#else
  return false;
#endif
}

bool
325
TransporterRegistry::createOSETransporter(TransporterConfiguration *conf) {
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
#ifdef NDB_OSE_TRANSPORTER

  if(!nodeIdSpecified){
    init(conf->localNodeId);
  }
  
  if(conf->localNodeId != localNodeId)
    return false;
  
  if(theTransporters[conf->remoteNodeId] != NULL)
    return false;

  if(theOSEReceiver == NULL){
    theOSEReceiver = new OSE_Receiver(this,
				      10,
				      localNodeId);
  }
  
344 345
  OSE_Transporter * t = new OSE_Transporter(conf->ose.prioASignalSize,
					    conf->ose.prioBSignalSize,
346 347 348
					    localNodeId,
					    conf->localHostName,
					    conf->remoteNodeId,
349
					    conf->serverNodeId,
350 351 352 353 354 355 356 357 358 359 360 361 362
					    conf->remoteHostName,
					    conf->checksum,
					    conf->signalId);
  if (t == NULL)
    return false;
  else if (!t->initTransporter()) {
    delete t;
    return false;
  }
  // Put the transporter in the transporter arrays
  theOSETransporters[nOSETransporters]      = t;
  theTransporters[t->getRemoteNodeId()]     = t;
  theTransporterTypes[t->getRemoteNodeId()] = tt_OSE_TRANSPORTER;
unknown's avatar
unknown committed
363
  performStates[t->getRemoteNodeId()]       = DISCONNECTED;
364 365 366 367 368 369 370 371 372 373 374
  
  nTransporters++;
  nOSETransporters++;

  return true;
#else
  return false;
#endif
}

bool
375
TransporterRegistry::createSCITransporter(TransporterConfiguration *config) {
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
#ifdef NDB_SCI_TRANSPORTER

  if(!SCI_Transporter::initSCI())
    abort();
  
  if(!nodeIdSpecified){
    init(config->localNodeId);
  }
  
  if(config->localNodeId != localNodeId)
    return false;
 
  if(theTransporters[config->remoteNodeId] != NULL)
    return false;
 
unknown's avatar
unknown committed
391 392 393 394
  SCI_Transporter * t = new SCI_Transporter(*this,
                                            config->localHostName,
                                            config->remoteHostName,
                                            config->port,
395 396 397 398 399 400
					    config->isMgmConnection,
                                            config->sci.sendLimit, 
					    config->sci.bufferSize,
					    config->sci.nLocalAdapters,
					    config->sci.remoteSciNodeId0,
					    config->sci.remoteSciNodeId1,
401 402
					    localNodeId,
					    config->remoteNodeId,
403
					    config->serverNodeId,
404 405 406 407 408 409 410 411 412 413 414 415 416
					    config->checksum,
					    config->signalId);
  
  if (t == NULL) 
    return false;
  else if (!t->initTransporter()) {
    delete t;
    return false;
  }
  // Put the transporter in the transporter arrays
  theSCITransporters[nSCITransporters]      = t;
  theTransporters[t->getRemoteNodeId()]     = t;
  theTransporterTypes[t->getRemoteNodeId()] = tt_SCI_TRANSPORTER;
unknown's avatar
unknown committed
417
  performStates[t->getRemoteNodeId()]       = DISCONNECTED;
418 419 420 421 422 423 424 425 426 427
  nTransporters++;
  nSCITransporters++;
  
  return true;
#else
  return false;
#endif
}

bool
428
TransporterRegistry::createSHMTransporter(TransporterConfiguration *config) {
429
  DBUG_ENTER("TransporterRegistry::createTransporter SHM");
430 431 432 433 434 435 436 437
#ifdef NDB_SHM_TRANSPORTER
  if(!nodeIdSpecified){
    init(config->localNodeId);
  }
  
  if(config->localNodeId != localNodeId)
    return false;
  
438
  if (!g_ndb_shm_signum) {
439
    g_ndb_shm_signum= config->shm.signum;
440 441 442 443 444 445 446 447 448 449 450
    DBUG_PRINT("info",("Block signum %d",g_ndb_shm_signum));
    /**
     * Make sure to block g_ndb_shm_signum
     *   TransporterRegistry::init is run from "main" thread
     */
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, g_ndb_shm_signum);
    pthread_sigmask(SIG_BLOCK, &mask, 0);
  }

451
  if(config->shm.signum != g_ndb_shm_signum)
452 453
    return false;
  
454 455 456
  if(theTransporters[config->remoteNodeId] != NULL)
    return false;

unknown's avatar
unknown committed
457
  SHM_Transporter * t = new SHM_Transporter(*this,
458 459
					    config->localHostName,
					    config->remoteHostName,
unknown's avatar
unknown committed
460
					    config->port,
461
					    config->isMgmConnection,
unknown's avatar
unknown committed
462
					    localNodeId,
463
					    config->remoteNodeId,
464
					    config->serverNodeId,
465
					    config->checksum,
unknown's avatar
unknown committed
466
					    config->signalId,
467 468
					    config->shm.shmKey,
					    config->shm.shmSize
469 470 471 472 473 474 475 476 477 478 479
					    );
  if (t == NULL)
    return false;
  else if (!t->initTransporter()) {
    delete t;
    return false;
  }
  // Put the transporter in the transporter arrays
  theSHMTransporters[nSHMTransporters]      = t;
  theTransporters[t->getRemoteNodeId()]     = t;
  theTransporterTypes[t->getRemoteNodeId()] = tt_SHM_TRANSPORTER;
unknown's avatar
unknown committed
480
  performStates[t->getRemoteNodeId()]       = DISCONNECTED;
481 482 483 484
  
  nTransporters++;
  nSHMTransporters++;

485
  DBUG_RETURN(true);
486
#else
487
  DBUG_RETURN(false);
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
#endif
}


void
TransporterRegistry::removeTransporter(NodeId nodeId) {

  DEBUG("Removing transporter from " << localNodeId
	<< " to " << nodeId);
  
  if(theTransporters[nodeId] == NULL)
    return;
  
  theTransporters[nodeId]->doDisconnect();
  
  const TransporterType type = theTransporterTypes[nodeId];

  int ind = 0;
  switch(type){
  case tt_TCP_TRANSPORTER:
#ifdef NDB_TCP_TRANSPORTER
    for(; ind < nTCPTransporters; ind++)
      if(theTCPTransporters[ind]->getRemoteNodeId() == nodeId)
	break;
    ind++;
    for(; ind<nTCPTransporters; ind++)
      theTCPTransporters[ind-1] = theTCPTransporters[ind];
    nTCPTransporters --;
#endif
    break;
  case tt_SCI_TRANSPORTER:
#ifdef NDB_SCI_TRANSPORTER
    for(; ind < nSCITransporters; ind++)
      if(theSCITransporters[ind]->getRemoteNodeId() == nodeId)
	break;
    ind++;
    for(; ind<nSCITransporters; ind++)
      theSCITransporters[ind-1] = theSCITransporters[ind];
    nSCITransporters --;
#endif
    break;
  case tt_SHM_TRANSPORTER:
#ifdef NDB_SHM_TRANSPORTER
    for(; ind < nSHMTransporters; ind++)
      if(theSHMTransporters[ind]->getRemoteNodeId() == nodeId)
	break;
    ind++;
    for(; ind<nSHMTransporters; ind++)
      theSHMTransporters[ind-1] = theSHMTransporters[ind];
    nSHMTransporters --;
#endif
    break;
  case tt_OSE_TRANSPORTER:
#ifdef NDB_OSE_TRANSPORTER
    for(; ind < nOSETransporters; ind++)
      if(theOSETransporters[ind]->getRemoteNodeId() == nodeId)
	break;
    ind++;
    for(; ind<nOSETransporters; ind++)
      theOSETransporters[ind-1] = theOSETransporters[ind];
    nOSETransporters --;
#endif
    break;
  }
  
  nTransporters--;

  // Delete the transporter and remove it from theTransporters array
  delete theTransporters[nodeId];
  theTransporters[nodeId] = NULL;        
}

SendStatus
TransporterRegistry::prepareSend(const SignalHeader * const signalHeader, 
				 Uint8 prio,
				 const Uint32 * const signalData,
				 NodeId nodeId, 
				 const LinearSectionPtr ptr[3]){


  Transporter *t = theTransporters[nodeId];
  if(t != NULL && 
     (((ioStates[nodeId] != HaltOutput) && (ioStates[nodeId] != HaltIO)) || 
571 572 573
      ((signalHeader->theReceiversBlockNumber == 252) ||
       (signalHeader->theReceiversBlockNumber == 4002)))) {
	 
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    if(t->isConnected()){
      Uint32 lenBytes = t->m_packer.getMessageLength(signalHeader, ptr);
      if(lenBytes <= MAX_MESSAGE_SIZE){
	Uint32 * insertPtr = t->getWritePtr(lenBytes, prio);
	if(insertPtr != 0){
	  t->m_packer.pack(insertPtr, prio, signalHeader, signalData, ptr);
	  t->updateWritePtr(lenBytes, prio);
	  return SEND_OK;
	}

	int sleepTime = 2;	

	/**
	 * @note: on linux/i386 the granularity is 10ms
	 *        so sleepTime = 2 generates a 10 ms sleep.
	 */
	for(int i = 0; i<50; i++){
	  if((nSHMTransporters+nSCITransporters) == 0)
	    NdbSleep_MilliSleep(sleepTime); 
	  insertPtr = t->getWritePtr(lenBytes, prio);
	  if(insertPtr != 0){
	    t->m_packer.pack(insertPtr, prio, signalHeader, signalData, ptr);
	    t->updateWritePtr(lenBytes, prio);
	    break;
	  }
	}
	
	if(insertPtr != 0){
	  /**
	   * Send buffer full, but resend works
	   */
	  reportError(callbackObj, nodeId, TE_SEND_BUFFER_FULL);
	  return SEND_OK;
	}
	
	WARNING("Signal to " << nodeId << " lost(buffer)");
	reportError(callbackObj, nodeId, TE_SIGNAL_LOST_SEND_BUFFER_FULL);
	return SEND_BUFFER_FULL;
      } else {
	return SEND_MESSAGE_TOO_BIG;
      }
    } else {
      DEBUG("Signal to " << nodeId << " lost(disconnect) ");
      return SEND_DISCONNECTED;
    }
  } else {
    DEBUG("Discarding message to block: " 
	  << signalHeader->theReceiversBlockNumber 
	  << " node: " << nodeId);
    
    if(t == NULL)
      return SEND_UNKNOWN_NODE;
    
    return SEND_BLOCKED;
  }
}

SendStatus
TransporterRegistry::prepareSend(const SignalHeader * const signalHeader, 
				 Uint8 prio,
				 const Uint32 * const signalData,
				 NodeId nodeId, 
				 class SectionSegmentPool & thePool,
				 const SegmentedSectionPtr ptr[3]){
  

  Transporter *t = theTransporters[nodeId];
  if(t != NULL && 
     (((ioStates[nodeId] != HaltOutput) && (ioStates[nodeId] != HaltIO)) || 
643 644 645
      ((signalHeader->theReceiversBlockNumber == 252)|| 
       (signalHeader->theReceiversBlockNumber == 4002)))) {
    
646 647 648 649 650 651 652 653 654 655
    if(t->isConnected()){
      Uint32 lenBytes = t->m_packer.getMessageLength(signalHeader, ptr);
      if(lenBytes <= MAX_MESSAGE_SIZE){
	Uint32 * insertPtr = t->getWritePtr(lenBytes, prio);
	if(insertPtr != 0){
	  t->m_packer.pack(insertPtr, prio, signalHeader, signalData, thePool, ptr);
	  t->updateWritePtr(lenBytes, prio);
	  return SEND_OK;
	}
	
656
	
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
	/**
	 * @note: on linux/i386 the granularity is 10ms
	 *        so sleepTime = 2 generates a 10 ms sleep.
	 */
	int sleepTime = 2;
	for(int i = 0; i<50; i++){
	  if((nSHMTransporters+nSCITransporters) == 0)
	    NdbSleep_MilliSleep(sleepTime); 
	  insertPtr = t->getWritePtr(lenBytes, prio);
	  if(insertPtr != 0){
	    t->m_packer.pack(insertPtr, prio, signalHeader, signalData, thePool, ptr);
	    t->updateWritePtr(lenBytes, prio);
	    break;
	  }
	}
	
	if(insertPtr != 0){
	  /**
	   * Send buffer full, but resend works
	   */
	  reportError(callbackObj, nodeId, TE_SEND_BUFFER_FULL);
	  return SEND_OK;
	}
	
	WARNING("Signal to " << nodeId << " lost(buffer)");
	reportError(callbackObj, nodeId, TE_SIGNAL_LOST_SEND_BUFFER_FULL);
	return SEND_BUFFER_FULL;
      } else {
	return SEND_MESSAGE_TOO_BIG;
      }
    } else {
      DEBUG("Signal to " << nodeId << " lost(disconnect) ");
      return SEND_DISCONNECTED;
    }
  } else {
    DEBUG("Discarding message to block: " 
	  << signalHeader->theReceiversBlockNumber 
	  << " node: " << nodeId);
    
    if(t == NULL)
      return SEND_UNKNOWN_NODE;
    
    return SEND_BLOCKED;
  }
}

void
TransporterRegistry::external_IO(Uint32 timeOutMillis) {
  //-----------------------------------------------------------
  // Most of the time we will send the buffers here and then wait
  // for new signals. Thus we start by sending without timeout
  // followed by the receive part where we expect to sleep for
  // a while.
  //-----------------------------------------------------------
  if(pollReceive(timeOutMillis)){
    performReceive();
  }
  performSend();
}

Uint32
TransporterRegistry::pollReceive(Uint32 timeOutMillis){
  Uint32 retVal = 0;
#ifdef NDB_OSE_TRANSPORTER
  retVal |= poll_OSE(timeOutMillis);
  retVal |= poll_TCP(0);
  return retVal;
#endif
  
726 727
  if((nSCITransporters) > 0)
  {
728
    timeOutMillis=0;
729 730 731 732 733 734 735 736 737 738 739 740 741 742
  }

#ifdef NDB_SHM_TRANSPORTER
  if(nSHMTransporters > 0)
  {
    Uint32 res = poll_SHM(0);
    if(res)
    {
      retVal |= res;
      timeOutMillis = 0;
    }
  }
#endif

743
#ifdef NDB_TCP_TRANSPORTER
744 745
  if(nTCPTransporters > 0 || retVal == 0)
  {
746
    retVal |= poll_TCP(timeOutMillis);
747
  }
748 749 750 751 752 753 754 755
  else
    tcpReadSelectReply = 0;
#endif
#ifdef NDB_SCI_TRANSPORTER
  if(nSCITransporters > 0)
    retVal |= poll_SCI(timeOutMillis);
#endif
#ifdef NDB_SHM_TRANSPORTER
756 757 758 759 760
  if(nSHMTransporters > 0 && retVal == 0)
  {
    int res = poll_SHM(0);
    retVal |= res;
  }
761 762 763 764 765 766 767
#endif
  return retVal;
}


#ifdef NDB_SCI_TRANSPORTER
Uint32
768 769
TransporterRegistry::poll_SCI(Uint32 timeOutMillis)
{
770 771 772 773 774 775 776 777 778 779 780 781 782
  for (int i=0; i<nSCITransporters; i++) {
    SCI_Transporter * t = theSCITransporters[i];
    if (t->isConnected()) {
      if(t->hasDataToRead())
	return 1;
    }
  }
  return 0;
}
#endif


#ifdef NDB_SHM_TRANSPORTER
783
static int g_shm_counter = 0;
784 785 786
Uint32
TransporterRegistry::poll_SHM(Uint32 timeOutMillis)
{  
787 788
  for(int j=0; j < 100; j++)
  {
789 790 791
    for (int i=0; i<nSHMTransporters; i++) {
      SHM_Transporter * t = theSHMTransporters[i];
      if (t->isConnected()) {
792
	if(t->hasDataToRead()) {
793 794 795 796 797 798 799 800 801 802 803
	  return 1;
	}
      }
    }
  }
  return 0;
}
#endif

#ifdef NDB_OSE_TRANSPORTER
Uint32
804 805
TransporterRegistry::poll_OSE(Uint32 timeOutMillis)
{
806 807 808 809 810 811 812 813 814 815
  if(theOSEReceiver != NULL){
    return theOSEReceiver->doReceive(timeOutMillis);
  }
  NdbSleep_MilliSleep(timeOutMillis);
  return 0;
}
#endif

#ifdef NDB_TCP_TRANSPORTER
Uint32 
816 817 818 819
TransporterRegistry::poll_TCP(Uint32 timeOutMillis)
{
  if (false && nTCPTransporters == 0)
  {
820 821 822 823 824 825 826
    tcpReadSelectReply = 0;
    return 0;
  }
  
  struct timeval timeout;
#ifdef NDB_OSE
  // Return directly if there are no TCP transporters configured
827
  
828 829 830 831 832 833 834 835 836 837 838 839
  if(timeOutMillis <= 1){
    timeout.tv_sec  = 0;
    timeout.tv_usec = 1025;
  } else {
    timeout.tv_sec  = timeOutMillis / 1000;
    timeout.tv_usec = (timeOutMillis % 1000) * 1000;
  }
#else  
  timeout.tv_sec  = timeOutMillis / 1000;
  timeout.tv_usec = (timeOutMillis % 1000) * 1000;
#endif

840
  NDB_SOCKET_TYPE maxSocketValue = -1;
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  
  // Needed for TCP/IP connections
  // The read- and writeset are used by select
  
  FD_ZERO(&tcpReadset);

  // Prepare for sending and receiving
  for (int i = 0; i < nTCPTransporters; i++) {
    TCP_Transporter * t = theTCPTransporters[i];
    
    // If the transporter is connected
    if (t->isConnected()) {
      
      const NDB_SOCKET_TYPE socket = t->getSocket();
      // Find the highest socket value. It will be used by select
      if (socket > maxSocketValue)
	maxSocketValue = socket;
      
      // Put the connected transporters in the socket read-set 
      FD_SET(socket, &tcpReadset);
    }
  }
  
  // The highest socket value plus one
  maxSocketValue++; 
  
  tcpReadSelectReply = select(maxSocketValue, &tcpReadset, 0, 0, &timeout);  
868 869 870
  if(false && tcpReadSelectReply == -1 && errno == EINTR)
    ndbout_c("woke-up by signal");

871 872 873 874 875 876
#ifdef NDB_WIN32
  if(tcpReadSelectReply == SOCKET_ERROR)
  {
    NdbSleep_MilliSleep(timeOutMillis);
  }
#endif
877
  
878 879 880 881 882 883
  return tcpReadSelectReply;
}
#endif


void
884 885
TransporterRegistry::performReceive()
{
886
#ifdef NDB_OSE_TRANSPORTER
887 888 889 890
  if(theOSEReceiver != 0)
  {
    while(theOSEReceiver->hasData())
    {
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
      NodeId remoteNodeId;
      Uint32 * readPtr;
      Uint32 sz = theOSEReceiver->getReceiveData(&remoteNodeId, &readPtr);
      Uint32 szUsed = unpack(readPtr,
			     sz,
			     remoteNodeId,
			     ioStates[remoteNodeId]);
#ifdef DEBUG_TRANSPORTER
      /**
       * OSE transporter can handle executions of
       *   half signals
       */
      assert(sz == szUsed);
#endif
      theOSEReceiver->updateReceiveDataPtr(szUsed);
      theOSEReceiver->doReceive(0);
      //      checkJobBuffer();
    }
  }
#endif

#ifdef NDB_TCP_TRANSPORTER
913 914 915 916
  if(tcpReadSelectReply > 0)
  {
    for (int i=0; i<nTCPTransporters; i++) 
    {
917 918 919 920
      checkJobBuffer();
      TCP_Transporter *t = theTCPTransporters[i];
      const NodeId nodeId = t->getRemoteNodeId();
      const NDB_SOCKET_TYPE socket    = t->getSocket();
unknown's avatar
unknown committed
921
      if(is_connected(nodeId)){
922 923
	if(t->isConnected() && FD_ISSET(socket, &tcpReadset)) 
	{
924
	  const int receiveSize = t->doReceive();
925 926
	  if(receiveSize > 0)
	  {
927 928 929 930 931 932 933 934 935 936
	    Uint32 * ptr;
	    Uint32 sz = t->getReceiveData(&ptr);
	    Uint32 szUsed = unpack(ptr, sz, nodeId, ioStates[nodeId]);
	    t->updateReceiveDataPtr(szUsed);
          }
	}
      } 
    }
  }
#endif
937
  
938 939 940
#ifdef NDB_SCI_TRANSPORTER
  //performReceive
  //do prepareReceive on the SCI transporters  (prepareReceive(t,,,,))
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
  for (int i=0; i<nSCITransporters; i++) 
  {
    checkJobBuffer();
    SCI_Transporter  *t = theSCITransporters[i];
    const NodeId nodeId = t->getRemoteNodeId();
    if(is_connected(nodeId))
    {
      if(t->isConnected() && t->checkConnected())
      {
	Uint32 * readPtr, * eodPtr;
	t->getReceivePtr(&readPtr, &eodPtr);
	Uint32 *newPtr = unpack(readPtr, eodPtr, nodeId, ioStates[nodeId]);
	t->updateReceivePtr(newPtr);
      }
    } 
  }
957 958
#endif
#ifdef NDB_SHM_TRANSPORTER
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
  for (int i=0; i<nSHMTransporters; i++) 
  {
    checkJobBuffer();
    SHM_Transporter *t = theSHMTransporters[i];
    const NodeId nodeId = t->getRemoteNodeId();
    if(is_connected(nodeId)){
      if(t->isConnected() && t->checkConnected())
      {
	Uint32 * readPtr, * eodPtr;
	t->getReceivePtr(&readPtr, &eodPtr);
	Uint32 *newPtr = unpack(readPtr, eodPtr, nodeId, ioStates[nodeId]);
	t->updateReceivePtr(newPtr);
      }
    } 
  }
974 975 976 977 978
#endif
}

static int x = 0;
void
979 980 981 982 983
TransporterRegistry::performSend()
{
  int i; 
  sendCounter = 1;
  
984
#ifdef NDB_OSE_TRANSPORTER
985 986 987 988 989 990 991 992
  for (int i = 0; i < nOSETransporters; i++)
  {
    OSE_Transporter *t = theOSETransporters[i]; 
    if(is_connected(t->getRemoteNodeId()) &&& (t->isConnected()))
    {
      t->doSend();
    }//if
  }//for
993
#endif
994
  
995 996
#ifdef NDB_TCP_TRANSPORTER
#ifdef NDB_OSE
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
  {
    int maxSocketValue = 0;
    
    // Needed for TCP/IP connections
    // The writeset are used by select
    fd_set writeset;
    FD_ZERO(&writeset);
    
    // Prepare for sending and receiving
    for (i = 0; i < nTCPTransporters; i++) {
      TCP_Transporter * t = theTCPTransporters[i];
      
      // If the transporter is connected
      if ((t->hasDataToSend()) && (t->isConnected())) {
	const int socket = t->getSocket();
	// Find the highest socket value. It will be used by select
	if (socket > maxSocketValue) {
	  maxSocketValue = socket;
	}//if
	FD_SET(socket, &writeset);
      }//if
    }//for
    
    // The highest socket value plus one
    if(maxSocketValue == 0)
      return;
    
    maxSocketValue++; 
    struct timeval timeout = { 0, 1025 };
    Uint32 tmp = select(maxSocketValue, 0, &writeset, 0, &timeout);
    
    if (tmp == 0) 
1029
    {
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
      return;
    }//if
    for (i = 0; i < nTCPTransporters; i++) {
      TCP_Transporter *t = theTCPTransporters[i];
      const NodeId nodeId = t->getRemoteNodeId();
      const int socket    = t->getSocket();
      if(is_connected(nodeId)){
	  if(t->isConnected() && FD_ISSET(socket, &writeset)) {
	    t->doSend();
	  }//if
	}//if
      }//for
1042 1043 1044
    }
#endif
#ifdef NDB_TCP_TRANSPORTER
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
  for (i = x; i < nTCPTransporters; i++) 
  {
    TCP_Transporter *t = theTCPTransporters[i];
    if (t && t->hasDataToSend() && t->isConnected() &&
	is_connected(t->getRemoteNodeId())) 
    {
      t->doSend();
    }
  }
  for (i = 0; i < x && i < nTCPTransporters; i++) 
  {
    TCP_Transporter *t = theTCPTransporters[i];
    if (t && t->hasDataToSend() && t->isConnected() &&
	is_connected(t->getRemoteNodeId())) 
    {
      t->doSend();
    }
  }
  x++;
  if (x == nTCPTransporters) x = 0;
1065 1066 1067
#endif
#endif
#ifdef NDB_SCI_TRANSPORTER
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
  //scroll through the SCI transporters, 
  // get each transporter, check if connected, send data
  for (i=0; i<nSCITransporters; i++) {
    SCI_Transporter  *t = theSCITransporters[i];
    const NodeId nodeId = t->getRemoteNodeId();
    
    if(is_connected(nodeId))
    {
      if(t->isConnected() && t->hasDataToSend()) {
	t->doSend();
1078
      } //if
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    } //if
  }
#endif
  
#ifdef NDB_SHM_TRANSPORTER
  for (i=0; i<nSHMTransporters; i++) 
  {
    SHM_Transporter  *t = theSHMTransporters[i];
    const NodeId nodeId = t->getRemoteNodeId();
    if(is_connected(nodeId))
    {
      if(t->isConnected())
      {
	t->doSend();
      }
    }
  }
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
#endif
}

int
TransporterRegistry::forceSendCheck(int sendLimit){
  int tSendCounter = sendCounter;
  sendCounter = tSendCounter + 1;
  if (tSendCounter >= sendLimit) {
    performSend();
    sendCounter = 1;
    return 1;
  }//if
  return 0;
}//TransporterRegistry::forceSendCheck()

#ifdef DEBUG_TRANSPORTER
void
TransporterRegistry::printState(){
  ndbout << "-- TransporterRegistry -- " << endl << endl
	 << "Transporters = " << nTransporters << endl;
  for(int i = 0; i<maxTransporters; i++)
    if(theTransporters[i] != NULL){
      const NodeId remoteNodeId = theTransporters[i]->getRemoteNodeId();
      ndbout << "Transporter: " << remoteNodeId 
	     << " PerformState: " << performStates[remoteNodeId]
	     << " IOState: " << ioStates[remoteNodeId] << endl;
    }
}
#endif

unknown's avatar
unknown committed
1126 1127 1128
IOState
TransporterRegistry::ioState(NodeId nodeId) { 
  return ioStates[nodeId]; 
1129 1130
}

unknown's avatar
unknown committed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
void
TransporterRegistry::setIOState(NodeId nodeId, IOState state) {
  DEBUG("TransporterRegistry::setIOState("
	<< nodeId << ", " << state << ")");
  ioStates[nodeId] = state;
}

static void * 
run_start_clients_C(void * me)
{
  ((TransporterRegistry*) me)->start_clients_thread();
1142
  return 0;
unknown's avatar
unknown committed
1143 1144 1145 1146 1147 1148 1149 1150 1151
}

// Run by kernel thread
void
TransporterRegistry::do_connect(NodeId node_id)
{
  PerformState &curr_state = performStates[node_id];
  switch(curr_state){
  case DISCONNECTED:
1152
    break;
unknown's avatar
unknown committed
1153 1154 1155 1156 1157
  case CONNECTED:
    return;
  case CONNECTING:
    return;
  case DISCONNECTING:
1158
    break;
unknown's avatar
unknown committed
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
  }
  curr_state= CONNECTING;
}
void
TransporterRegistry::do_disconnect(NodeId node_id)
{
  PerformState &curr_state = performStates[node_id];
  switch(curr_state){
  case DISCONNECTED:
    return;
  case CONNECTED:
1170
    break;
unknown's avatar
unknown committed
1171
  case CONNECTING:
1172
    break;
unknown's avatar
unknown committed
1173 1174
  case DISCONNECTING:
    return;
1175
  }
unknown's avatar
unknown committed
1176
  curr_state= DISCONNECTING;
1177 1178 1179
}

void
unknown's avatar
unknown committed
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
TransporterRegistry::report_connect(NodeId node_id)
{
  performStates[node_id] = CONNECTED;
  reportConnect(callbackObj, node_id);
}

void
TransporterRegistry::report_disconnect(NodeId node_id, int errnum)
{
  performStates[node_id] = DISCONNECTED;
  reportDisconnect(callbackObj, node_id, errnum);
1191 1192 1193
}

void
unknown's avatar
unknown committed
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
TransporterRegistry::update_connections()
{
  for (int i= 0, n= 0; n < nTransporters; i++){
    Transporter * t = theTransporters[i];
    if (!t)
      continue;
    n++;

    const NodeId nodeId = t->getRemoteNodeId();
    switch(performStates[nodeId]){
    case CONNECTED:
    case DISCONNECTED:
      break;
    case CONNECTING:
      if(t->isConnected())
	report_connect(nodeId);
      break;
    case DISCONNECTING:
      if(!t->isConnected())
	report_disconnect(nodeId, 0);
      break;
1215 1216 1217 1218
    }
  }
}

unknown's avatar
unknown committed
1219 1220 1221 1222
// run as own thread
void
TransporterRegistry::start_clients_thread()
{
unknown's avatar
unknown committed
1223
  DBUG_ENTER("TransporterRegistry::start_clients_thread");
unknown's avatar
unknown committed
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
  while (m_run_start_clients_thread) {
    NdbSleep_MilliSleep(100);
    for (int i= 0, n= 0; n < nTransporters && m_run_start_clients_thread; i++){
      Transporter * t = theTransporters[i];
      if (!t)
	continue;
      n++;

      const NodeId nodeId = t->getRemoteNodeId();
      switch(performStates[nodeId]){
      case CONNECTING:
1235
	if(!t->isConnected() && !t->isServer) {
1236
	  bool connected= false;
1237 1238 1239
	  /**
	   * First, we try to connect (if we have a port number).
	   */
1240
	  if (t->get_s_port())
1241
	    connected= t->connect_client();
1242 1243 1244 1245

	  /**
	   * If dynamic, get the port for connecting from the management server
	   */
1246
	  if( !connected && t->get_s_port() <= 0) {	// Port is dynamic
1247
	    int server_port= 0;
1248
	    struct ndb_mgm_reply mgm_reply;
1249

1250
	    if(!ndb_mgm_is_connected(m_mgm_handle))
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
	      ndb_mgm_connect(m_mgm_handle, 0, 0, 0);
	    
	    if(ndb_mgm_is_connected(m_mgm_handle))
	    {
	      int res=
		ndb_mgm_get_connection_int_parameter(m_mgm_handle,
						     t->getRemoteNodeId(),
						     t->getLocalNodeId(),
						     CFG_CONNECTION_SERVER_PORT,
						     &server_port,
						     &mgm_reply);
	      DBUG_PRINT("info",("Got dynamic port %d for %d -> %d (ret: %d)",
				 server_port,t->getRemoteNodeId(),
				 t->getLocalNodeId(),res));
	      if( res >= 0 )
	      {
		/**
		 * Server_port == 0 just means that that a mgmt server
		 * has not received a new port yet. Keep the old.
		 */
		if (server_port)
		  t->set_s_port(server_port);
	      }
1274
	      else
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
	      {
		ndbout_c("Failed to get dynamic port to connect to: %d", res);
		ndb_mgm_disconnect(m_mgm_handle);
	      }
	    }
	    /** else
	     * We will not be able to get a new port unless
	     * the m_mgm_handle is connected. Note that not
	     * being connected is an ok state, just continue
	     * until it is able to connect. Continue using the
	     * old port until we can connect again and get a
	     * new port.
	     */
1288 1289
	  }
	}
unknown's avatar
unknown committed
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
	break;
      case DISCONNECTING:
	if(t->isConnected())
	  t->doDisconnect();
	break;
      default:
	break;
      }
    }
  }
unknown's avatar
unknown committed
1300
  DBUG_VOID_RETURN;
1301 1302
}

unknown's avatar
unknown committed
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
bool
TransporterRegistry::start_clients()
{
  m_run_start_clients_thread= true;
  m_start_clients_thread= NdbThread_Create(run_start_clients_C,
					   (void**)this,
					   32768,
					   "ndb_start_clients",
					   NDB_THREAD_PRIO_LOW);
  if (m_start_clients_thread == 0) {
    m_run_start_clients_thread= false;
    return false;
  }
  return true;
}

bool
TransporterRegistry::stop_clients()
{
  if (m_start_clients_thread) {
    m_run_start_clients_thread= false;
    void* status;
1325
    NdbThread_WaitFor(m_start_clients_thread, &status);
unknown's avatar
unknown committed
1326 1327 1328 1329 1330
    NdbThread_Destroy(&m_start_clients_thread);
  }
  return true;
}

1331
void
unknown's avatar
unknown committed
1332
TransporterRegistry::add_transporter_interface(NodeId remoteNodeId,
1333
					       const char *interf, 
1334
					       int s_port)
unknown's avatar
unknown committed
1335
{
1336
  DBUG_ENTER("TransporterRegistry::add_transporter_interface");
1337
  DBUG_PRINT("enter",("interface=%s, s_port= %d", interf, s_port));
unknown's avatar
unknown committed
1338 1339
  if (interf && strlen(interf) == 0)
    interf= 0;
1340 1341 1342 1343

  for (unsigned i= 0; i < m_transporter_interface.size(); i++)
  {
    Transporter_interface &tmp= m_transporter_interface[i];
1344
    if (s_port != tmp.m_s_service_port || tmp.m_s_service_port==0)
unknown's avatar
unknown committed
1345
      continue;
unknown's avatar
unknown committed
1346 1347
    if (interf != 0 && tmp.m_interface != 0 &&
	strcmp(interf, tmp.m_interface) == 0)
1348 1349 1350
    {
      DBUG_VOID_RETURN; // found match, no need to insert
    }
unknown's avatar
unknown committed
1351
    if (interf == 0 && tmp.m_interface == 0)
1352 1353
    {
      DBUG_VOID_RETURN; // found match, no need to insert
unknown's avatar
unknown committed
1354 1355
    }
  }
1356
  Transporter_interface t;
unknown's avatar
unknown committed
1357
  t.m_remote_nodeId= remoteNodeId;
1358
  t.m_s_service_port= s_port;
unknown's avatar
unknown committed
1359
  t.m_interface= interf;
1360 1361 1362 1363
  m_transporter_interface.push_back(t);
  DBUG_PRINT("exit",("interface and port added"));
  DBUG_VOID_RETURN;
}
unknown's avatar
unknown committed
1364

1365 1366 1367
bool
TransporterRegistry::start_service(SocketServer& socket_server)
{
1368 1369
  struct ndb_mgm_reply mgm_reply;

1370
  DBUG_ENTER("TransporterRegistry::start_service");
unknown's avatar
unknown committed
1371
  if (m_transporter_interface.size() > 0 && !nodeIdSpecified)
1372 1373
  {
    ndbout_c("TransporterRegistry::startReceiving: localNodeId not specified");
1374
    DBUG_RETURN(false);
1375
  }
unknown's avatar
unknown committed
1376

1377 1378 1379
  for (unsigned i= 0; i < m_transporter_interface.size(); i++)
  {
    Transporter_interface &t= m_transporter_interface[i];
1380

1381 1382 1383
    unsigned short port= (unsigned short)t.m_s_service_port;
    if(t.m_s_service_port<0)
      port= -t.m_s_service_port; // is a dynamic port
1384 1385 1386
    TransporterService *transporter_service =
      new TransporterService(new SocketAuthSimple("ndbd", "ndbd passwd"));
    if(!socket_server.setup(transporter_service,
1387
			    &port, t.m_interface))
1388
    {
1389 1390
      DBUG_PRINT("info", ("Trying new port"));
      port= 0;
1391
      if(t.m_s_service_port>0
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
	 || !socket_server.setup(transporter_service,
				 &port, t.m_interface))
      {
	/*
	 * If it wasn't a dynamically allocated port, or
	 * our attempts at getting a new dynamic port failed
	 */
	ndbout_c("Unable to setup transporter service port: %s:%d!\n"
		 "Please check if the port is already used,\n"
		 "(perhaps the node is already running)",
1402
		 t.m_interface ? t.m_interface : "*", t.m_s_service_port);
1403
	delete transporter_service;
1404
	DBUG_RETURN(false);
1405
      }
unknown's avatar
unknown committed
1406
    }
1407 1408
    t.m_s_service_port= (t.m_s_service_port<=0)?-port:port; // -`ve if dynamic
    DBUG_PRINT("info", ("t.m_s_service_port = %d",t.m_s_service_port));
1409 1410
    transporter_service->setTransporterRegistry(this);
  }
1411
  DBUG_RETURN(true);
1412 1413
}

1414 1415 1416 1417 1418 1419 1420 1421 1422
#ifdef NDB_SHM_TRANSPORTER
static
RETSIGTYPE 
shm_sig_handler(int signo)
{
  g_shm_counter++;
}
#endif

1423
void
unknown's avatar
unknown committed
1424 1425
TransporterRegistry::startReceiving()
{
1426
  DBUG_ENTER("TransporterRegistry::startReceiving");
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
#ifdef NDB_OSE_TRANSPORTER
  if(theOSEReceiver != NULL){
    theOSEReceiver->createPhantom();
  }
#endif

#ifdef NDB_OSE
  theOSEJunkSocketRecv = socket(AF_INET, SOCK_STREAM, 0);
#endif

#if defined NDB_OSE || defined NDB_SOFTOSE
  theReceiverPid = current_process();
  for(int i = 0; i<nTCPTransporters; i++)
    theTCPTransporters[i]->theReceiverPid = theReceiverPid;
#endif
1442 1443

#ifdef NDB_SHM_TRANSPORTER
1444
  m_shm_own_pid = getpid();
1445
  if (g_ndb_shm_signum)
1446
  {
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    DBUG_PRINT("info",("Install signal handler for signum %d",
		       g_ndb_shm_signum));
    struct sigaction sa;
    sigemptyset(&sa.sa_mask);
    sigaddset(&sa.sa_mask, g_ndb_shm_signum);
    pthread_sigmask(SIG_UNBLOCK, &sa.sa_mask, 0);
    sa.sa_handler = shm_sig_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    int ret;
    while((ret = sigaction(g_ndb_shm_signum, &sa, 0)) == -1 && errno == EINTR);
    if(ret != 0)
    {
      DBUG_PRINT("error",("Install failed"));
      g_eventLogger.error("Failed to install signal handler for"
			  " SHM transporter errno: %d (%s)", errno, 
1463
			  strerror(errno));
1464
    }
1465
  }
1466 1467
#endif // NDB_SHM_TRANSPORTER
  DBUG_VOID_RETURN;
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
}

void
TransporterRegistry::stopReceiving(){
#ifdef NDB_OSE_TRANSPORTER
  if(theOSEReceiver != NULL){
    theOSEReceiver->destroyPhantom();
  }
#endif

  /**
   * Disconnect all transporters, this includes detach from remote node
   * and since that must be done from the same process that called attach
   * it's done here in the receive thread
   */
  disconnectAll();

#if defined NDB_OSE || defined NDB_SOFTOSE
  if(theOSEJunkSocketRecv > 0)
    close(theOSEJunkSocketRecv);
  theOSEJunkSocketRecv = -1;
#endif

}

void
TransporterRegistry::startSending(){
#if defined NDB_OSE || defined NDB_SOFTOSE
  theOSEJunkSocketSend = socket(AF_INET, SOCK_STREAM, 0);
#endif
}

void
TransporterRegistry::stopSending(){
#if defined NDB_OSE || defined NDB_SOFTOSE
  if(theOSEJunkSocketSend > 0)
    close(theOSEJunkSocketSend);
  theOSEJunkSocketSend = -1;
#endif
}

NdbOut & operator <<(NdbOut & out, SignalHeader & sh){
  out << "-- Signal Header --" << endl;
  out << "theLength:    " << sh.theLength << endl;
  out << "gsn:          " << sh.theVerId_signalNumber << endl;
  out << "recBlockNo:   " << sh.theReceiversBlockNumber << endl;
  out << "sendBlockRef: " << sh.theSendersBlockRef << endl;
  out << "sendersSig:   " << sh.theSendersSignalId << endl;
  out << "theSignalId:  " << sh.theSignalId << endl;
  out << "trace:        " << (int)sh.theTrace << endl;
  return out;
} 
1520

unknown's avatar
unknown committed
1521 1522 1523
Transporter*
TransporterRegistry::get_transporter(NodeId nodeId) {
  return theTransporters[nodeId];
1524
}
unknown's avatar
unknown committed
1525

1526
bool TransporterRegistry::connect_client(NdbMgmHandle *h)
1527 1528 1529
{
  DBUG_ENTER("TransporterRegistry::connect_client(NdbMgmHandle)");

1530 1531 1532 1533
  Uint32 mgm_nodeid= ndb_mgm_get_mgmd_nodeid(*h);

  if(!mgm_nodeid)
    return false;
1534 1535 1536

  Transporter * t = theTransporters[mgm_nodeid];
  if (!t)
1537
    return false;
1538 1539 1540 1541 1542 1543 1544 1545

  DBUG_RETURN(t->connect_client(connect_ndb_mgmd(h)));
}

/**
 * Given a connected NdbMgmHandle, turns it into a transporter
 * and returns the socket.
 */
1546
NDB_SOCKET_TYPE TransporterRegistry::connect_ndb_mgmd(NdbMgmHandle *h)
1547 1548 1549
{
  struct ndb_mgm_reply mgm_reply;

1550
  if ( h==NULL || *h == NULL )
1551 1552 1553 1554 1555
  {
    return NDB_INVALID_SOCKET;
  }

  for(unsigned int i=0;i < m_transporter_interface.size();i++)
1556 1557
    if (m_transporter_interface[i].m_s_service_port < 0
	&& ndb_mgm_set_connection_int_parameter(*h,
1558 1559 1560 1561 1562 1563
				   get_localNodeId(),
				   m_transporter_interface[i].m_remote_nodeId,
				   CFG_CONNECTION_SERVER_PORT,
				   m_transporter_interface[i].m_s_service_port,
				   &mgm_reply) < 0)
    {
1564
      ndb_mgm_destroy_handle(h);
1565 1566 1567 1568 1569 1570 1571 1572 1573
      return NDB_INVALID_SOCKET;
    }

  /**
   * convert_to_transporter also disposes of the handle (i.e. we don't leak
   * memory here.
   */
  NDB_SOCKET_TYPE sockfd= ndb_mgm_convert_to_transporter(h);
  if ( sockfd == NDB_INVALID_SOCKET)
1574
    ndb_mgm_destroy_handle(h);
1575 1576 1577 1578 1579 1580 1581
  return sockfd;
}

/**
 * Given a SocketClient, creates a NdbMgmHandle, turns it into a transporter
 * and returns the socket.
 */
1582 1583
NDB_SOCKET_TYPE TransporterRegistry::connect_ndb_mgmd(SocketClient *sc)
{
1584
  NdbMgmHandle h= ndb_mgm_create_handle();
1585

1586
  if ( h == NULL )
1587
  {
1588
    return NDB_INVALID_SOCKET;
1589 1590
  }

1591 1592 1593
  /**
   * Set connectstring
   */
1594
  {
1595 1596 1597
    BaseString cs;
    cs.assfmt("%s:%u",sc->get_server_name(),sc->get_port());
    ndb_mgm_set_connectstring(h, cs.c_str());
1598 1599 1600
  }

  if(ndb_mgm_connect(h, 0, 0, 0)<0)
1601 1602
  {
    ndb_mgm_destroy_handle(&h);
1603
    return NDB_INVALID_SOCKET;
1604 1605
  }

1606
  return connect_ndb_mgmd(&h);
1607 1608
}

1609
template class Vector<TransporterRegistry::Transporter_interface>;