Example #1
0
void
Conn::conn0()
{
    int fd;
    while (1) {
	if ((fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
	    fatal("%s: create client socket failed: %s", info, strerror(errno));
	}
	struct sockaddr_in servaddr;
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	servaddr.sin_addr = hostaddr.sin_addr;
#if 0	// coredump
	if (Ndb_getInAddr(&servaddr.sin_addr, hostname) != 0) {
	    fatal("%s: hostname %s lookup failed", info, hostname);
	}
#endif
	if (connect(fd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == 0)
	    break;
	if (errno != ECONNREFUSED) {
	    fatal("%s: connect failed: %s", info, strerror(errno));
	}
	close(fd);
	NdbSleep_MilliSleep(100);
    }
    sockfd[0] = fd;
    debug("%s: side 0 connected", info);
}
int 
runError4012(NDBT_Context* ctx, NDBT_Step* step){
  int result = NDBT_OK;
  //int loops = ctx->getNumLoops();
  //int stepNo = step->getStepNo();
  
  int timeout = ctx->getProperty("TransactionDeadlockTimeout", TIMEOUT);

  HugoOperations hugoOps(*ctx->getTab());
  Ndb* pNdb = GETNDB(step);

  do{
    // Commit transaction
    CHECK(hugoOps.startTransaction(pNdb) == 0);
    CHECK(hugoOps.pkUpdateRecord(pNdb, 0) == 0);
    int ret = hugoOps.execute_NoCommit(pNdb);
    if (ret == 0)
    {
      int sleep = timeout;
      ndbout << "Sleeping for " << sleep << " milliseconds" << endl;
      NdbSleep_MilliSleep(sleep);
      
      // Expect that transaction has NOT timed-out
      CHECK(hugoOps.execute_Commit(pNdb) == 0);
    }
    else
    {
      CHECK(ret == 4012);
    }
  } while(false);
  
  hugoOps.closeTransaction(pNdb);
  
  return result;
}
Example #3
0
  bool wait_confirmed_config(int timeout = 30)
  {
    if (!m_mgmd_client.is_connected())
    {
      g_err << "wait_confirmed_config: not connected!" << endl;
      return false;
    }

    int retries = 0;
    Config conf;
    while (!m_mgmd_client.get_config(conf))
    {
      retries++;

      if (retries == timeout * 10)
      {
        g_err << "wait_confirmed_config: Failed to get config within "
                << timeout << " seconds" << endl;
        return false;
      }

      g_err << "Failed to get config, sleeping" << endl;
      NdbSleep_MilliSleep(100);

    }
    g_info << "wait_confirmed_config: ok" << endl;
    return true;

  }
void
SocketServer::stopSessions(bool wait){
  int i;
  m_session_mutex.lock();
  for(i = m_sessions.size() - 1; i>=0; i--)
  {
    m_sessions[i].m_session->stopSession();
    m_sessions[i].m_session->m_stop = true; // to make sure
  }
  m_session_mutex.unlock();
  
  for(i = m_services.size() - 1; i>=0; i--)
    m_services[i].m_service->stopSessions();
  
  if(wait){
    m_session_mutex.lock();
    while(m_sessions.size() > 0){
      checkSessionsImpl();
      m_session_mutex.unlock();
      NdbSleep_MilliSleep(100);
      m_session_mutex.lock();
    }
    m_session_mutex.unlock();
  }
}
Example #5
0
void
ClusterMgr::startup()
{
  assert(theStop == -1);
  Uint32 nodeId = getOwnNodeId();
  Node & cm_node = theNodes[nodeId];
  trp_node & theNode = cm_node;
  assert(theNode.defined);

  lock();
  theFacade.doConnect(nodeId);
  flush_send_buffers();
  unlock();

  for (Uint32 i = 0; i<3000; i++)
  {
    lock();
    theFacade.theTransporterRegistry->update_connections();
    flush_send_buffers();
    unlock();
    if (theNode.is_connected())
      break;
    NdbSleep_MilliSleep(20);
  }

  assert(theNode.is_connected());
  Guard g(clusterMgrThreadMutex);
  theStop = 0;
  NdbCondition_Broadcast(waitForHBCond);
}
Example #6
0
bool
remove_dir(const char * path, bool inclusive)
{
  if (access(path, 0))
    return true;

  const int max_retries = 20;
  int attempt = 0;

  while(true)
  {
    if (NdbDir::remove_recursive(path, !inclusive))
      return true;

    attempt++;
    if (attempt > max_retries)
    {
      g_logger.error("Failed to remove directory '%s'!", path);
      return false;
    }

    g_logger.warning(" - attempt %d to remove directory '%s' failed "
                     ", retrying...", attempt, path);

    NdbSleep_MilliSleep(100);
  }

  abort(); // Never reached
  return false;
}
Example #7
0
void
ClusterMgr::startup()
{
    assert(theStop == -1);
    Uint32 nodeId = getOwnNodeId();
    Node & cm_node = theNodes[nodeId];
    trp_node & theNode = cm_node;
    assert(theNode.defined);

    lock();
    theFacade.doConnect(nodeId);
    flush_send_buffers();
    unlock();

    for (Uint32 i = 0; i<3000; i++)
    {
        theFacade.request_connection_check();
        start_poll();
        do_poll(0);
        complete_poll();

        if (theNode.is_connected())
            break;
        NdbSleep_MilliSleep(20);
    }

    assert(theNode.is_connected());
    Guard g(clusterMgrThreadMutex);
    /* Signalling to creating thread that we are done with thread startup */
    theStop = 0;
    NdbCondition_Broadcast(waitForHBCond);
}
bool
SocketServer::stopSessions(bool wait, unsigned wait_timeout){
  int i;
  m_session_mutex.lock();
  for(i = m_sessions.size() - 1; i>=0; i--)
  {
    m_sessions[i].m_session->stopSession();
  }
  m_session_mutex.unlock();
  
  for(i = m_services.size() - 1; i>=0; i--)
    m_services[i].m_service->stopSessions();
  
  if(!wait)
    return false; // No wait

  const NDB_TICKS start = NdbTick_getCurrentTicks();
  m_session_mutex.lock();
  while(m_sessions.size() > 0){
    checkSessionsImpl();
    m_session_mutex.unlock();

    if (wait_timeout > 0 &&
        NdbTick_Elapsed(start,NdbTick_getCurrentTicks()).milliSec() > wait_timeout)
      return false; // Wait abandoned

    NdbSleep_MilliSleep(100);
    m_session_mutex.lock();
  }
  m_session_mutex.unlock();
  return true; // All sessions gone
}
static bool file_exists(const char* path, Uint32 timeout = 1)
{
  g_info << "File '" << path << "' ";
  /**
   * ndb_mgmd does currently not fsync the directory
   *   after committing config-bin,
   *   which means that it can be on disk, wo/ being visible
   *   remedy this by retrying some
   */
  for (Uint32 i = 0; i < 10 * timeout; i++)
  {
    if (access(path, F_OK) == 0)
    {
      g_info << "exists" << endl;
      return true;
    }
    if (i == 0)
    {
      g_info << "does not exist, retrying...";
    }
    NdbSleep_MilliSleep(100);
  }
  g_info << "does not exist" << endl;
  return false;
}
int runMiscUntilStopped(NDBT_Context* ctx, NDBT_Step* step){
  int records = ctx->getNumRecords();
  int i = 0;
  Ndb * ndb = GETNDB(step);
  HugoTransactions hugoTrans(*ctx->getTab());
  while (ctx->isTestStopped() == false) {
    int r = 0;
    switch(i % 5) {
      case 0:  // batch size = 2, random = 1
        r = hugoTrans.pkReadRecords(ndb, records / 20, 2, 
                                    NdbOperation::LM_Read, 1);
        break;
      case 1:
        r = hugoTrans.pkUpdateRecords(ndb, records / 20);
        break;
      case 2:
        r = hugoTrans.scanReadRecords(ndb, records);
        break;
      case 3:
        r = hugoTrans.scanUpdateRecords(ndb, records / 10);
        break;
      case 4:
        NdbSleep_MilliSleep(records);
        break;
    }
    if(r != 0) return NDBT_FAILED;
    i++;
  }
  ndbout << "V2 Test misc thread: " << i << " transactions" << endl;
  return NDBT_OK;
}
Example #11
0
bool
TCP_Transporter::sendIsPossible(struct timeval * timeout) {
#ifdef NDB_OSE
  /**
   * In OSE you cant do select without owning a socket,
   * and since this method might be called by any thread in the api
   * we choose not to implementet and always return true after sleeping
   * a while.
   *
   * Note that this only sensible as long as the sockets are non blocking
   */
  if(theSocket >= 0){
    Uint32 timeOutMillis = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;
    NdbSleep_MilliSleep(timeOutMillis);
    return true;
  }
  return false;
#else
  if(theSocket != NDB_INVALID_SOCKET){
    fd_set   writeset;
    FD_ZERO(&writeset);
    FD_SET(theSocket, &writeset);
    
    int selectReply = select(theSocket + 1, NULL, &writeset, NULL, timeout);

    if ((selectReply > 0) && FD_ISSET(theSocket, &writeset)) 
      return true;
    else
      return false;
  }
  return false;
#endif
}
Example #12
0
void
start_T1(Ndb * pNDB, ThreadData * td, int async){

  DEBUG2("T1(%.*s): - Starting", SUBSCRIBER_NUMBER_LENGTH, 
	 td->transactionData.number); 

  NdbConnection * pCON = 0;
  while((pCON = startTransaction(pNDB, td)) == 0){
    CHECK_ALLOWED_ERROR("T1: startTransaction", td, pNDB->getNdbError());
    NdbSleep_MilliSleep(10);
  }

  NdbOperation *MyOp = pCON->getNdbOperation(SUBSCRIBER_TABLE);
  if (MyOp != NULL) {  
    MyOp->updateTuple();  
    MyOp->equal(IND_SUBSCRIBER_NUMBER, 
		td->transactionData.number);
    MyOp->setValue(IND_SUBSCRIBER_LOCATION, 
		   (char *)&td->transactionData.location);
    MyOp->setValue(IND_SUBSCRIBER_CHANGED_BY, 
		   td->transactionData.changed_by);
    MyOp->setValue(IND_SUBSCRIBER_CHANGED_TIME, 
		   td->transactionData.changed_time);
    if (async == 1) {
      pCON->executeAsynchPrepare( Commit , T1_Callback, td);
    } else {
      int result = pCON->execute(Commit);
      T1_Callback(result, pCON, (void*)td);
      return;
    }//if
  } else {
    CHECK_NULL(MyOp, "T1: getNdbOperation", td, pCON->getNdbError());
  }//if
}
int runScanRefreshNoTimeout(NDBT_Context* ctx, NDBT_Step* step){
  int result = NDBT_OK;
  int loops = ctx->getNumLoops();
  int records = ctx->getNumRecords();
  int stepNo = step->getStepNo();
  int maxSleep = (int)(TIMEOUT * 0.3);
  ndbout << "TransactionInactiveTimeout="<< TIMEOUT
	 << ", maxSleep="<<maxSleep<<endl;

  HugoOperations hugoOps(*ctx->getTab());
  Ndb* pNdb = GETNDB(step);

  for (int l = 1; l < loops && result == NDBT_OK; l++){

    do{
      // Start an insert trans
      CHECK(hugoOps.startTransaction(pNdb) == 0);
      int recordNo = records + (stepNo*loops) + l;
      CHECK(hugoOps.pkInsertRecord(pNdb, recordNo) == 0);
      CHECK(hugoOps.execute_NoCommit(pNdb) == 0);
      
      for (int i = 0; i < 3; i++)
      {
        NdbTransaction* pTrans = hugoOps.getTransaction();

        Vector<NdbScanOperation*> ops;
        for (int j = 0; j <= i; j++)
        {
          // Perform buddy scan reads
          NdbScanOperation* pOp = pTrans->getNdbScanOperation(ctx->getTab());
          CHECK(pOp != 0);
          CHECK(pOp->readTuples(NdbOperation::LM_Read, 0, 0, 1) == 0);
          ops.push_back(pOp);
        }
        CHECK(pTrans->execute(NoCommit) == 0);

        for (unsigned i = 0; i<TIMEOUT; i += 1000)
        {
          pTrans->refresh();
          NdbSleep_MilliSleep(1000);
        }

        int res;
        for (unsigned j = 0; j < ops.size(); j++)
        {
          while((res = ops[j]->nextResult()) == 0);
          CHECK(res != -1);
        }
      }

      // Expect that transaction has NOT timed-out
      CHECK(hugoOps.execute_Commit(pNdb) == 0); 
    
    } while(false);

    hugoOps.closeTransaction(pNdb);
  }

  return result;
}
Example #14
0
/**
 * Transaction 2 - T2
 *
 * Read from Subscriber:
 *
 * Input:
 *   SubscriberNumber
 *
 * Output:
 *   Location
 *   Changed by
 *   Changed Timestamp
 *   Name
 */
void
start_T2(Ndb * pNDB, ThreadData * td, int async) {

    DEBUG3("T2(%.*s, %d): - Starting", SUBSCRIBER_NUMBER_LENGTH,
           td->transactionData.number,
           td->transactionData.location);

    NdbConnection * pCON = 0;

    while((pCON = startTransaction(pNDB, td)) == 0) {
        CHECK_ALLOWED_ERROR("T2-1: startTransaction", td, pNDB->getNdbError());
        NdbSleep_MilliSleep(10);
    }

    if (td->ndbRecordSharedData)
    {
        char* rowPtr= (char*) &td->transactionData;
        const NdbRecord* record= td->ndbRecordSharedData->
                                 subscriberTableNdbRecord;
        Uint32 m=0;
        unsigned char* mask= (unsigned char*) &m;

        SET_MASK(mask, IND_SUBSCRIBER_LOCATION);
        SET_MASK(mask, IND_SUBSCRIBER_CHANGED_BY);
        SET_MASK(mask, IND_SUBSCRIBER_CHANGED_TIME);
        SET_MASK(mask, IND_SUBSCRIBER_NAME);

        const NdbOperation* MyOp= pCON->readTuple(record, rowPtr, record, rowPtr,
                                  NdbOperation::LM_Read, mask);
        CHECK_NULL((void*) MyOp, "T2: readTuple", td,
                   pCON->getNdbError());
    }
    else
    {
        NdbOperation *MyOp= pCON->getNdbOperation(SUBSCRIBER_TABLE);
        CHECK_NULL(MyOp, "T2: getNdbOperation", td,
                   pCON->getNdbError());

        MyOp->readTuple();
        MyOp->equal(IND_SUBSCRIBER_NUMBER,
                    td->transactionData.number);
        MyOp->getValue(IND_SUBSCRIBER_LOCATION,
                       (char *)&td->transactionData.location);
        MyOp->getValue(IND_SUBSCRIBER_CHANGED_BY,
                       td->transactionData.changed_by);
        MyOp->getValue(IND_SUBSCRIBER_CHANGED_TIME,
                       td->transactionData.changed_time);
        MyOp->getValue(IND_SUBSCRIBER_NAME,
                       td->transactionData.name);
    }

    if (async == 1) {
        pCON->executeAsynchPrepare( Commit , T2_Callback, td);
    } else {
        int result = pCON->execute(Commit);
        T2_Callback(result, pCON, (void*)td);
        return;
    }//if
}
bool
SCI_Transporter::init_remote()
{
  DBUG_ENTER("SCI_Transporter::init_remote");
  sci_error_t err; 
  Uint32 offset = 0;
  if(!m_mapped ) {
    DBUG_PRINT("info", ("Map remote segments"));
    for(Uint32 i=0; i < m_adapters ; i++) {
      m_TargetSegm[i].rhm[i].remoteHandle=0;
      SCIConnectSegment(sciAdapters[i].scidesc,
                        &(m_TargetSegm[i].rhm[i].remoteHandle),
                        m_remoteNodes[i],
                        remoteSegmentId(localNodeId, remoteNodeId),
                        i,
                        0,
                        0,
                        0,
                        0,
                        &err);

      if(err != SCI_ERR_OK) {
        NdbSleep_MilliSleep(10);
        DBUG_PRINT("error", ("Error connecting segment, err 0x%x", err));
        DBUG_RETURN(false);
      }
    }
    // Map the remote memory segment into program space  
    for(Uint32 i=0; i < m_adapters ; i++) {
      m_TargetSegm[i].mappedMemory =
        SCIMapRemoteSegment((m_TargetSegm[i].rhm[i].remoteHandle),
                            &(m_TargetSegm[i].rhm[i].map),
                            offset,
                            m_BufferSize,
                            NULL,
                            FLAGS,
                            &err);

      if(err!= SCI_ERR_OK) {
        DBUG_PRINT("error",
          ("Cannot map a segment to the remote node %d. Error code 0x%x",
          m_RemoteSciNodeId, err));
        //NDB SHOULD TERMINATE AND COMPUTER REBOOTED! 
        report_error(TE_SCI_CANNOT_MAP_REMOTESEGMENT);
        DBUG_RETURN(false);
      }
    }
    m_mapped=true;
    setupRemoteSegment();
    setConnected();
    DBUG_PRINT("info", ("connected and mapped to segment, remoteNode: %d",
               remoteNodeId));
    DBUG_PRINT("info", ("remoteSegId: %d",
               remoteSegmentId(localNodeId, remoteNodeId)));
    DBUG_RETURN(true);
  } else {
    DBUG_RETURN(getConnectionStatus());
  }
}
Example #16
0
Uint32 
TransporterRegistry::poll_TCP(Uint32 timeOutMillis)
{
  bool hasdata = false;
  if (false && nTCPTransporters == 0)
  {
    tcpReadSelectReply = 0;
    return 0;
  }
  
  NDB_SOCKET_TYPE maxSocketValue = -1;
  
  // 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
    NodeId nodeId = t->getRemoteNodeId();
    if (is_connected(nodeId) && 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);
    }
    hasdata |= t->hasReceiveData();
  }
  
  timeOutMillis = hasdata ? 0 : timeOutMillis;
  
  struct timeval timeout;
  timeout.tv_sec  = timeOutMillis / 1000;
  timeout.tv_usec = (timeOutMillis % 1000) * 1000;

  // The highest socket value plus one
  maxSocketValue++; 
  
  tcpReadSelectReply = select(maxSocketValue, &tcpReadset, 0, 0, &timeout);  
  if(false && tcpReadSelectReply == -1 && errno == EINTR)
    g_eventLogger.info("woke-up by signal");

#ifdef NDB_WIN32
  if(tcpReadSelectReply == SOCKET_ERROR)
  {
    NdbSleep_MilliSleep(timeOutMillis);
  }
#endif
  
  return tcpReadSelectReply || hasdata;
}
bool
SHM_Transporter::connectClient(Uint32 timeOutMillis){
  if(!_shmSegCreated)
  {
    char szName[32];
    sprintf(szName, "ndb%lu", shmKey);
    hFileMapping = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, szName);

    if(!hFileMapping)
    {
      NdbSleep_MilliSleep(timeOutMillis);
      return false;
    }
    _shmSegCreated = true;
  }

  if(!_attached){
    shmBuf = (char*)MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);
    if(shmBuf == 0){
      reportThreadError(remoteNodeId, TE_SHM_UNABLE_TO_ATTACH_SEGMENT);
      NdbSleep_MilliSleep(timeOutMillis);
      return false;
    }
    volatile Uint32 * sharedCountAttached = 
      (volatile Uint32*)(shmBuf + 6*sizeof(Uint32*));
    ++*sharedCountAttached;
    _attached = true;
  }
  
  volatile Uint32 * sharedCountAttached = 
    (volatile Uint32*)(shmBuf + 6*sizeof(Uint32*));

  if(*sharedCountAttached == 2 && !setupBuffersDone) {
    setupBuffers();
    setupBuffersDone=true;
  }

  if(setupBuffersDone) {
    if(*serverStatusFlag==1 && *clientStatusFlag==1)
      return true;
  }
  NdbSleep_MilliSleep(timeOutMillis);
  return false;

}
static void run_master_update(struct Xxx &xxx, struct XxxR &xxxr)
{
  Ndb *ndb = xxx.ndb;
  const NdbDictionary::Table *myTable = xxx.table;
  int retry_sleep= 10; /* 10 milliseconds */
  int retries= 100;
  while (1)
  {
    Uint32 val;
    NdbTransaction *trans = ndb->startTransaction();
    if (trans == NULL)
      goto err;
    {
      NdbOperation *op = trans->getNdbOperation(myTable);
      if (op == NULL)
        APIERROR(trans->getNdbError());
      op->readTupleExclusive();
      op->equal(xxx.pk_col, xxxr.pk_val);
      op->getValue(xxx.col, (char *)&val);
    }
    if (trans->execute(NdbTransaction::NoCommit))
      goto err;
    //fprintf(stderr, "read %u\n", val);
    xxxr.val = val + 1;
    {
      NdbOperation *op = trans->getNdbOperation(myTable);
      if (op == NULL)
        APIERROR(trans->getNdbError());
      op->updateTuple();
      op->equal(xxx.pk_col, xxxr.pk_val);
      op->setValue(xxx.col, xxxr.val);
    }
    if (trans->execute(NdbTransaction::Commit))
      goto err;
    ndb->closeTransaction(trans);
    //fprintf(stderr, "updated to %u\n", xxxr.val);
    break;
err:
    const NdbError this_error= trans ?
      trans->getNdbError() : ndb->getNdbError();
    if (this_error.status == NdbError::TemporaryError)
    {
      if (retries--)
      {
        if (trans)
          ndb->closeTransaction(trans);
        NdbSleep_MilliSleep(retry_sleep);
        continue; // retry
      }
    }
    if (trans)
      ndb->closeTransaction(trans);
    APIERROR(this_error);
  }
  /* update done start timer */
  gettimeofday(&xxxr.start_time, 0);
}
Example #19
0
bool
DbUtil::waitConnected(int timeout) {
  timeout*= 10;
  while(!isConnected()){
    if (timeout-- == 0)
      return false;
    NdbSleep_MilliSleep(100);
  }
  return true;
}
Example #20
0
/**
 * returns true if is recoverable,
 * Error handling based on hugo
 *  false if it is an  error that generates an abort.
 */
static
bool asynchErrorHandler(NdbTransaction * trans, Ndb* ndb) 
{
  NdbError error = trans->getNdbError();
  ndb->closeTransaction(trans);
  switch(error.status)
  {
  case NdbError::Success:
      return false;
      // ERROR!
      break;
      
  case NdbError::TemporaryError:
    NdbSleep_MilliSleep(10);
    return true;
    // RETRY
    break;
    
  case NdbError::UnknownResult:
    ndbout << error << endl;
    return false;
    // ERROR!
    break;
    
  default:
  case NdbError::PermanentError:
    switch (error.code)
    {
    case 499:
    case 250:
      NdbSleep_MilliSleep(10);
      return true; //temp errors?
    default:
      break;
    }
    //ERROR
    ndbout << error << endl;
    return false;
    break;
  }
  return false;
}
Example #21
0
inline
int 
SocketRegistry<T>::pollSocketClients(Uint32 timeOutMillis) {



  // Return directly if there are no TCP transporters configured
  if (m_nSocketClients == 0){
    tcpReadSelectReply = 0;
    return 0;
  }
  struct timeval timeout;
  timeout.tv_sec  = timeOutMillis / 1000;
  timeout.tv_usec = (timeOutMillis % 1000) * 1000;


  NDB_SOCKET_TYPE maxSocketValue = 0;
  
  // Needed for TCP/IP connections
  // The read- and writeset are used by select
  
  FD_ZERO(&tcpReadset);

  // Prepare for sending and receiving
  for (Uint32 i = 0; i < m_nSocketClients; i++) {
    SocketClient * t = m_socketClients[i];
    
    // If the socketclient 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);  
#ifdef NDB_WIN32
  if(tcpReadSelectReply == SOCKET_ERROR)
  {
    NdbSleep_MilliSleep(timeOutMillis);
  }
#endif

  return tcpReadSelectReply;

}
void
SocketServer::doRun(){

  while(!m_stopThread){
    m_session_mutex.lock();
    checkSessionsImpl();
    m_session_mutex.unlock();

    if(m_sessions.size() >= m_maxSessions){
      // Don't accept more connections yet
      NdbSleep_MilliSleep(200);
      continue;
    }

    if (!doAccept()){
      // accept failed, step back
      NdbSleep_MilliSleep(200);
    }
  }
}
Example #23
0
int
Ndb_cluster_connection::wait_until_ready(int timeout,
					 int timeout_after_first_alive)
{
  DBUG_ENTER("Ndb_cluster_connection::wait_until_ready");
  TransporterFacade *tp = TransporterFacade::instance();
  if (tp == 0)
  {
    DBUG_RETURN(-1);
  }
  if (tp->ownId() == 0)
  {
    DBUG_RETURN(-1);
  }
  int secondsCounter = 0;
  int milliCounter = 0;
  int noChecksSinceFirstAliveFound = 0;
  do {
    unsigned int foundAliveNode = 0;
    tp->lock_mutex();
    for(unsigned i= 0; i < no_db_nodes(); i++)
    {
      //************************************************
      // If any node is answering, ndb is answering
      //************************************************
      if (tp->get_node_alive(m_impl.m_all_nodes[i].id) != 0) {
	foundAliveNode++;
      }
    }
    tp->unlock_mutex();

    if (foundAliveNode == no_db_nodes())
    {
      DBUG_RETURN(0);
    }
    else if (foundAliveNode > 0)
    {
      noChecksSinceFirstAliveFound++;
      // 100 ms delay -> 10*
      if (noChecksSinceFirstAliveFound > 10*timeout_after_first_alive)
	DBUG_RETURN(1);
    }
    else if (secondsCounter >= timeout)
    { // no alive nodes and timed out
      DBUG_RETURN(-1);
    }
    NdbSleep_MilliSleep(100);
    milliCounter += 100;
    if (milliCounter >= 1000) {
      secondsCounter++;
      milliCounter = 0;
    }//if
  } while (1);
}
Example #24
0
void SleepOneCall(void)
{
    int iMillisecToSleep;
    if(g_nMaxCallsPerSecond>0)
        iMillisecToSleep = (1000*g_nNumThreads)/g_nMaxCallsPerSecond;
    else
        iMillisecToSleep = 50;

    if(iMillisecToSleep>0)
        NdbSleep_MilliSleep(iMillisecToSleep);

}
Example #25
0
int runPkReadPkUpdateUntilStopped(NDBT_Context* ctx, NDBT_Step* step){
  int result = NDBT_OK;
  int records = ctx->getNumRecords();
  Ndb* pNdb = GETNDB(step);
  int i = 0;
  HugoOperations hugoOps(*ctx->getTab());
  while (ctx->isTestStopped() == false) {
    g_info << i++ << ": ";
    int rows = (rand()%records)+1;
    int batch = (rand()%rows)+1;
    int row = (records - rows) ? rand() % (records - rows) : 0;
    
    int j,k;
    for(j = 0; j<rows; j += batch)
    {
      k = batch;
      if(j+k > rows)
	k = rows - j;
      
      if(hugoOps.startTransaction(pNdb) != 0)
	goto err;
      
      if(hugoOps.pkReadRecord(pNdb, row+j, k, NdbOperation::LM_Exclusive) != 0)
	goto err;

      if(hugoOps.execute_NoCommit(pNdb) != 0)
	goto err;

      if(hugoOps.pkUpdateRecord(pNdb, row+j, k, rand()) != 0)
	goto err;

      if(hugoOps.execute_Commit(pNdb) != 0)
	goto err;

      if(hugoOps.closeTransaction(pNdb) != 0)
	return NDBT_FAILED;
    }
    
    continue;
err:
    NdbConnection* pCon = hugoOps.getTransaction();
    if(pCon == 0)
      continue;
    NdbError error = pCon->getNdbError();
    hugoOps.closeTransaction(pNdb);
    if (error.status == NdbError::TemporaryError){
      NdbSleep_MilliSleep(50);
      continue;
    }
    return NDBT_FAILED;    
  }
  return NDBT_OK;
}
// Wait until connected to ndb_mgmd
int
NdbRestarter::waitConnected(unsigned int _timeout){
  _timeout*= 10;
  while (isConnected() && getStatus() != 0){
    if (_timeout-- == 0){
      ndbout << "NdbRestarter::waitConnected failed" << endl;
      return -1;
    }
    NdbSleep_MilliSleep(100);
  }
  return 0;
}
/* Producer thread */
int runV2MultiWait_Producer(NDBT_Context* ctx, NDBT_Step* step,
                           int thd_id, int nthreads)
{
  int records = ctx->getNumRecords();
  HugoOperations hugoOps(*ctx->getTab());

  /* For three threads (2 producers + 1 consumer) we loop 0-7.
     producer 0 is slow if (loop & 1)  
     producer 1 is slow if (loop & 2)
     consumer is slow if (loop & 4)
  */
  for (int loop = 0; loop < V2_NLOOPS; loop++) 
  {
    ctx->getPropertyWait("LOOP", loop+1);
    bool slow = loop & (thd_id+1);
    for (int j=0; j < records; j++)
    {
      if(j % nthreads == thd_id) 
      {
        Ndb* ndb = global_ndb_pool->getNdb();
        NdbTransaction* trans = ndb->startTransaction();
        check(trans != NULL, (*ndb));
        ndb->setCustomData(trans);

        NdbOperation* readOp = trans->getNdbOperation(ctx->getTab());
        check(readOp != NULL, (*trans));
        check(readOp->readTuple() == 0, (*readOp));
        check(hugoOps.equalForRow(readOp, j) == 0, hugoOps);

        /* Read all other cols */
        for (int k=0; k < ctx->getTab()->getNoOfColumns(); k++)
        {
          check(readOp->getValue(ctx->getTab()->getColumn(k)) != NULL,
                (*readOp));
        }

        trans->executeAsynchPrepare(NdbTransaction::Commit,
                                    NULL,
                                    NULL,
                                    NdbOperation::AbortOnError);
        ndb->sendPreparedTransactions();
        global_poll_group->push(ndb);
        if(slow) 
        {
          int tm = myRandom48(3) * myRandom48(3);
          if(tm) NdbSleep_MilliSleep(tm);
        }
      }
    }
  } 
  return NDBT_OK;
}
Example #28
0
int
runWait(NDBT_Context* ctx, NDBT_Step* step)
{
    Uint32 waitSeconds = ctx->getProperty("WaitSeconds", Uint32(30));
    while (waitSeconds &&
            !ctx->isTestStopped())
    {
        NdbSleep_MilliSleep(1000);
        waitSeconds --;
    }
    ctx->stopTest();
    return NDBT_OK;
}
Example #29
0
bool
BackupRestore::finalize_table(const TableS & table){
  bool ret= true;
  if (!m_restore && !m_restore_meta)
    return ret;
  if (!table.have_auto_inc())
    return ret;

  Uint64 max_val= table.get_max_auto_val();
  do
  {
    Uint64 auto_val = ~(Uint64)0;
    int r= m_ndb->readAutoIncrementValue(get_table(table.m_dictTable), auto_val);
    if (r == -1 && m_ndb->getNdbError().status == NdbError::TemporaryError)
    {
      NdbSleep_MilliSleep(50);
      continue; // retry
    }
    else if (r == -1 && m_ndb->getNdbError().code != 626)
    {
      ret= false;
    }
    else if ((r == -1 && m_ndb->getNdbError().code == 626) ||
             max_val+1 > auto_val || auto_val == ~(Uint64)0)
    {
      r= m_ndb->setAutoIncrementValue(get_table(table.m_dictTable),
                                      max_val+1, false);
      if (r == -1 &&
            m_ndb->getNdbError().status == NdbError::TemporaryError)
      {
        NdbSleep_MilliSleep(50);
        continue; // retry
      }
      ret = (r == 0);
    }
    return (ret);
  } while (1);
}
Example #30
0
void 
waitForThreads(void)
{
  int cont;
  do {
    cont = 0;
    NdbSleep_MilliSleep(20);
    for (int i = 0; i < tNoOfThreads ; i++) {
      if (ThreadReady[i] == 0) {
        cont = 1;
      }
    }
  } while (cont == 1);
}