int
verifySlave_rep1(NDBT_Context* ctx, NDBT_Step* step)
{
  BaseString sql;
  BaseString db;
  BaseString column;

  sql.assign("SELECT SUM(c3) FROM rep1");
  db.assign("TEST_DB");
  column.assign("c3");

  if (!verifySlave(sql,db,column))
    return NDBT_FAILED;
  return NDBT_OK;
}
示例#2
0
BaseString replace_tags(const char* str)
{
  BaseString result(str);
  for (size_t i = 0; i < num_replaces; i++)
  {
    Vector<BaseString> parts;
    const char* p = result.c_str();
    const char* tag = replaces[i].tag;

    /* Split on <tag> */
    const char* first;
    while((first = strstr(p, tag)))
    {
      BaseString part;
      part.assign(p, first - p);
      parts.push_back(part);
      p = first + strlen(tag);
    }
    parts.push_back(p);

    /* Put back together */
    BaseString res;
    const char* separator = "";
    for (unsigned j = 0; j < parts.size(); j++)
    {
      res.appfmt("%s%s", separator, parts[j].c_str());
      separator = replaces[i].string;
    }

    /* Save result from this loop */
    result = res;
  }
  return result;
}
bool
SocketInputStream2::get_buffered_line(BaseString& str)
{
  char *start, *ptr;
  char *end = (char*)m_buffer.get_data() + m_buffer.length();
  start = ptr =(char*)m_buffer.get_data() + m_buffer_read_pos;

  while(ptr && ptr < end && *ptr)
  {
    if (*ptr == '\n')
    {
      size_t len = ptr-start;
      /* Found end of line, return this part of the buffer */
      str.assign(start, len);

      /*
         Set new read position in buffer, increase with
         one to step past '\n'
      */
      m_buffer_read_pos += (len + 1);

      return true;
    }
    ptr++;
  }
  return false;
}
bool
verifySlaveLoad(BaseString &table)
{
  //BaseString  sqlStm;
  BaseString  db;
  unsigned int masterCount = 0;
  unsigned int slaveCount  = 0;
 
  db.assign("TEST_DB");
  //sqlStm.assfmt("SELECT COUNT(*) FROM %s", table);

  //First thing to do is sync slave
  printf("Calling syncSlave\n");
  if(!syncSlaveWithMaster())
  {
    g_err << "Verify Load -> Syncing with slave failed" << endl;
    return false;
  }

  //Now that slave is sync we can verify load
  DbUtil master(db.c_str());

  //Login to Master
  if (!master.connect())
  {
    g_err << "Verify Load -> connect to master failed" << endl;
    return false;
  }

  if((masterCount = master.selectCountTable(table.c_str())) == 0 )
  {
    g_err << "Verify Load -> masterCount == ZERO!" << endl;
    return false;
  }
  
  //Create a DB Object for slave
  DbUtil slave(db.c_str(), ".1.slave");

  //Login to slave
  if (!slave.connect())
  {
    g_err << "Verify Load -> connect to master failed" << endl;
    return false;
  }

  if((slaveCount = slave.selectCountTable(table.c_str())) == 0 )
  {
    g_err << "Verify Load -> slaveCount == ZERO" << endl;
    return false;
  }
  
  if(slaveCount != masterCount)
  {
    g_err << "Verify Load -> Slave Count != Master Count "
          << endl;
    return false;
  }
  return true;
}
示例#5
0
//---------------------------------------------------------------------------
BaseString IpAddressToString(int IP)
{
    in_addr Addr;
    BaseString Result;
    Addr.s_addr=IP;
    Result.assign(inet_ntoa(Addr));
    return Result;
}
示例#6
0
BaseString
BaseString::substr(ssize_t start, ssize_t stop) {
    if(stop < 0)
	stop = length();
    ssize_t len = stop-start;
    if(len <= 0)
	return BaseString("");
    BaseString s;
    s.assign(m_chr+start, len);
    return s;
}
示例#7
0
//---------------------------------------------------------------------------
BaseString TimeToString(time_t dt)
{
    char dts[50];
    BaseString Result;
    struct tm * DateTime = localtime (&dt);
    if (DateTime!=NULL) {
        strftime(dts,50,"%Y-%m-%d %H:%M:%S",DateTime);
        Result.assign(dts);
        return Result;
    }
    else
        return "";
}
示例#8
0
//---------------------------------------------------------------------------
BaseString NumToString(int Value, int Base, unsigned int Len)
{
	char CNumber[50];
	BaseString result;
	itoa(Value,CNumber,Base);
	result.assign(CNumber);
	if (Len>0)
	{
		while (result.length()<Len)
            result="0"+result;
	}
	return result;
}
示例#9
0
static BaseString path(const char* first, ...)
{
  BaseString path;
  path.assign(first);

  const char* str;
  va_list args;
  va_start(args, first);
  while ((str = va_arg(args, const char*)) != NULL)
  {
    path.appfmt("%s%s", DIR_SEPARATOR, str);
  }
  va_end(args);
  return path;
}
示例#10
0
int
createTEST_DB(NDBT_Context* ctx, NDBT_Step* step)
{
  BaseString cdb;
  cdb.assign("TEST_DB");

  //Create a dbutil object
  DbUtil master("mysql");

  if (!master.connect())
  {
    g_err << "Create DB -> Connect to master failed"
          << endl;
    return NDBT_FAILED;
  }

  if (!master.createDb(cdb))
  {
      return NDBT_FAILED;
  }
  return NDBT_OK;
}
示例#11
0
void
CPCD::Process::do_exec() {
  unsigned i;

#ifdef _WIN32
  Vector<BaseString> saved;
  char *cwd = 0;
  save_environment(m_env.c_str(), saved);
#endif

  setup_environment(m_env.c_str());

  char **argv = BaseString::argify(m_path.c_str(), m_args.c_str());

  if(strlen(m_cwd.c_str()) > 0) {
#ifdef _WIN32
    cwd = getcwd(0, 0);
    if(!cwd)
    {
      logger.critical("Couldn't getcwd before spawn");
    }
#endif
    int err = chdir(m_cwd.c_str());
    if(err == -1) {
      BaseString err;
      logger.error("%s: %s\n", m_cwd.c_str(), strerror(errno));
      _exit(1);
    }
  }
#ifndef _WIN32
  Vector<BaseString> ulimit;
  m_ulimit.split(ulimit);
  for(i = 0; i<ulimit.size(); i++){
    if(ulimit[i].trim().length() > 0 && set_ulimit(ulimit[i]) != 0){
      _exit(1);
    }
  }
#endif

  const char *nul = IF_WIN("nul:", "/dev/null");
  int fdnull = open(nul, O_RDWR, 0);
  if(fdnull == -1) {
    logger.error("Cannot open `%s': %s\n", nul, strerror(errno));
    _exit(1);
  }
  
  BaseString * redirects[] = { &m_stdin, &m_stdout, &m_stderr };
  int fds[3];
#ifdef _WIN32
  int std_dups[3];
#endif
  for (i = 0; i < 3; i++) {
#ifdef _WIN32
    std_dups[i] = dup(i);
#endif
    if (redirects[i]->empty()) {
#ifndef DEBUG
      dup2(fdnull, i);
#endif
      continue;
    }
    
    if((* redirects[i]) == "2>&1" && i == 2){
      dup2(fds[1], 2);
      continue;
    }
    
    /**
     * Make file
     */
    int flags = 0;
    int mode = S_IRUSR | S_IWUSR ;
    if(i == 0){
      flags |= O_RDONLY;
    } else {
      flags |= O_WRONLY | O_CREAT | O_APPEND;
    }
    int f = fds[i]= open(redirects[i]->c_str(), flags, mode);
    if(f == -1){
      logger.error("Cannot redirect %u to/from '%s' : %s\n", i,
		   redirects[i]->c_str(), strerror(errno));
      _exit(1);
    }
    dup2(f, i);
#ifdef _WIN32
    close(f);
#endif
  }

#ifndef _WIN32
  /* Close all filedescriptors */
  for(i = STDERR_FILENO+1; (int)i < getdtablesize(); i++)
    close(i);

  execv(m_path.c_str(), argv);
  /* XXX If we reach this point, an error has occurred, but it's kind of hard
   * to report it, because we've closed all files... So we should probably
   * create a new logger here */
  logger.error("Exec failed: %s\n", strerror(errno));
  /* NOTREACHED */
#else

  // Get full path to cygwins shell
  FILE *fpipe = _popen("sh -c 'cygpath -w `which sh`'", "rt");
  char buf[MAX_PATH];

  require(fgets(buf, MAX_PATH - 1, fpipe));
  fclose(fpipe);

  BaseString sh;
  sh.assign(buf);
  sh.trim("\n");
  sh.append(".exe");

  BaseString shcmd;
  shcmd.assfmt("%s -c '%s %s'", sh.c_str(), m_path.c_str(), m_args.c_str());

  PROCESS_INFORMATION pi = {0};
  STARTUPINFO si = {sizeof(STARTUPINFO), 0};

  si.dwFlags   |=  STARTF_USESTDHANDLES;
  si.hStdInput  = (HANDLE)_get_osfhandle(0);
  si.hStdOutput = (HANDLE)_get_osfhandle(1);
  si.hStdError  = (HANDLE)_get_osfhandle(2);

  if(!CreateProcessA(sh.c_str(),
                     (LPSTR)shcmd.c_str(),
                     NULL,
                     NULL,
                     TRUE,
                     CREATE_SUSPENDED, // Resumed after assigned to Job
                     NULL,
                     NULL,
                     &si,
                     &pi))
  {
    char* message;
    DWORD err = GetLastError();

    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                  FORMAT_MESSAGE_FROM_SYSTEM |
                  FORMAT_MESSAGE_IGNORE_INSERTS,
                  NULL,
                  err,
                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                  (LPTSTR)&message,
                  0, NULL );

    logger.error("CreateProcess failed, error: %d, message: '%s'",
                 err, message);
    LocalFree(message);

  }

  HANDLE proc = pi.hProcess;
  require(proc);

  // Job control
  require(m_job = CreateJobObject(0, 0));
  require(AssignProcessToJobObject(m_job, proc));

  // Resum process after it has been added to Job
  ResumeThread(pi.hThread);
  CloseHandle(pi.hThread);


  // go back up to original cwd
  if(chdir(cwd))
  {
    logger.critical("Couldn't go back to saved cwd after spawn()");
    logger.critical("errno: %d, strerror: %s", errno, strerror(errno));
  }
  free(cwd);

  // get back to original std i/o
  for(i = 0; i < 3; i++) {
    dup2(std_dups[i], i);
    close(std_dups[i]);
  }

  for (i = 0; i < saved.size(); i++) {
    putenv(saved[i].c_str());
  }

  logger.debug("'%s' has been started", shcmd.c_str());

  DWORD exitcode;
  BOOL result = GetExitCodeProcess(proc, &exitcode);
  //maybe a short running process
  if (result && exitcode != 259) {
    m_status = STOPPED;
    logger.warning("Process terminated early");
  }

  int pid = GetProcessId(proc);
  if (!pid)
    logger.critical("GetProcessId failed, error: %d!", GetLastError());

  logger.debug("new pid %d", pid);

  CloseHandle(proc);
  m_status = RUNNING;
  writePid(pid);
#endif

  close(fdnull);
}
示例#12
0
int main(int argc, char** argv) {
    NDB_INIT(argv[0]);

    load_defaults("my",load_default_groups,&argc,&argv);
    int ho_error;
#ifndef DBUG_OFF
    opt_debug= "d:t:O,/tmp/ndb_mgm.trace";
#endif
    if ((ho_error=handle_options(&argc, &argv, my_long_options,
                                 ndb_std_get_one_option)))
        exit(ho_error);

    char buf[MAXHOSTNAMELEN+10];
    if(argc == 1) {
        BaseString::snprintf(buf, sizeof(buf), "%s",  argv[0]);
        opt_connect_str= buf;
    } else if (argc >= 2) {
        BaseString::snprintf(buf, sizeof(buf), "%s:%s",  argv[0], argv[1]);
        opt_connect_str= buf;
    }

    if (!isatty(0) || opt_execute_str)
    {
        prompt= 0;
    }

    signal(SIGPIPE, handler);
    com = new Ndb_mgmclient(opt_connect_str,1);
    int ret= 0;
    BaseString histfile;
    if (!opt_execute_str)
    {
#ifdef HAVE_READLINE
        char *histfile_env= getenv("NDB_MGM_HISTFILE");
        if (histfile_env)
            histfile.assign(histfile_env,strlen(histfile_env));
        else if(getenv("HOME"))
        {
            histfile.assign(getenv("HOME"),strlen(getenv("HOME")));
            histfile.append("/.ndb_mgm_history");
        }
        if (histfile.length())
            read_history(histfile.c_str());
#endif

        ndbout << "-- NDB Cluster -- Management Client --" << endl;
        while(read_and_execute(_try_reconnect));

#ifdef HAVE_READLINE
        if (histfile.length())
        {
            BaseString histfile_tmp;
            histfile_tmp.assign(histfile);
            histfile_tmp.append(".TMP");
            if(!write_history(histfile_tmp.c_str()))
                my_rename(histfile_tmp.c_str(), histfile.c_str(), MYF(MY_WME));
        }
#endif
    }
    else
    {
        com->execute(opt_execute_str,_try_reconnect, 0, &ret);
    }
    delete com;

    ndb_end(opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
    return ret;
}
示例#13
0
int
createTable_rep1(NDBT_Context* ctx, NDBT_Step* step)
{
  BaseString table;
  BaseString db;

  table.assign("rep1");
  db.assign("TEST_DB");

  //Ensure slave is up and ready
  if(!syncSlaveWithMaster())
  {
    g_err << "Create Table -> Syncing with slave failed"
          << endl;
    return NDBT_FAILED;
  }

  //Create an SQL Object
  DbUtil master(db.c_str());

  //Login to Master
  if (!master.connect())
  {
    g_err << "Create Table -> Connect to Master failed"
          << endl;
    return NDBT_FAILED;
  }

  if (!master.doQuery("CREATE TABLE rep1 (c1 MEDIUMINT NOT NULL AUTO_INCREMENT,"
                     " c2 FLOAT, c3 CHAR(5), c4 TEXT(8), c5 FLOAT, c6 INT,"
                     " c7 INT, PRIMARY KEY (c1))ENGINE=NDB"))
  {
    g_err << "Create Table -> Create table SQL failed"
          << endl;
    return NDBT_FAILED;
  }

  /* Not happy with the data hugo generated

  Ndb* ndb=GETNDB(step);
  NdbDictionary::Dictionary* myDict = ndb->getDictionary();
  const NdbDictionary::Table *ndbTab = myDict->getTable(table.c_str());
  HugoTransactions hugoTrans(*ndbTab);

  if (hugoTrans.loadTable(GETNDB(step), ctx->getNumRecords(), 1, true, 0)
      == NDBT_FAILED)
  {
    g_err << "Create Table -> Hudo Load failed!" << endl;
    return NDBT_FAILED;
  }

  */

  for(int i = 0; i < ctx->getNumRecords(); i++)
  {
    if (!master.doQuery("INSERT INTO rep1 VALUES(NULL, 0, 'TEXAS', 'works', 0, 2, 1)"))
    {
       g_err << "Create Table -> Insert SQL failed"
             << endl;
       return NDBT_FAILED;
    }
  }

  if(!verifySlaveLoad(table))
  {
    g_err << "Create Table -> Failed on verify slave load!" 
          << endl;
    return NDBT_FAILED;
  }
  //else everything is okay  
  return NDBT_OK;
}
 SavedRecord(int _gci, BaseString _str){ 
   m_gci = _gci; 
   m_str.assign(_str); 
 }
示例#15
0
int main(int argc, char** argv){
  NDB_INIT(argv[0]);

  ndb_opt_set_usage_funcs(short_usage_sub, usage);
  load_defaults("my",load_default_groups,&argc,&argv);
  int ho_error;
#ifndef DBUG_OFF
  opt_debug= "d:t:O,/tmp/ndb_mgm.trace";
#endif
  if ((ho_error=handle_options(&argc, &argv, my_long_options,
			       ndb_std_get_one_option)))
    exit(ho_error);

  BaseString connect_str(opt_ndb_connectstring);
  if(argc == 1) {
    connect_str.assfmt("%s", argv[0]);
  } else if (argc >= 2) {
    connect_str.assfmt("%s:%s", argv[0], argv[1]);
  }

  if (!isatty(0) || opt_execute_str)
  {
    prompt= 0;
  }

  com = new Ndb_mgmclient(connect_str.c_str(), opt_verbose);
  int ret= 0;
  BaseString histfile;
  if (!opt_execute_str)
  {
#ifdef HAVE_READLINE
    char *histfile_env= getenv("NDB_MGM_HISTFILE");
    if (histfile_env)
      histfile.assign(histfile_env,strlen(histfile_env));
    else if(getenv("HOME"))
    {
      histfile.assign(getenv("HOME"),strlen(getenv("HOME")));
      histfile.append("/.ndb_mgm_history");
    }
    if (histfile.length())
      read_history(histfile.c_str());
#endif

    ndbout << "-- NDB Cluster -- Management Client --" << endl;
    while(read_and_execute(opt_try_reconnect))
      ;

#ifdef HAVE_READLINE
    if (histfile.length())
    {
      BaseString histfile_tmp;
      histfile_tmp.assign(histfile);
      histfile_tmp.append(".TMP");
      if(!write_history(histfile_tmp.c_str()))
        my_rename(histfile_tmp.c_str(), histfile.c_str(), MYF(MY_WME));
    }
#endif
  }
  else
  {
    com->execute(opt_execute_str, opt_try_reconnect, 0, &ret);
  }
  delete com;

  ndb_end(opt_ndb_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);

  // Don't allow negative return code
  if (ret < 0)
    ret = 255;
  return ret;
}