1 //////////////////////////////////////////////////////////////////////////////
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)
7 // See http://www.boost.org/libs/interprocess for documentation.
9 //////////////////////////////////////////////////////////////////////////////
11 #ifndef BOOST_INTERPROCESS_ROBUST_EMULATION_HPP
12 #define BOOST_INTERPROCESS_ROBUST_EMULATION_HPP
14 #ifndef BOOST_CONFIG_HPP
15 # include <boost/config.hpp>
18 #if defined(BOOST_HAS_PRAGMA_ONCE)
22 #include <boost/interprocess/detail/config_begin.hpp>
23 #include <boost/interprocess/detail/workaround.hpp>
24 #include <boost/interprocess/sync/interprocess_mutex.hpp>
25 #include <boost/interprocess/sync/interprocess_recursive_mutex.hpp>
26 #include <boost/interprocess/detail/atomic.hpp>
27 #include <boost/interprocess/detail/os_file_functions.hpp>
28 #include <boost/interprocess/detail/shared_dir_helpers.hpp>
29 #include <boost/interprocess/detail/intermodule_singleton.hpp>
30 #include <boost/interprocess/detail/portable_intermodule_singleton.hpp>
31 #include <boost/interprocess/exceptions.hpp>
32 #include <boost/interprocess/sync/spin/wait.hpp>
33 #include <boost/interprocess/sync/detail/common_algorithms.hpp>
37 namespace interprocess{
40 namespace robust_emulation_helpers {
46 static void take_ownership(T &t)
47 { t.take_ownership(); }
50 inline void remove_if_can_lock_file(const char *file_path)
52 file_handle_t fhnd = open_existing_file(file_path, read_write);
54 if(fhnd != invalid_file()){
56 if(try_acquire_file_lock(fhnd, acquired) && acquired){
57 delete_file(file_path);
63 inline const char *robust_lock_subdir_path()
66 inline const char *robust_lock_prefix()
69 inline void robust_lock_path(std::string &s)
73 s += robust_lock_subdir_path();
76 inline void create_and_get_robust_lock_file_path(std::string &s, OS_process_id_t pid)
78 intermodule_singleton_helpers::create_tmp_subdir_and_get_pid_based_filepath
79 (robust_lock_subdir_path(), robust_lock_prefix(), pid, s);
82 //This class will be a intermodule_singleton. The constructor will create
83 //a lock file, the destructor will erase it.
85 //We should take in care that another process might be erasing unlocked
86 //files while creating this one, so there are some race conditions we must
87 //take in care to guarantee some robustness.
88 class robust_mutex_lock_file
93 robust_mutex_lock_file()
97 //Remove old lock files of other processes
98 remove_old_robust_lock_files();
99 //Create path and obtain lock file path for this process
100 create_and_get_robust_lock_file_path(fname, get_current_process_id());
102 //Now try to open or create the lock file
103 fd = create_or_open_file(fname.c_str(), read_write, p);
104 //If we can't open or create it, then something unrecoverable has happened
105 if(fd == invalid_file()){
106 throw interprocess_exception(other_error, "Robust emulation robust_mutex_lock_file constructor failed: could not open or create file");
109 //Now we must take in care a race condition with another process
110 //calling "remove_old_robust_lock_files()". No other threads from this
111 //process will be creating the lock file because intermodule_singleton
112 //guarantees this. So let's loop acquiring the lock and checking if we
113 //can't exclusively create the file (if the file is erased by another process
114 //then this exclusive open would fail). If the file can't be exclusively created
115 //then we have correctly open/create and lock the file. If the file can
116 //be exclusively created, then close previous locked file and try again.
119 if(!try_acquire_file_lock(fd, acquired) || !acquired ){
120 throw interprocess_exception(other_error, "Robust emulation robust_mutex_lock_file constructor failed: try_acquire_file_lock");
122 //Creating exclusively must fail with already_exists_error
123 //to make sure we've locked the file and no one has
124 //deleted it between creation and locking
125 file_handle_t fd2 = create_new_file(fname.c_str(), read_write, p);
126 if(fd2 != invalid_file()){
131 //If exclusive creation fails with expected error go ahead
132 else if(error_info(system_error_code()).get_error_code() == already_exists_error){ //must already exist
133 //Leak descriptor to mantain the file locked until the process dies
136 //If exclusive creation fails with unexpected error throw an unrecoverable error
139 throw interprocess_exception(other_error, "Robust emulation robust_mutex_lock_file constructor failed: create_file filed with unexpected error");
144 ~robust_mutex_lock_file()
146 //The destructor is guaranteed by intermodule_singleton to be
147 //executed serialized between all threads from current process,
148 //so we just need to close and unlink the file.
150 //If some other process deletes the file before us after
151 //closing it there should not be any problem.
152 delete_file(fname.c_str());
156 //This functor is execute for all files in the lock file directory
157 class other_process_lock_remover
160 void operator()(const char *filepath, const char *filename)
163 //If the lock file is not our own lock file, then try to do the cleanup
164 if(!intermodule_singleton_helpers::check_if_filename_complies_with_pid
165 (filename, robust_lock_prefix(), get_current_process_id(), pid_str)){
166 remove_if_can_lock_file(filepath);
171 bool remove_old_robust_lock_files()
173 std::string refcstrRootDirectory;
174 robust_lock_path(refcstrRootDirectory);
175 return for_each_file_in_dir(refcstrRootDirectory.c_str(), other_process_lock_remover());
179 } //namespace robust_emulation_helpers {
181 //This is the mutex class. Mutex should follow mutex concept
182 //with an additonal "take_ownership()" function to take ownership of the
183 //mutex when robust_spin_mutex determines the previous owner was dead.
184 template<class Mutex>
185 class robust_spin_mutex
188 static const boost::uint32_t correct_state = 0;
189 static const boost::uint32_t fixing_state = 1;
190 static const boost::uint32_t broken_state = 2;
192 typedef robust_emulation_helpers::mutex_traits<Mutex> mutex_traits_t;
197 bool timed_lock(const boost::posix_time::ptime &abs_time);
200 bool previous_owner_dead();
203 static const unsigned int spin_threshold = 100u;
204 bool lock_own_unique_file();
206 bool check_if_owner_dead_and_take_ownership_atomically();
207 bool is_owner_dead(boost::uint32_t own);
208 void owner_to_filename(boost::uint32_t own, std::string &s);
211 //The pid of the owner
212 volatile boost::uint32_t owner;
213 //The state of the mutex (correct, fixing, broken)
214 volatile boost::uint32_t state;
217 template<class Mutex>
218 inline robust_spin_mutex<Mutex>::robust_spin_mutex()
219 : mtx(), owner(get_invalid_process_id()), state(correct_state)
222 template<class Mutex>
223 inline void robust_spin_mutex<Mutex>::lock()
224 { try_based_lock(*this); }
226 template<class Mutex>
227 inline bool robust_spin_mutex<Mutex>::try_lock()
229 //Same as lock() but without spinning
230 if(atomic_read32(&this->state) == broken_state){
231 throw interprocess_exception(lock_error, "Broken id");
234 if(!this->lock_own_unique_file()){
235 throw interprocess_exception(lock_error, "Broken id");
239 atomic_write32(&this->owner, get_current_process_id());
243 if(!this->robust_check()){
252 template<class Mutex>
253 inline bool robust_spin_mutex<Mutex>::timed_lock
254 (const boost::posix_time::ptime &abs_time)
255 { return try_based_timed_lock(*this, abs_time); }
257 template<class Mutex>
258 inline void robust_spin_mutex<Mutex>::owner_to_filename(boost::uint32_t own, std::string &s)
260 robust_emulation_helpers::create_and_get_robust_lock_file_path(s, own);
263 template<class Mutex>
264 inline bool robust_spin_mutex<Mutex>::robust_check()
266 //If the old owner was dead, and we've acquired ownership, mark
267 //the mutex as 'fixing'. This means that a "consistent()" is needed
268 //to avoid marking the mutex as "broken" when the mutex is unlocked.
269 if(!this->check_if_owner_dead_and_take_ownership_atomically()){
272 atomic_write32(&this->state, fixing_state);
276 template<class Mutex>
277 inline bool robust_spin_mutex<Mutex>::check_if_owner_dead_and_take_ownership_atomically()
279 boost::uint32_t cur_owner = get_current_process_id();
280 boost::uint32_t old_owner = atomic_read32(&this->owner), old_owner2;
281 //The cas loop guarantees that only one thread from this or another process
282 //will succeed taking ownership
284 //Check if owner is dead
285 if(!this->is_owner_dead(old_owner)){
288 //If it's dead, try to mark this process as the owner in the owner field
289 old_owner2 = old_owner;
290 old_owner = atomic_cas32(&this->owner, cur_owner, old_owner);
291 }while(old_owner2 != old_owner);
292 //If success, we fix mutex internals to assure our ownership
293 mutex_traits_t::take_ownership(mtx);
297 template<class Mutex>
298 inline bool robust_spin_mutex<Mutex>::is_owner_dead(boost::uint32_t own)
300 //If owner is an invalid id, then it's clear it's dead
301 if(own == (boost::uint32_t)get_invalid_process_id()){
305 //Obtain the lock filename of the owner field
307 this->owner_to_filename(own, file);
309 //Now the logic is to open and lock it
310 file_handle_t fhnd = open_existing_file(file.c_str(), read_write);
312 if(fhnd != invalid_file()){
313 //If we can open the file, lock it.
315 if(try_acquire_file_lock(fhnd, acquired) && acquired){
316 //If locked, just delete the file
317 delete_file(file.c_str());
321 //If not locked, the owner is suppossed to be still alive
325 //If the lock file does not exist then the owner is dead (a previous cleanup)
326 //function has deleted the file. If there is another reason, then this is
327 //an unrecoverable error
328 if(error_info(system_error_code()).get_error_code() == not_found_error){
335 template<class Mutex>
336 inline void robust_spin_mutex<Mutex>::consistent()
338 //This function supposes the previous state was "fixing"
339 //and the current process holds the mutex
340 if(atomic_read32(&this->state) != fixing_state &&
341 atomic_read32(&this->owner) != (boost::uint32_t)get_current_process_id()){
342 throw interprocess_exception(lock_error, "Broken id");
344 //If that's the case, just update mutex state
345 atomic_write32(&this->state, correct_state);
348 template<class Mutex>
349 inline bool robust_spin_mutex<Mutex>::previous_owner_dead()
351 //Notifies if a owner recovery has been performed in the last lock()
352 return atomic_read32(&this->state) == fixing_state;
355 template<class Mutex>
356 inline void robust_spin_mutex<Mutex>::unlock()
358 //If in "fixing" state, unlock and mark the mutex as unrecoverable
359 //so next locks will fail and all threads will be notified that the
360 //data protected by the mutex was not recoverable.
361 if(atomic_read32(&this->state) == fixing_state){
362 atomic_write32(&this->state, broken_state);
364 //Write an invalid owner to minimize pid reuse possibility
365 atomic_write32(&this->owner, get_invalid_process_id());
369 template<class Mutex>
370 inline bool robust_spin_mutex<Mutex>::lock_own_unique_file()
372 //This function forces instantiation of the singleton
373 robust_emulation_helpers::robust_mutex_lock_file* dummy =
374 &ipcdetail::intermodule_singleton
375 <robust_emulation_helpers::robust_mutex_lock_file>::get();
379 } //namespace ipcdetail{
380 } //namespace interprocess{
383 #include <boost/interprocess/detail/config_end.hpp>