コード例 #1
0
ファイル: LibraryManager.cpp プロジェクト: dezed/mantid
/** Opens all suitable DLLs on a given path.
*  @param filePath :: The filepath to the directory where the libraries are.
*  @param isRecursive :: Whether to search subdirectories.
*  @return The number of libraries opened.
*/
int LibraryManagerImpl::OpenAllLibraries(const std::string &filePath,
                                         bool isRecursive) {
  g_log.debug() << "Opening all libraries in " << filePath << "\n";
  int libCount = 0;
  // validate inputs
  Poco::File libPath;
  try {
    libPath = Poco::File(filePath);
  } catch (...) {
    return libCount;
  }
  if (libPath.exists() && libPath.isDirectory()) {
    DllOpen::addSearchDirectory(filePath);
    // Iteratate over the available files
    Poco::DirectoryIterator end_itr;
    for (Poco::DirectoryIterator itr(libPath); itr != end_itr; ++itr) {
      const Poco::Path &item = itr.path();
      if (item.isDirectory()) {
        if (isRecursive) {
          libCount += OpenAllLibraries(item.toString());
        }
      } else {
        if (skip(item.toString()))
          continue;
        if (loadLibrary(item.toString())) {
          ++libCount;
        }
      }
    }
  } else {
    g_log.error("In OpenAllLibraries: " + filePath + " must be a directory.");
  }

  return libCount;
}
コード例 #2
0
ファイル: statsutil.cpp プロジェクト: SeredithM/ppmdu
    int CStatsUtil::DoExportGameScripts()
    {
        //Validate output + input paths
        Poco::Path inpath(m_inputPath);
        Poco::Path outpath;
        
        if( m_outputPath.empty() )
            outpath = inpath.absolute().makeParent().append(DefExportScriptsDir);
        else
            outpath = Poco::Path(m_outputPath).makeAbsolute();

        Poco::File fTestOut = outpath;
        if( ! fTestOut.exists() )
        {
            cout << "Created output directory \"" << fTestOut.path() <<"\"!\n";
            fTestOut.createDirectory();
        }
        else if( ! fTestOut.isDirectory() )
            throw runtime_error("CStatsUtil::DoExportGameScripts(): Output path is not a directory!");

        //Setup the script handler
        GameScripts scripts( inpath.absolute().toString() );

        //Convert to XML
        scripts.ExportScriptsToXML( outpath.toString() );

        return 0;
    }
コード例 #3
0
// ---
bool VSWAEImportContentWindow::validateDir (const QString& d)
{
	bool result = false;

	// Calculates the paths for everything: the basic dir, the definition file...
	// ...and the basic path received as parameter during the initialization.
	Poco::Path defPath;
	Poco::File defFile;
	Poco::File defDir (d.toStdString ());
	Poco::Path bPath (_basicPath.toStdString ());
	bool isDefDirADir = defDir.isDirectory (); // The directory has to be a dir (this is guarantte by the window, but just in case)
	if (isDefDirADir) 
	{
		defPath = Poco::Path (d.toStdString ());
		defFile = Poco::File ((d + QString (__PATH_SEPARATOR__) + 
			_name -> text () + QString (".xml")).toStdString ());
	}

	// If the directory is a directory, then it is needed to test whether the
	// directory is or not contained in the basic path received as parameter.
	bool isDefDirInBPath = false;
	if (isDefDirADir)
		isDefDirInBPath = ((defPath.toString () + std::string (__PATH_SEPARATOR__)).
			find (bPath.toString () + std::string (__PATH_SEPARATOR__)) != -1);

	// To determinate whether the dir is or not valid...
	result = !isDefDirADir || (isDefDirADir && isDefDirInBPath);

	return (result);
}
コード例 #4
0
ファイル: LibraryManager.cpp プロジェクト: DanNixon/mantid
/**
 * Opens suitable DLLs on a given path.
 *  @param libpath A Poco::File object pointing to a directory where the
 * libraries are.
 *  @param loadingBehaviour Control how libraries are searched for
 *  @param excludes If not empty then each string is considered as a substring
 * to search within each library to be opened. If the substring is found then
 * the library is not opened.
 *  @return The number of libraries opened.
 */
int LibraryManagerImpl::openLibraries(
    const Poco::File &libpath,
    LibraryManagerImpl::LoadLibraries loadingBehaviour,
    const std::vector<std::string> &excludes) {
  int libCount(0);
  if (libpath.exists() && libpath.isDirectory()) {
    // Iterate over the available files
    Poco::DirectoryIterator end_itr;
    for (Poco::DirectoryIterator itr(libpath); itr != end_itr; ++itr) {
      const Poco::File &item = *itr;
      if (item.isFile()) {
        if (shouldBeLoaded(itr.path().getFileName(), excludes))
          libCount += openLibrary(itr.path(), itr.path().getFileName());
        else
          continue;
      } else if (loadingBehaviour == LoadLibraries::Recursive) {
        // it must be a directory
        libCount += openLibraries(item, LoadLibraries::Recursive, excludes);
      }
    }
  } else {
    g_log.error("In OpenAllLibraries: " + libpath.path() +
                " must be a directory.");
  }
  return libCount;
}
コード例 #5
0
bool TraverseBase::isDirectory(Poco::File& file)
{
	try
	{
		return file.isDirectory();
	}
	catch (...)
	{
		return false;
	}
}
コード例 #6
0
 void unlink_directory()
 {
     if ( directory.exists() && directory.isDirectory() )
     {
         try
         {
             directory.remove(true);
         }
         catch(Poco::Exception &e)
         {
             std::cout << e.displayText() << std::endl;
         }
     }
 }
コード例 #7
0
ファイル: host.cpp プロジェクト: jonnymind/kroll
	void Host::FindBasicModules(std::string& dir)
	{
		ScopedLock lock(&moduleMutex);

		Poco::DirectoryIterator iter = Poco::DirectoryIterator(dir);
		Poco::DirectoryIterator end;
		while (iter != end)
		{
			Poco::File f = *iter;
			if (!f.isDirectory() && !f.isHidden())
			{
				std::string fpath = iter.path().absolute().toString();
				if (IsModule(fpath))
				{
					this->LoadModule(fpath, this);
				}
				else
				{
					this->AddInvalidModuleFile(fpath);
				}
			}
			iter++;
		}
	}
コード例 #8
0
ファイル: BaseDaemon.cpp プロジェクト: jacktang/ClickHouse
void BaseDaemon::initialize(Application& self)
{
	task_manager.reset(new Poco::TaskManager);
	ServerApplication::initialize(self);

	bool is_daemon = config().getBool("application.runAsDaemon", false);

	if (is_daemon)
	{
		/** При создании pid файла и поиске конфигурации, будем интерпретировать относительные пути
		  * от директории запуска программы.
		  */
		std::string path = Poco::Path(config().getString("application.path")).setFileName("").toString();
		if (0 != chdir(path.c_str()))
			throw Poco::Exception("Cannot change directory to " + path);
	}

	/// Считаем конфигурацию
	reloadConfiguration();

	/// В случае падения - сохраняем коры
	{
		struct rlimit rlim;
		if (getrlimit(RLIMIT_CORE, &rlim))
			throw Poco::Exception("Cannot getrlimit");
		/// 1 GiB. Если больше - они слишком долго пишутся на диск.
		rlim.rlim_cur = config().getUInt64("core_dump.size_limit", 1024 * 1024 * 1024);

		if (setrlimit(RLIMIT_CORE, &rlim))
		{
			std::string message = "Cannot set max size of core file to " + std::to_string(rlim.rlim_cur);
		#if !defined(ADDRESS_SANITIZER) && !defined(THREAD_SANITIZER)
			throw Poco::Exception(message);
		#else
			/// Не работает под address/thread sanitizer. http://lists.llvm.org/pipermail/llvm-bugs/2013-April/027880.html
			std::cerr << message << std::endl;
		#endif
		}
	}

	/// This must be done before any usage of DateLUT. In particular, before any logging.
	if (config().has("timezone"))
	{
		if (0 != setenv("TZ", config().getString("timezone").data(), 1))
			throw Poco::Exception("Cannot setenv TZ variable");

		tzset();
	}

	std::string log_path = config().getString("logger.log", "");
	if (!log_path.empty())
		log_path = Poco::Path(log_path).setFileName("").toString();

	if (is_daemon)
	{
		/** Переназначим stdout, stderr в отдельные файлы в директориях с логами.
		  * Некоторые библиотеки пишут в stderr в случае ошибок или в отладочном режиме,
		  *  и этот вывод иногда имеет смысл смотреть даже когда программа запущена в режиме демона.
		  * Делаем это до buildLoggers, чтобы ошибки во время инициализации логгера, попали в эти файлы.
		  */
		if (!log_path.empty())
		{
			std::string stdout_path = log_path + "/stdout";
			if (!freopen(stdout_path.c_str(), "a+", stdout))
				throw Poco::OpenFileException("Cannot attach stdout to " + stdout_path);

			std::string stderr_path = log_path + "/stderr";
			if (!freopen(stderr_path.c_str(), "a+", stderr))
				throw Poco::OpenFileException("Cannot attach stderr to " + stderr_path);
		}

		/// Создадим pid-file.
		if (is_daemon && config().has("pid"))
			pid.seed(config().getString("pid"));
	}

	buildLoggers();

	if (is_daemon)
	{
		/** Сменим директорию на ту, куда надо писать core файлы.
		  * Делаем это после buildLoggers, чтобы не менять текущую директорию раньше.
		  * Это важно, если конфиги расположены в текущей директории.
		  */

		std::string core_path = config().getString("core_path", "");
		if (core_path.empty())
			core_path = getDefaultCorePath();

		tryCreateDirectories(&logger(), core_path);

		Poco::File cores = core_path;
		if (!(cores.exists() && cores.isDirectory()))
		{
			core_path = !log_path.empty() ? log_path : "/opt/";
			tryCreateDirectories(&logger(), core_path);
		}

		if (0 != chdir(core_path.c_str()))
			throw Poco::Exception("Cannot change directory to " + core_path);
	}

	/// Ставим terminate_handler
	std::set_terminate(terminate_handler);

	/// Ставим обработчики сигналов
	auto add_signal_handler =
		[](const std::vector<int> & signals, signal_function handler)
		{
			struct sigaction sa;
			memset(&sa, 0, sizeof(sa));
			sa.sa_sigaction = handler;
			sa.sa_flags = SA_SIGINFO;

			{
				if (sigemptyset(&sa.sa_mask))
					throw Poco::Exception("Cannot set signal handler.");

				for (auto signal : signals)
					if (sigaddset(&sa.sa_mask, signal))
						throw Poco::Exception("Cannot set signal handler.");

				for (auto signal : signals)
					if (sigaction(signal, &sa, 0))
						throw Poco::Exception("Cannot set signal handler.");
			}
		};

	add_signal_handler({SIGABRT, SIGSEGV, SIGILL, SIGBUS, SIGSYS, SIGFPE, SIGPIPE}, faultSignalHandler);
	add_signal_handler({SIGHUP, SIGUSR1}, closeLogsSignalHandler);
	add_signal_handler({SIGINT, SIGQUIT, SIGTERM}, terminateRequestedSignalHandler);

	/// Ставим ErrorHandler для потоков
	static KillingErrorHandler killing_error_handler;
	Poco::ErrorHandler::set(&killing_error_handler);

	/// Выведем ревизию демона
	logRevision();

	signal_listener.reset(new SignalListener(*this));
	signal_listener_thread.start(*signal_listener);

	graphite_writer.reset(new GraphiteWriter("graphite"));
}