Exemplo n.º 1
0
static char* 
NdbConfig_AllocHomePath(int _len)
{
  int path_len;
  const char *path= NdbConfig_get_path(&path_len);
  int len= _len+path_len;
  char *buf= NdbMem_Allocate(len);
  basestring_snprintf(buf, len, "%s%s", path, DIR_SEPARATOR);
  return buf;
}
Exemplo n.º 2
0
/*
 *  MAIN 
 */
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_mgmd.trace";
#endif
  if ((ho_error=handle_options(&argc, &argv, my_long_options, 
			       ndb_std_get_one_option)))
    exit(ho_error);

start:
  glob= new MgmGlobals;

  /**
   * OSE specific. Enable shared ownership of file system resources. 
   * This is needed in order to use the cluster log since the events 
   * from the cluster is written from the 'ndb_receive'(NDBAPI) thread/process.
   */
#if defined NDB_OSE || defined NDB_SOFTOSE
  efs_segment_share();
#endif

  global_mgmt_server_check = 1;

  if (opt_interactive ||
      opt_non_interactive ||
      g_print_full_config) {
    opt_daemon= 0;
  }

  if (opt_mycnf && opt_config_filename)
  {
    ndbout_c("Both --mycnf and -f is not supported");
    return 0;
  }

  if (opt_mycnf == 0 && opt_config_filename == 0)
  {
    struct stat buf;
    if (stat("config.ini", &buf) != -1)
      opt_config_filename = "config.ini";
  }
  
  glob->socketServer = new SocketServer();

  MgmApiService * mapi = new MgmApiService();

  glob->mgmObject = new MgmtSrvr(glob->socketServer,
				 opt_config_filename,
				 opt_connect_str);

  if (g_print_full_config)
    goto the_end;

  if (glob->mgmObject->init())
    goto error_end;

  my_setwd(NdbConfig_get_path(0), MYF(0));

  glob->localNodeId= glob->mgmObject->getOwnNodeId();
  if (glob->localNodeId == 0) {
    goto error_end;
  }

  glob->port= glob->mgmObject->getPort();

  if (glob->port == 0)
    goto error_end;

  glob->interface_name = 0;
  glob->use_specific_ip = false;

  if(!glob->use_specific_ip){
    int count= 5; // no of retries for tryBind
    while(!glob->socketServer->tryBind(glob->port, glob->interface_name)){
      if (--count > 0) {
	NdbSleep_MilliSleep(1000);
	continue;
      }
      ndbout_c("Unable to setup port: %s:%d!\n"
	       "Please check if the port is already used,\n"
	       "(perhaps a ndb_mgmd is already running),\n"
	       "and if you are executing on the correct computer", 
	       (glob->interface_name ? glob->interface_name : "*"), glob->port);
      goto error_end;
    }
    free(glob->interface_name);
    glob->interface_name = 0;
  }

  if(!glob->socketServer->setup(mapi, &glob->port, glob->interface_name))
  {
    ndbout_c("Unable to setup management port: %d!\n"
	     "Please check if the port is already used,\n"
	     "(perhaps a ndb_mgmd is already running),\n"
	     "and if you are executing on the correct computer", 
	     glob->port);
    delete mapi;
    goto error_end;
  }

  if(!glob->mgmObject->check_start()){
    ndbout_c("Unable to check start management server.");
    ndbout_c("Probably caused by illegal initial configuration file.");
    goto error_end;
  }

  if (opt_daemon) {
    // Become a daemon
    char *lockfile= NdbConfig_PidFileName(glob->localNodeId);
    char *logfile=  NdbConfig_StdoutFileName(glob->localNodeId);
    NdbAutoPtr<char> tmp_aptr1(lockfile), tmp_aptr2(logfile);

    if (NdbDaemon_Make(lockfile, logfile, 0) == -1) {
      ndbout << "Cannot become daemon: " << NdbDaemon_ErrorText << endl;
      return 1;
    }
  }

#ifndef NDB_WIN32
  signal(SIGPIPE, SIG_IGN);
#endif
  {
    BaseString error_string;
    if(!glob->mgmObject->start(error_string)){
      ndbout_c("Unable to start management server.");
      ndbout_c("Probably caused by illegal initial configuration file.");
      ndbout_c(error_string.c_str());
      goto error_end;
    }
  }

  //glob->mgmObject->saveConfig();
  mapi->setMgm(glob->mgmObject);

  char msg[256];
  BaseString::snprintf(msg, sizeof(msg),
	   "NDB Cluster Management Server. %s", NDB_VERSION_STRING);
  ndbout_c(msg);
  g_eventLogger.info(msg);

  BaseString::snprintf(msg, 256, "Id: %d, Command port: %d",
	   glob->localNodeId, glob->port);
  ndbout_c(msg);
  g_eventLogger.info(msg);
  
  g_StopServer = false;
  g_RestartServer= false;
  glob->socketServer->startServer();

#if ! defined NDB_OSE && ! defined NDB_SOFTOSE
  if(opt_interactive) {
    BaseString con_str;
    if(glob->interface_name)
      con_str.appfmt("host=%s:%d", glob->interface_name, glob->port);
    else 
      con_str.appfmt("localhost:%d", glob->port);
    Ndb_mgmclient com(con_str.c_str(), 1);
    while(g_StopServer != true && read_and_execute(&com, "ndb_mgm> ", 1));
  } else 
#endif
  {
    while(g_StopServer != true)
      NdbSleep_MilliSleep(500);
  }

  if(g_RestartServer)
    g_eventLogger.info("Restarting server...");
  else
    g_eventLogger.info("Shutting down server...");
  glob->socketServer->stopServer();
  // We disconnect from the ConfigRetreiver mgmd when we delete glob below
  glob->socketServer->stopSessions(true);
  g_eventLogger.info("Shutdown complete");
 the_end:
  delete glob;
  if(g_RestartServer)
    goto start;
  ndb_end(opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
  return 0;
 error_end:
  delete glob;
  ndb_end(opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
  return 1;
}
Exemplo n.º 3
0
void
ndbd_run(bool foreground, int report_fd,
         const char* connect_str, int force_nodeid, const char* bind_address,
         bool no_start, bool initial, bool initialstart,
         unsigned allocated_nodeid)
{
#ifdef _WIN32
  {
    char shutdown_event_name[32];
    _snprintf(shutdown_event_name, sizeof(shutdown_event_name),
              "ndbd_shutdown_%d", GetCurrentProcessId());

    g_shutdown_event = CreateEvent(NULL, TRUE, FALSE, shutdown_event_name);
    if (g_shutdown_event == NULL)
    {
      g_eventLogger->error("Failed to create shutdown event, error: %d",
                           GetLastError());
     ndbd_exit(1);
    }

    HANDLE thread = CreateThread(NULL, 0, &shutdown_thread, NULL, 0, NULL);
    if (thread == NULL)
    {
      g_eventLogger->error("couldn't start shutdown thread, error: %d",
                           GetLastError());
      ndbd_exit(1);
    }
  }
#endif

  if (foreground)
    g_eventLogger->info("Ndb started in foreground");

  if (report_fd)
  {
    g_eventLogger->debug("Opening report stream on fd: %d", report_fd);
    // Open a stream for sending extra status to angel
    if (!(angel_info_w = fdopen(report_fd, "w")))
    {
      g_eventLogger->error("Failed to open stream for reporting "
                           "to angel, error: %d (%s)", errno, strerror(errno));
      ndbd_exit(-1);
    }
  }
  else
  {
    // No reporting requested, open /dev/null
    const char* dev_null = IF_WIN("nul", "/dev/null");
    if (!(angel_info_w = fopen(dev_null, "w")))
    {
      g_eventLogger->error("Failed to open stream for reporting to "
                           "'%s', error: %d (%s)", dev_null, errno,
                           strerror(errno));
      ndbd_exit(-1);
    }
  }

  globalEmulatorData.create();

  Configuration* theConfig = globalEmulatorData.theConfiguration;
  if(!theConfig->init(no_start, initial, initialstart))
  {
    g_eventLogger->error("Failed to init Configuration");
    ndbd_exit(-1);
  }

  theConfig->fetch_configuration(connect_str, force_nodeid, bind_address,
                                 allocated_nodeid);

  if (NdbDir::chdir(NdbConfig_get_path(NULL)) != 0)
  {
    g_eventLogger->warning("Cannot change directory to '%s', error: %d",
                           NdbConfig_get_path(NULL), errno);
    // Ignore error
  }

  theConfig->setupConfiguration();

  if (get_multithreaded_config(globalEmulatorData))
    ndbd_exit(-1);

  systemInfo(* theConfig, * theConfig->m_logLevel);

  NdbThread* pWatchdog = globalEmulatorData.theWatchDog->doStart();

  {
    /*
     * Memory allocation can take a long time for large memory.
     *
     * So we want the watchdog to monitor the process of initial allocation.
     */
    Uint32 watchCounter;
    watchCounter = 9;           //  Means "doing allocation"
    globalEmulatorData.theWatchDog->registerWatchedThread(&watchCounter, 0);
    if (init_global_memory_manager(globalEmulatorData, &watchCounter))
      ndbd_exit(1);
    globalEmulatorData.theWatchDog->unregisterWatchedThread(0);
  }

  globalEmulatorData.theThreadConfig->init();

#ifdef VM_TRACE
  // Create a signal logger before block constructors
  char *buf= NdbConfig_SignalLogFileName(globalData.ownId);
  NdbAutoPtr<char> tmp_aptr(buf);
  FILE * signalLog = fopen(buf, "a");
  globalSignalLoggers.setOwnNodeId(globalData.ownId);
  globalSignalLoggers.setOutputStream(signalLog);
#if 1 // to log startup
  { const char* p = NdbEnv_GetEnv("NDB_SIGNAL_LOG", (char*)0, 0);
    if (p != 0) {
      char buf[200];
      BaseString::snprintf(buf, sizeof(buf), "BLOCK=%s", p);
      for (char* q = buf; *q != 0; q++) *q = toupper(toascii(*q));
      globalSignalLoggers.log(SignalLoggerManager::LogInOut, buf);
      globalData.testOn = 1;
      assert(signalLog != 0);
      fprintf(signalLog, "START\n");
      fflush(signalLog);
    }
  }
#endif
#endif

  // Load blocks (both main and workers)
  globalEmulatorData.theSimBlockList->load(globalEmulatorData);

  // Set thread concurrency for Solaris' light weight processes
  int status;
  status = NdbThread_SetConcurrencyLevel(30);
  assert(status == 0);

  catchsigs(foreground);

  /**
   * Do startup
   */
  switch(globalData.theRestartFlag){
  case initial_state:
    globalEmulatorData.theThreadConfig->doStart(NodeState::SL_CMVMI);
    break;
  case perform_start:
    globalEmulatorData.theThreadConfig->doStart(NodeState::SL_CMVMI);
    globalEmulatorData.theThreadConfig->doStart(NodeState::SL_STARTING);
    break;
  default:
    assert("Illegal state globalData.theRestartFlag" == 0);
  }

  globalTransporterRegistry.startSending();
  globalTransporterRegistry.startReceiving();
  if (!globalTransporterRegistry.start_service(*globalEmulatorData.m_socket_server)){
    ndbout_c("globalTransporterRegistry.start_service() failed");
    ndbd_exit(-1);
  }

  // Re-use the mgm handle as a transporter
  if(!globalTransporterRegistry.connect_client(
		 theConfig->get_config_retriever()->get_mgmHandlePtr()))
      ERROR_SET(fatal, NDBD_EXIT_CONNECTION_SETUP_FAILED,
                "Failed to convert mgm connection to a transporter",
                __FILE__);

  NdbThread* pTrp = globalTransporterRegistry.start_clients();
  if (pTrp == 0)
  {
    ndbout_c("globalTransporterRegistry.start_clients() failed");
    ndbd_exit(-1);
  }

  NdbThread* pSockServ = globalEmulatorData.m_socket_server->startServer();

  globalEmulatorData.theConfiguration->addThread(pTrp, SocketClientThread);
  globalEmulatorData.theConfiguration->addThread(pWatchdog, WatchDogThread);
  globalEmulatorData.theConfiguration->addThread(pSockServ, SocketServerThread);

  //  theConfig->closeConfiguration();
  {
    NdbThread *pThis = NdbThread_CreateObject(0);
    Uint32 inx = globalEmulatorData.theConfiguration->addThread(pThis,
                                                                MainThread);
    globalEmulatorData.theThreadConfig->ipControlLoop(pThis, inx);
    globalEmulatorData.theConfiguration->removeThreadId(inx);
  }
  NdbShutdown(0, NST_Normal);

  ndbd_exit(0);
}
Exemplo n.º 4
0
static int mgmd_main(int argc, char** argv)
{
    NDB_INIT(argv[0]);

    printf("MySQL Cluster Management Server %s\n", NDB_VERSION_STRING);

    ndb_opt_set_usage_funcs(short_usage_sub, usage);

    load_defaults("my",load_default_groups,&argc,&argv);
    defaults_argv= argv; /* Must be freed by 'free_defaults' */

    int ho_error;
#ifndef DBUG_OFF
    opt_debug= IF_WIN("d:t:i:F:o,c:\\ndb_mgmd.trace",
                      "d:t:i:F:o,/tmp/ndb_mgmd.trace");
#endif

    if ((ho_error=handle_options(&argc, &argv, my_long_options,
                                 ndb_std_get_one_option)))
        mgmd_exit(ho_error);

    if (opts.interactive ||
            opts.non_interactive ||
            opts.print_full_config) {
        opts.daemon= 0;
    }

    if (opts.mycnf && opts.config_filename)
    {
        fprintf(stderr, "ERROR: Both --mycnf and -f is not supported\n");
        mgmd_exit(1);
    }

    if (opt_nowait_nodes)
    {
        int res = parse_mask(opt_nowait_nodes, opts.nowait_nodes);
        if(res == -2 || (res > 0 && opts.nowait_nodes.get(0)))
        {
            fprintf(stderr, "ERROR: Invalid nodeid specified in nowait-nodes: '%s'\n",
                    opt_nowait_nodes);
            mgmd_exit(1);
        }
        else if (res < 0)
        {
            fprintf(stderr, "ERROR: Unable to parse nowait-nodes argument: '%s'\n",
                    opt_nowait_nodes);
            mgmd_exit(1);
        }
    }

    /* Setup use of event logger */
    g_eventLogger->setCategory(opt_logname);

    /* Output to console initially */
    g_eventLogger->createConsoleHandler();

#ifdef _WIN32
    /* Output to Windows event log */
    g_eventLogger->createEventLogHandler("MySQL Cluster Management Server");
#endif

    if (opts.verbose)
        g_eventLogger->enable(Logger::LL_ALL); // --verbose turns on everything

    /**
       Install signal handler for SIGPIPE
       Done in TransporterFacade as well.. what about Configretriever?
     */
#if !defined NDB_WIN32
    signal(SIGPIPE, SIG_IGN);
#endif

    while (!g_StopServer)
    {
        mgm= new MgmtSrvr(opts);
        if (mgm == NULL) {
            g_eventLogger->critical("Out of memory, couldn't create MgmtSrvr");
            mgmd_exit(1);
        }

        /* Init mgm, load or fetch config */
        if (!mgm->init()) {
            delete mgm;
            mgmd_exit(1);
        }

        if (NdbDir::chdir(NdbConfig_get_path(NULL)) != 0)
        {
            g_eventLogger->warning("Cannot change directory to '%s', error: %d",
                                   NdbConfig_get_path(NULL), errno);
            // Ignore error
        }

        if (opts.daemon)
        {
            NodeId localNodeId= mgm->getOwnNodeId();
            if (localNodeId == 0) {
                g_eventLogger->error("Couldn't get own node id");
                delete mgm;
                mgmd_exit(1);
            }

            char *lockfile= NdbConfig_PidFileName(localNodeId);
            char *logfile=  NdbConfig_StdoutFileName(localNodeId);
            if (ndb_daemonize(lockfile, logfile))
            {
                g_eventLogger->error("Couldn't start as daemon, error: '%s'",
                                     ndb_daemon_error);
                mgmd_exit(1);
            }
        }

        /* Start mgm services */
        if (!mgm->start()) {
            delete mgm;
            mgmd_exit(1);
        }

        if (opts.interactive) {
            int port= mgm->getPort();
            BaseString con_str;
            if(opts.bind_address)
                con_str.appfmt("host=%s:%d", opts.bind_address, port);
            else
                con_str.appfmt("localhost:%d", port);
            Ndb_mgmclient com(con_str.c_str(), 1);
            while(!g_StopServer) {
                if (!read_and_execute(&com, "ndb_mgm> ", 1))
                    g_StopServer = true;
            }
        }
        else
        {
            g_eventLogger->info("MySQL Cluster Management Server %s started",
                                NDB_VERSION_STRING);

            while (!g_StopServer)
                NdbSleep_MilliSleep(500);
        }

        g_eventLogger->info("Shutting down server...");
        delete mgm;
        g_eventLogger->info("Shutdown complete");

        if(g_RestartServer) {
            g_eventLogger->info("Restarting server...");
            g_RestartServer= g_StopServer= false;
        }
    }

    mgmd_exit(0);
    return 0;
}