robust_emulation.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. bool timed_lock(const boost::posix_time::ptime &abs_time);
  176. void unlock();
  177. void consistent();
  178. bool previous_owner_dead();
  179. private:
  180. static const unsigned int spin_threshold = 100u;
  181. bool lock_own_unique_file();
  182. bool robust_check();
  183. bool check_if_owner_dead_and_take_ownership_atomically();
  184. bool is_owner_dead(boost::uint32_t own);
  185. void owner_to_filename(boost::uint32_t own, std::string &s);
  186. //The real mutex
  187. Mutex mtx;
  188. //The pid of the owner
  189. volatile boost::uint32_t owner;
  190. //The state of the mutex (correct, fixing, broken)
  191. volatile boost::uint32_t state;
  192. };
  193. template<class Mutex>
  194. inline robust_spin_mutex<Mutex>::robust_spin_mutex()
  195. : mtx(), owner(get_invalid_process_id()), state(correct_state)
  196. {}
  197. template<class Mutex>
  198. inline void robust_spin_mutex<Mutex>::lock()
  199. { try_based_lock(*this); }
  200. template<class Mutex>
  201. inline bool robust_spin_mutex<Mutex>::try_lock()
  202. {
  203. //Same as lock() but without spinning
  204. if(atomic_read32(&this->state) == broken_state){
  205. throw interprocess_exception(lock_error, "Broken id");
  206. }
  207. if(!this->lock_own_unique_file()){
  208. throw interprocess_exception(lock_error, "Broken id");
  209. }
  210. if (mtx.try_lock()){
  211. atomic_write32(&this->owner, get_current_process_id());
  212. return true;
  213. }
  214. else{
  215. if(!this->robust_check()){
  216. return false;
  217. }
  218. else{
  219. return true;
  220. }
  221. }
  222. }
  223. template<class Mutex>
  224. inline bool robust_spin_mutex<Mutex>::timed_lock
  225. (const boost::posix_time::ptime &abs_time)
  226. { return try_based_timed_lock(*this, abs_time); }
  227. template<class Mutex>
  228. inline void robust_spin_mutex<Mutex>::owner_to_filename(boost::uint32_t own, std::string &s)
  229. {
  230. robust_emulation_helpers::create_and_get_robust_lock_file_path(s, own);
  231. }
  232. template<class Mutex>
  233. inline bool robust_spin_mutex<Mutex>::robust_check()
  234. {
  235. //If the old owner was dead, and we've acquired ownership, mark
  236. //the mutex as 'fixing'. This means that a "consistent()" is needed
  237. //to avoid marking the mutex as "broken" when the mutex is unlocked.
  238. if(!this->check_if_owner_dead_and_take_ownership_atomically()){
  239. return false;
  240. }
  241. atomic_write32(&this->state, fixing_state);
  242. return true;
  243. }
  244. template<class Mutex>
  245. inline bool robust_spin_mutex<Mutex>::check_if_owner_dead_and_take_ownership_atomically()
  246. {
  247. boost::uint32_t cur_owner = get_current_process_id();
  248. boost::uint32_t old_owner = atomic_read32(&this->owner), old_owner2;
  249. //The cas loop guarantees that only one thread from this or another process
  250. //will succeed taking ownership
  251. do{
  252. //Check if owner is dead
  253. if(!this->is_owner_dead(old_owner)){
  254. return false;
  255. }
  256. //If it's dead, try to mark this process as the owner in the owner field
  257. old_owner2 = old_owner;
  258. old_owner = atomic_cas32(&this->owner, cur_owner, old_owner);
  259. }while(old_owner2 != old_owner);
  260. //If success, we fix mutex internals to assure our ownership
  261. mutex_traits_t::take_ownership(mtx);
  262. return true;
  263. }
  264. template<class Mutex>
  265. inline bool robust_spin_mutex<Mutex>::is_owner_dead(boost::uint32_t own)
  266. {
  267. //If owner is an invalid id, then it's clear it's dead
  268. if(own == (boost::uint32_t)get_invalid_process_id()){
  269. return true;
  270. }
  271. //Obtain the lock filename of the owner field
  272. std::string file;
  273. this->owner_to_filename(own, file);
  274. //Now the logic is to open and lock it
  275. file_handle_t fhnd = open_existing_file(file.c_str(), read_write);
  276. if(fhnd != invalid_file()){
  277. //If we can open the file, lock it.
  278. bool acquired;
  279. if(try_acquire_file_lock(fhnd, acquired) && acquired){
  280. //If locked, just delete the file
  281. delete_file(file.c_str());
  282. close_file(fhnd);
  283. return true;
  284. }
  285. //If not locked, the owner is suppossed to be still alive
  286. close_file(fhnd);
  287. }
  288. else{
  289. //If the lock file does not exist then the owner is dead (a previous cleanup)
  290. //function has deleted the file. If there is another reason, then this is
  291. //an unrecoverable error
  292. if(error_info(system_error_code()).get_error_code() == not_found_error){
  293. return true;
  294. }
  295. }
  296. return false;
  297. }
  298. template<class Mutex>
  299. inline void robust_spin_mutex<Mutex>::consistent()
  300. {
  301. //This function supposes the previous state was "fixing"
  302. //and the current process holds the mutex
  303. if(atomic_read32(&this->state) != fixing_state &&
  304. atomic_read32(&this->owner) != (boost::uint32_t)get_current_process_id()){
  305. throw interprocess_exception(lock_error, "Broken id");
  306. }
  307. //If that's the case, just update mutex state
  308. atomic_write32(&this->state, correct_state);
  309. }
  310. template<class Mutex>
  311. inline bool robust_spin_mutex<Mutex>::previous_owner_dead()
  312. {
  313. //Notifies if a owner recovery has been performed in the last lock()
  314. return atomic_read32(&this->state) == fixing_state;
  315. }
  316. template<class Mutex>
  317. inline void robust_spin_mutex<Mutex>::unlock()
  318. {
  319. //If in "fixing" state, unlock and mark the mutex as unrecoverable
  320. //so next locks will fail and all threads will be notified that the
  321. //data protected by the mutex was not recoverable.
  322. if(atomic_read32(&this->state) == fixing_state){
  323. atomic_write32(&this->state, broken_state);
  324. }
  325. //Write an invalid owner to minimize pid reuse possibility
  326. atomic_write32(&this->owner, get_invalid_process_id());
  327. mtx.unlock();
  328. }
  329. template<class Mutex>
  330. inline bool robust_spin_mutex<Mutex>::lock_own_unique_file()
  331. {
  332. //This function forces instantiation of the singleton
  333. robust_emulation_helpers::robust_mutex_lock_file* dummy =
  334. &ipcdetail::intermodule_singleton
  335. <robust_emulation_helpers::robust_mutex_lock_file>::get();
  336. return dummy != 0;
  337. }
  338. } //namespace ipcdetail{
  339. } //namespace interprocess{
  340. } //namespace boost{
  341. #include <boost/interprocess/detail/config_end.hpp>
  342. #endif