ChimeraTK-DeviceAccess 03.25.00
Loading...
Searching...
No Matches
SharedMemoryManager.cc
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Deutsches Elektronen-Synchrotron DESY, MSK, ChimeraTK Project <chimeratk-support@desy.de>
2// SPDX-License-Identifier: LGPL-3.0-or-later
3
5#include "Utilities.h"
6
7namespace ChimeraTK {
8
9 namespace {
10 // Proxy class to add try_lock_for() to boost::interprocess::named_mutex::named_mutex, which is not present on older
11 // BOOST versions like on Ubuntu 20.04. This can be removed and replaced with boost::interprocess::named_mutex once
12 // we are fully on Ubuntu 24.04 or newer.
13 class IpcNamedMutex {
14 public:
15 explicit IpcNamedMutex(boost::interprocess::named_mutex& mx) : _mx(mx) {}
16
17 template<typename Duration>
18 // NOLINTNEXTLINE(readability-identifier-naming)
19 bool try_lock_for(const Duration& dur) {
20 auto abs_time = boost::posix_time::microsec_clock::universal_time();
21 auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();
22 auto bmillis = boost::posix_time::milliseconds(millis);
23 abs_time += bmillis;
24 return _mx.timed_lock(abs_time);
25 }
26
27 template<typename Duration>
28 // NOLINTNEXTLINE(readability-identifier-naming)
29 bool try_lock_until(const Duration& abs_time) {
30 return _mx.timed_lock(abs_time);
31 }
32
33 void lock() { _mx.lock(); }
34
35 void unlock() { _mx.unlock(); }
36
37 // NOLINTNEXTLINE(readability-identifier-naming)
38 bool try_lock() { return _mx.try_lock(); }
39
40 private:
41 boost::interprocess::named_mutex& _mx;
42 };
43 } // namespace
44
45 // Construct/deconstruct
46 SharedDummyBackend::SharedMemoryManager::SharedMemoryManager(
47 SharedDummyBackend& sharedDummyBackend_, std::size_t instanceIdHash, const std::string& mapFileName)
48 : sharedDummyBackend(sharedDummyBackend_), name(Utilities::createShmName(instanceIdHash, mapFileName, getUserName())),
49 segment(boost::interprocess::open_or_create, name.c_str(), getRequiredMemoryWithOverhead()),
50 sharedMemoryIntAllocator(segment.get_segment_manager()),
51 interprocessMutex(boost::interprocess::open_or_create, name.c_str()) {
52 retry:
53 // scope for lock guard of the interprocess mutex
54 {
55 IpcNamedMutex proxy(interprocessMutex);
56 std::unique_lock<IpcNamedMutex> lock(proxy, std::defer_lock);
57 bool ok = lock.try_lock_for(std::chrono::milliseconds(2000));
58 if(!ok) {
59 std::cerr << "SharedDummyBackend: stale lock detected, removing mutex... " << std::endl;
60
61 // named_mutex has no (move) assignment operator, so we need to work around here (placement delete and new)
62 boost::interprocess::named_mutex::remove(name.c_str());
63 interprocessMutex.~named_mutex();
64 new(&interprocessMutex) boost::interprocess::named_mutex(boost::interprocess::open_or_create, name.c_str());
65
66 goto retry;
67 }
68
69 pidSet = findOrConstructVector(SHARED_MEMORY_PID_SET_NAME, 0);
70
71 // Clean up pidSet, if needed
72 bool reInitRequired = checkPidSetConsistency();
73
74 // If only "zombie" processes were found in PidSet,
75 // reset data entries in shared memory.
76 if(reInitRequired) {
77 reInitMemory();
78 }
79
80 // Get memory item for version number
81 requiredVersion = segment.find_or_construct<unsigned>(SHARED_MEMORY_REQUIRED_VERSION_NAME)(0);
82
83 // Protect against too many accessing processes to prevent
84 // overflow of pidSet in shared memory.
85 if(pidSet->size() >= SHARED_MEMORY_N_MAX_MEMBER) {
86 std::string errMsg{"Maximum number of accessing members reached."};
87 throw ChimeraTK::runtime_error(errMsg);
88 }
89 InterruptDispatcherInterface::cleanupShm(segment, pidSet);
90
91 pidSet->emplace_back(static_cast<int32_t>(getOwnPID()));
92 } // releases the lock
93 this->intDispatcherIf = boost::movelib::unique_ptr<InterruptDispatcherInterface>(
94 new InterruptDispatcherInterface(sharedDummyBackend, segment, interprocessMutex));
95 }
96
97 SharedDummyBackend::SharedMemoryManager::~SharedMemoryManager() {
98 // stop and delete dispatcher thread first since it uses shm and mutex
99 intDispatcherIf.reset();
100 size_t pidSetSize;
101 try {
102 // The scope of the try-block is the scope of the lock_guard, which can throw when locking.
103 // All the lines in the try-block have to be executed under the lock, although not everything
104 // might be throwing.
105
106 // lock guard with the interprocess mutex
107 std::lock_guard<boost::interprocess::named_mutex> lock(interprocessMutex);
108
109 // Clean up
110 checkPidSetConsistency();
111
112 auto ownPid = static_cast<int32_t>(getOwnPID());
113 for(auto it = pidSet->begin(); it != pidSet->end();) {
114 if(*it == ownPid) {
115 it = pidSet->erase(it);
116 }
117 else {
118 ++it;
119 }
120 }
121 pidSetSize = pidSet->size();
122 }
123 catch(boost::interprocess::interprocess_exception&) {
124 // interprocess_exception is only thrown if something seriously went wrong.
125 // In this case we don't want anyone to catch it but terminate.
126 std::terminate();
127 }
128 // If size of pidSet is 0 (i.e, the instance belongs to the last accessing
129 // process), destroy shared memory and the interprocess mutex
130 if(pidSetSize == 0) {
131 boost::interprocess::shared_memory_object::remove(name.c_str());
132 boost::interprocess::named_mutex::remove(name.c_str());
133 }
134 }
135
136 // Member functions
137 SharedMemoryVector* SharedDummyBackend::SharedMemoryManager::findOrConstructVector(
138 const std::string& objName, const size_t size) {
139 SharedMemoryVector* vector =
140 segment.find_or_construct<SharedMemoryVector>(objName.c_str())(size, 0, sharedMemoryIntAllocator);
141
142 return vector;
143 }
144
145 size_t SharedDummyBackend::SharedMemoryManager::getRequiredMemoryWithOverhead() {
146 // Note: This uses _barSizeInBytes to determine number of vectors used,
147 // as it is initialized when this method gets called in the init list.
148 return SHARED_MEMORY_OVERHEAD_PER_VECTOR * sharedDummyBackend._barSizesInBytes.size() +
149 SHARED_MEMORY_CONST_OVERHEAD + sharedDummyBackend.getTotalRegisterSizeInBytes() + sizeof(ShmForSems);
150 }
151
152 std::pair<size_t, size_t> SharedDummyBackend::SharedMemoryManager::getInfoOnMemory() {
153 return std::make_pair(segment.get_size(), segment.get_free_memory());
154 }
155
156 bool SharedDummyBackend::SharedMemoryManager::checkPidSetConsistency() {
157 unsigned pidSetSizeBeforeCleanup = pidSet->size();
158
159 for(auto it = pidSet->begin(); it != pidSet->end();) {
160 if(!processExists(*it)) {
161 // std::cout << "Nonexistent PID " << *it << " found. " <<std::endl;
162 it = pidSet->erase(it);
163 }
164 else {
165 it++;
166 }
167 }
168
169 return pidSetSizeBeforeCleanup != 0 && pidSet->empty();
170 }
171
172 void SharedDummyBackend::SharedMemoryManager::reInitMemory() {
173 std::vector<std::string> nameList = listNamedElements();
174
175 for(auto& item : nameList) {
176 if(item == SHARED_MEMORY_REQUIRED_VERSION_NAME) {
177 segment.destroy<unsigned>(item.c_str());
178 }
179 // reset the BAR vectors in shm.
180 // Note, InterruptDispatcherInterface uses unique_instance mechanism so it is not affected here
181 else if(item != SHARED_MEMORY_PID_SET_NAME) {
182 segment.destroy<SharedMemoryVector>(item.c_str());
183 }
184 }
185 InterruptDispatcherInterface::cleanupShm(segment);
186 }
187
188 std::vector<std::string> SharedDummyBackend::SharedMemoryManager::listNamedElements() {
189 std::vector<std::string> list(segment.get_num_named_objects());
190
191 for(auto seg = segment.named_begin(); seg != segment.named_end(); ++seg) {
192 list.emplace_back(seg->name());
193 }
194 return list;
195 }
196
197} /* namespace ChimeraTK */
std::string getUserName()
bool processExists(unsigned pid)
unsigned getOwnPID()
boost::interprocess::vector< int32_t, ShmemAllocator > SharedMemoryVector
Exception thrown when a runtime error has occured.
Definition Exception.h:18
std::string createShmName(std::size_t instanceIdHash, const std::string &mapFileName, const std::string &userName)
Generates shm dummy name from parameter hashes.