TransientDirectory.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file TransientDirectory.cpp
  15. * @author Marek Kotewicz <marek@ethdev.com>
  16. * @date 2015
  17. */
  18. #include <thread>
  19. #include <boost/filesystem.hpp>
  20. #include "Exceptions.h"
  21. #include "TransientDirectory.h"
  22. #include "CommonIO.h"
  23. #include "Log.h"
  24. using namespace std;
  25. using namespace dev;
  26. namespace fs = boost::filesystem;
  27. TransientDirectory::TransientDirectory():
  28. TransientDirectory((boost::filesystem::temp_directory_path() / "eth_transient" / toString(FixedHash<4>::random())).string())
  29. {}
  30. TransientDirectory::TransientDirectory(std::string const& _path):
  31. m_path(_path)
  32. {
  33. // we never ever want to delete a directory (including all its contents) that we did not create ourselves.
  34. if (boost::filesystem::exists(m_path))
  35. BOOST_THROW_EXCEPTION(FileError());
  36. if (!fs::create_directories(m_path))
  37. BOOST_THROW_EXCEPTION(FileError());
  38. DEV_IGNORE_EXCEPTIONS(fs::permissions(m_path, fs::owner_all));
  39. }
  40. TransientDirectory::~TransientDirectory()
  41. {
  42. boost::system::error_code ec;
  43. fs::remove_all(m_path, ec);
  44. if (!ec)
  45. return;
  46. // In some cases, antivirus runnig on Windows will scan all the newly created directories.
  47. // As a consequence, directory is locked and can not be deleted immediately.
  48. // Retry after 10 milliseconds usually is successful.
  49. // This will help our tests run smoothly in such environment.
  50. this_thread::sleep_for(chrono::milliseconds(10));
  51. ec.clear();
  52. fs::remove_all(m_path, ec);
  53. if (!ec)
  54. {
  55. cwarn << "Failed to delete directory '" << m_path << "': " << ec.message();
  56. }
  57. }