robust_emulation.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2010-2012. Distributed under the Boost
  4. // Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org/libs/interprocess for documentation.
  8. //
  9. //////////////////////////////////////////////////////////////////////////////
  10. #ifndef BOOST_INTERPROCESS_ROBUST_EMULATION_HPP
  11. #define BOOST_INTERPROCESS_ROBUST_EMULATION_HPP
  12. #ifndef BOOST_CONFIG_HPP
  13. # include <boost/config.hpp>
  14. #endif
  15. #
  16. #if defined(BOOST_HAS_PRAGMA_ONCE)
  17. #pragma once
  18. #endif
  19. #include <boost/interprocess/detail/config_begin.hpp>
  20. #include <boost/interprocess/detail/workaround.hpp>
  21. #include <boost/interprocess/sync/interprocess_mutex.hpp>
  22. #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
  23. #include <boost/interprocess/detail/atomic.hpp>
  24. #include <boost/interprocess/detail/os_file_functions.hpp>
  25. #include <boost/interprocess/detail/shared_dir_helpers.hpp>
  26. #include <boost/interprocess/detail/intermodule_singleton.hpp>
  27. #include <boost/interprocess/detail/portable_intermodule_singleton.hpp>
  28. #include <boost/interprocess/exceptions.hpp>
  29. #include <boost/interprocess/sync/spin/wait.hpp>
  30. #include <boost/interprocess/sync/detail/common_algorithms.hpp>
  31. #include <string>
  32. namespace boost{
  33. namespace interprocess{
  34. namespace ipcdetail{
  35. namespace robust_emulation_helpers {
  36. template<class T>
  37. class mutex_traits
  38. {
  39. public:
  40. static void take_ownership(T &t)
  41. { t.take_ownership(); }
  42. };
  43. inline void remove_if_can_lock_file(const char *file_path)
  44. {
  45. file_handle_t fhnd = open_existing_file(file_path, read_write);
  46. if(fhnd != invalid_file()){
  47. bool acquired;
  48. if(try_acquire_file_lock(fhnd, acquired) && acquired){
  49. delete_file(file_path);
  50. }
  51. close_file(fhnd);
  52. }
  53. }
  54. inline const char *robust_lock_subdir_path()
  55. { return "robust"; }
  56. inline const char *robust_lock_prefix()
  57. { return "lck"; }
  58. inline void robust_lock_path(std::string &s)
  59. {
  60. get_shared_dir(s);
  61. s += "/";
  62. s += robust_lock_subdir_path();
  63. }
  64. inline void create_and_get_robust_lock_file_path(std::string &s, OS_process_id_t pid)
  65. {
  66. intermodule_singleton_helpers::create_tmp_subdir_and_get_pid_based_filepath
  67. (robust_lock_subdir_path(), robust_lock_prefix(), pid, s);
  68. }
  69. //This class will be a intermodule_singleton. The constructor will create
  70. //a lock file, the destructor will erase it.
  71. //
  72. //We should take in care that another process might be erasing unlocked
  73. //files while creating this one, so there are some race conditions we must
  74. //take in care to guarantee some robustness.
  75. class robust_mutex_lock_file
  76. {
  77. file_handle_t fd;
  78. std::string fname;
  79. public:
  80. robust_mutex_lock_file()
  81. {
  82. permissions p;
  83. p.set_unrestricted();
  84. //Remove old lock files of other processes
  85. remove_old_robust_lock_files();
  86. //Create path and obtain lock file path for this process
  87. create_and_get_robust_lock_file_path(fname, get_current_process_id());
  88. //Now try to open or create the lock file
  89. fd = create_or_open_file(fname.c_str(), read_write, p);
  90. //If we can't open or create it, then something unrecoverable has happened
  91. if(fd == invalid_file()){
  92. throw interprocess_exception(other_error, "Robust emulation robust_mutex_lock_file constructor failed: could not open or create file");
  93. }
  94. //Now we must take in care a race condition with another process
  95. //calling "remove_old_robust_lock_files()". No other threads from this
  96. //process will be creating the lock file because intermodule_singleton
  97. //guarantees this. So let's loop acquiring the lock and checking if we
  98. //can't exclusively create the file (if the file is erased by another process
  99. //then this exclusive open would fail). If the file can't be exclusively created
  100. //then we have correctly open/create and lock the file. If the file can
  101. //be exclusively created, then close previous locked file and try again.
  102. while(1){
  103. bool acquired;
  104. if(!try_acquire_file_lock(fd, acquired) || !acquired ){
  105. throw interprocess_exception(other_error, "Robust emulation robust_mutex_lock_file constructor failed: try_acquire_file_lock");
  106. }
  107. //Creating exclusively must fail with already_exists_error
  108. //to make sure we've locked the file and no one has
  109. //deleted it between creation and locking
  110. file_handle_t fd2 = create_new_file(fname.c_str(), read_write, p);
  111. if(fd2 != invalid_file()){
  112. close_file(fd);
  113. fd = fd2;
  114. continue;
  115. }
  116. //If exclusive creation fails with expected error go ahead
  117. else if(error_info(system_error_code()).get_error_code() == already_exists_error){ //must already exist
  118. //Leak descriptor to mantain the file locked until the process dies
  119. break;
  120. }
  121. //If exclusive creation fails with unexpected error throw an unrecoverable error
  122. else{
  123. close_file(fd);
  124. throw interprocess_exception(other_error, "Robust emulation robust_mutex_lock_file constructor failed: create_file filed with unexpected error");
  125. }
  126. }
  127. }
  128. ~robust_mutex_lock_file()
  129. {
  130. //The destructor is guaranteed by intermodule_singleton to be
  131. //executed serialized between all threads from current process,
  132. //so we just need to close and unlink the file.
  133. close_file(fd);
  134. //If some other process deletes the file before us after
  135. //closing it there should not be any problem.
  136. delete_file(fname.c_str());
  137. }
  138. private:
  139. //This functor is execute for all files in the lock file directory
  140. class other_process_lock_remover
  141. {
  142. public:
  143. void operator()(const char *filepath, const char *filename)
  144. {
  145. std::string pid_str;
  146. //If the lock file is not our own lock file, then try to do the cleanup
  147. if(!intermodule_singleton_helpers::check_if_filename_complies_with_pid
  148. (filename, robust_lock_prefix(), get_current_process_id(), pid_str)){
  149. remove_if_can_lock_file(filepath);
  150. }
  151. }
  152. };
  153. bool remove_old_robust_lock_files()
  154. {
  155. std::string refcstrRootDirectory;
  156. robust_lock_path(refcstrRootDirectory);
  157. return for_each_file_in_dir(refcstrRootDirectory.c_str(), other_process_lock_remover());
  158. }
  159. };
  160. } //namespace robust_emulation_helpers {
  161. //This is the mutex class. Mutex should follow mutex concept
  162. //with an additonal "take_ownership()" function to take ownership of the
  163. //mutex when robust_spin_mutex determines the previous owner was dead.
  164. template<class Mutex>
  165. class robust_spin_mutex
  166. {
  167. public:
  168. static const boost::uint32_t correct_state = 0;
  169. static const boost::uint32_t fixing_state = 1;
  170. static const boost::uint32_t broken_state = 2;
  171. typedef robust_emulation_helpers::mutex_traits<Mutex> mutex_traits_t;
  172. robust_spin_mutex();
  173. void lock();
  174. bool try_lock();
  175. template<class TimePoint>
  176. bool timed_lock(const TimePoint &abs_time);
  177. void unlock();
  178. void consistent();
  179. bool previous_owner_dead();
  180. private:
  181. static const unsigned int spin_threshold = 100u;
  182. bool lock_own_unique_file();
  183. bool robust_check();
  184. bool check_if_owner_dead_and_take_ownership_atomically();
  185. bool is_owner_dead(boost::uint32_t own);
  186. void owner_to_filename(boost::uint32_t own, std::string &s);
  187. //The real mutex
  188. Mutex mtx;
  189. //The pid of the owner
  190. volatile boost::uint32_t owner;
  191. //The state of the mutex (correct, fixing, broken)
  192. volatile boost::uint32_t state;
  193. };
  194. template<class Mutex>
  195. inline robust_spin_mutex<Mutex>::robust_spin_mutex()
  196. : mtx(), owner((boost::uint32_t)get_invalid_process_id()), state(correct_state)
  197. {}
  198. template<class Mutex>
  199. inline void robust_spin_mutex<Mutex>::lock()
  200. { try_based_lock(*this); }
  201. template<class Mutex>
  202. inline bool robust_spin_mutex<Mutex>::try_lock()
  203. {
  204. //Same as lock() but without spinning
  205. if(atomic_read32(&this->state) == broken_state){
  206. throw interprocess_exception(lock_error, "Broken id");
  207. }
  208. if(!this->lock_own_unique_file()){
  209. throw interprocess_exception(lock_error, "Broken id");
  210. }
  211. if (mtx.try_lock()){
  212. atomic_write32(&this->owner, static_cast<boost::uint32_t>(get_current_process_id()));
  213. return true;
  214. }
  215. else{
  216. if(!this->robust_check()){
  217. return false;
  218. }
  219. else{
  220. return true;
  221. }
  222. }
  223. }
  224. template<class Mutex>
  225. template<class TimePoint>
  226. inline bool robust_spin_mutex<Mutex>::timed_lock
  227. (const TimePoint &abs_time)
  228. { return try_based_timed_lock(*this, abs_time); }
  229. template<class Mutex>
  230. inline void robust_spin_mutex<Mutex>::owner_to_filename(boost::uint32_t own, std::string &s)
  231. {
  232. robust_emulation_helpers::create_and_get_robust_lock_file_path(s, (OS_process_id_t)own);
  233. }
  234. template<class Mutex>
  235. inline bool robust_spin_mutex<Mutex>::robust_check()
  236. {
  237. //If the old owner was dead, and we've acquired ownership, mark
  238. //the mutex as 'fixing'. This means that a "consistent()" is needed
  239. //to avoid marking the mutex as "broken" when the mutex is unlocked.
  240. if(!this->check_if_owner_dead_and_take_ownership_atomically()){
  241. return false;
  242. }
  243. atomic_write32(&this->state, fixing_state);
  244. return true;
  245. }
  246. template<class Mutex>
  247. inline bool robust_spin_mutex<Mutex>::check_if_owner_dead_and_take_ownership_atomically()
  248. {
  249. boost::uint32_t cur_owner = static_cast<boost::uint32_t>(get_current_process_id());
  250. boost::uint32_t old_owner = atomic_read32(&this->owner), old_owner2;
  251. //The cas loop guarantees that only one thread from this or another process
  252. //will succeed taking ownership
  253. do{
  254. //Check if owner is dead
  255. if(!this->is_owner_dead(old_owner)){
  256. return false;
  257. }
  258. //If it's dead, try to mark this process as the owner in the owner field
  259. old_owner2 = old_owner;
  260. old_owner = atomic_cas32(&this->owner, cur_owner, old_owner);
  261. }while(old_owner2 != old_owner);
  262. //If success, we fix mutex internals to assure our ownership
  263. mutex_traits_t::take_ownership(mtx);
  264. return true;
  265. }
  266. template<class Mutex>
  267. inline bool robust_spin_mutex<Mutex>::is_owner_dead(boost::uint32_t own)
  268. {
  269. //If owner is an invalid id, then it's clear it's dead
  270. if(own == static_cast<boost::uint32_t>(get_invalid_process_id())){
  271. return true;
  272. }
  273. //Obtain the lock filename of the owner field
  274. std::string file;
  275. this->owner_to_filename(own, file);
  276. //Now the logic is to open and lock it
  277. file_handle_t fhnd = open_existing_file(file.c_str(), read_write);
  278. if(fhnd != invalid_file()){
  279. //If we can open the file, lock it.
  280. bool acquired;
  281. if(try_acquire_file_lock(fhnd, acquired) && acquired){
  282. //If locked, just delete the file
  283. delete_file(file.c_str());
  284. close_file(fhnd);
  285. return true;
  286. }
  287. //If not locked, the owner is suppossed to be still alive
  288. close_file(fhnd);
  289. }
  290. else{
  291. //If the lock file does not exist then the owner is dead (a previous cleanup)
  292. //function has deleted the file. If there is another reason, then this is
  293. //an unrecoverable error
  294. if(error_info(system_error_code()).get_error_code() == not_found_error){
  295. return true;
  296. }
  297. }
  298. return false;
  299. }
  300. template<class Mutex>
  301. inline void robust_spin_mutex<Mutex>::consistent()
  302. {
  303. //This function supposes the previous state was "fixing"
  304. //and the current process holds the mutex
  305. if(atomic_read32(&this->state) != fixing_state &&
  306. atomic_read32(&this->owner) != (boost::uint32_t)get_current_process_id()){
  307. throw interprocess_exception(lock_error, "Broken id");
  308. }
  309. //If that's the case, just update mutex state
  310. atomic_write32(&this->state, correct_state);
  311. }
  312. template<class Mutex>
  313. inline bool robust_spin_mutex<Mutex>::previous_owner_dead()
  314. {
  315. //Notifies if a owner recovery has been performed in the last lock()
  316. return atomic_read32(&this->state) == fixing_state;
  317. }
  318. template<class Mutex>
  319. inline void robust_spin_mutex<Mutex>::unlock()
  320. {
  321. //If in "fixing" state, unlock and mark the mutex as unrecoverable
  322. //so next locks will fail and all threads will be notified that the
  323. //data protected by the mutex was not recoverable.
  324. if(atomic_read32(&this->state) == fixing_state){
  325. atomic_write32(&this->state, broken_state);
  326. }
  327. //Write an invalid owner to minimize pid reuse possibility
  328. atomic_write32(&this->owner, static_cast<boost::uint32_t>(get_invalid_process_id()));
  329. mtx.unlock();
  330. }
  331. template<class Mutex>
  332. inline bool robust_spin_mutex<Mutex>::lock_own_unique_file()
  333. {
  334. //This function forces instantiation of the singleton
  335. robust_emulation_helpers::robust_mutex_lock_file* dummy =
  336. &ipcdetail::intermodule_singleton
  337. <robust_emulation_helpers::robust_mutex_lock_file>::get();
  338. return dummy != 0;
  339. }
  340. } //namespace ipcdetail{
  341. } //namespace interprocess{
  342. } //namespace boost{
  343. #include <boost/interprocess/detail/config_end.hpp>
  344. #endif