IPC.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #include "IPC.h"
  2. #include <QCoreApplication>
  3. #include <QDebug>
  4. #include <QThread>
  5. #include <ctime>
  6. #include <random>
  7. IPC::IPC(uint32_t profileId)
  8. : profileId{profileId}
  9. , globalMemory{"ipc-" IPC_PROTOCOL_VERSION}
  10. {
  11. qRegisterMetaType<IPCEventHandler>("IPCEventHandler");
  12. timer.setInterval(EVENT_TIMER_MS);
  13. timer.setSingleShot(true);
  14. connect(&timer, &QTimer::timeout, this, &IPC::processEvents);
  15. std::default_random_engine randEngine((std::random_device())());
  16. std::uniform_int_distribution<uint64_t> distribution;
  17. globalId = distribution(randEngine);
  18. qDebug() << "Our global IPC ID is " << globalId;
  19. if (globalMemory.create(sizeof(IPCMemory))) {
  20. if (globalMemory.lock()) {
  21. IPCMemory* mem = global();
  22. memset(mem, 0, sizeof(IPCMemory));
  23. mem->globalId = globalId;
  24. mem->lastProcessed = time(nullptr);
  25. globalMemory.unlock();
  26. } else {
  27. qWarning() << "Couldn't lock to take ownership";
  28. }
  29. } else if (globalMemory.attach()) {
  30. qDebug() << "Attaching to the global shared memory";
  31. } else {
  32. qDebug() << "Failed to attach to the global shared memory, giving up. Error:"
  33. << globalMemory.error();
  34. return;
  35. }
  36. processEvents();
  37. }
  38. IPC::~IPC()
  39. {
  40. if (!globalMemory.lock()) {
  41. qWarning() << "Failed to lock in ~IPC";
  42. return;
  43. }
  44. if (isCurrentOwnerNoLock()) {
  45. global()->globalId = 0;
  46. }
  47. globalMemory.unlock();
  48. }
  49. time_t IPC::postEvent(const QString& name, const QByteArray& data, uint32_t dest)
  50. {
  51. QByteArray binName = name.toUtf8();
  52. if (binName.length() > (int32_t)sizeof(IPCEvent::name)) {
  53. return 0;
  54. }
  55. if (data.length() > (int32_t)sizeof(IPCEvent::data)) {
  56. return 0;
  57. }
  58. if (!globalMemory.lock()) {
  59. qDebug() << "Failed to lock in postEvent()";
  60. return 0;
  61. }
  62. IPCEvent* evt = nullptr;
  63. IPCMemory* mem = global();
  64. time_t result = 0;
  65. for (uint32_t i = 0; !evt && i < EVENT_QUEUE_SIZE; ++i) {
  66. if (mem->events[i].posted == 0) {
  67. evt = &mem->events[i];
  68. }
  69. }
  70. if (evt) {
  71. memset(evt, 0, sizeof(IPCEvent));
  72. memcpy(evt->name, binName.constData(), binName.length());
  73. memcpy(evt->data, data.constData(), data.length());
  74. mem->lastEvent = evt->posted = result = qMax(mem->lastEvent + 1, time(nullptr));
  75. evt->dest = dest;
  76. evt->sender = qApp->applicationPid();
  77. qDebug() << "postEvent " << name << "to" << dest;
  78. }
  79. globalMemory.unlock();
  80. return result;
  81. }
  82. bool IPC::isCurrentOwner()
  83. {
  84. if (globalMemory.lock()) {
  85. const bool isOwner = isCurrentOwnerNoLock();
  86. globalMemory.unlock();
  87. return isOwner;
  88. } else {
  89. qWarning() << "isCurrentOwner failed to lock, returning false";
  90. return false;
  91. }
  92. }
  93. void IPC::registerEventHandler(const QString& name, IPCEventHandler handler)
  94. {
  95. eventHandlers[name] = handler;
  96. }
  97. bool IPC::isEventAccepted(time_t time)
  98. {
  99. bool result = false;
  100. if (!globalMemory.lock()) {
  101. return result;
  102. }
  103. if (difftime(global()->lastProcessed, time) > 0) {
  104. IPCMemory* mem = global();
  105. for (uint32_t i = 0; i < EVENT_QUEUE_SIZE; ++i) {
  106. if (mem->events[i].posted == time && mem->events[i].processed) {
  107. result = mem->events[i].accepted;
  108. break;
  109. }
  110. }
  111. }
  112. globalMemory.unlock();
  113. return result;
  114. }
  115. bool IPC::waitUntilAccepted(time_t postTime, int32_t timeout /*=-1*/)
  116. {
  117. bool result = false;
  118. time_t start = time(nullptr);
  119. forever
  120. {
  121. result = isEventAccepted(postTime);
  122. if (result || (timeout > 0 && difftime(time(nullptr), start) >= timeout)) {
  123. break;
  124. }
  125. qApp->processEvents();
  126. QThread::msleep(0);
  127. }
  128. return result;
  129. }
  130. bool IPC::isAttached() const
  131. {
  132. return globalMemory.isAttached();
  133. }
  134. void IPC::setProfileId(uint32_t profileId)
  135. {
  136. this->profileId = profileId;
  137. }
  138. IPC::IPCEvent* IPC::fetchEvent()
  139. {
  140. IPCMemory* mem = global();
  141. for (uint32_t i = 0; i < EVENT_QUEUE_SIZE; ++i) {
  142. IPCEvent* evt = &mem->events[i];
  143. if ((evt->processed && difftime(time(nullptr), evt->processed) > EVENT_GC_TIMEOUT)
  144. || (!evt->processed && difftime(time(nullptr), evt->posted) > EVENT_GC_TIMEOUT)) {
  145. memset(evt, 0, sizeof(IPCEvent));
  146. }
  147. if (evt->posted && !evt->processed && evt->sender != qApp->applicationPid()
  148. && (evt->dest == profileId || (evt->dest == 0 && isCurrentOwnerNoLock()))) {
  149. return evt;
  150. }
  151. }
  152. return nullptr;
  153. }
  154. bool IPC::runEventHandler(IPCEventHandler handler, const QByteArray& arg)
  155. {
  156. bool result = false;
  157. if (QThread::currentThread() == qApp->thread()) {
  158. result = handler(arg);
  159. } else {
  160. QMetaObject::invokeMethod(this, "runEventHandler", Qt::BlockingQueuedConnection,
  161. Q_RETURN_ARG(bool, result), Q_ARG(IPCEventHandler, handler),
  162. Q_ARG(const QByteArray&, arg));
  163. }
  164. return result;
  165. }
  166. void IPC::processEvents()
  167. {
  168. if (!globalMemory.lock()) {
  169. timer.start();
  170. return;
  171. }
  172. IPCMemory* mem = global();
  173. if (mem->globalId == globalId) {
  174. mem->lastProcessed = time(nullptr);
  175. } else {
  176. if (difftime(time(nullptr), mem->lastProcessed) >= OWNERSHIP_TIMEOUT_S) {
  177. qDebug() << "Previous owner timed out, taking ownership" << mem->globalId << "->"
  178. << globalId;
  179. memset(mem, 0, sizeof(IPCMemory));
  180. mem->globalId = globalId;
  181. mem->lastProcessed = time(nullptr);
  182. }
  183. }
  184. while (IPCEvent* evt = fetchEvent()) {
  185. QString name = QString::fromUtf8(evt->name);
  186. auto it = eventHandlers.find(name);
  187. if (it != eventHandlers.end()) {
  188. evt->accepted = runEventHandler(it.value(), evt->data);
  189. qDebug() << "Processed event:" << name << "posted:" << evt->posted
  190. << "accepted:" << evt->accepted;
  191. if (evt->dest == 0) {
  192. if (evt->accepted) {
  193. evt->processed = time(nullptr);
  194. }
  195. } else {
  196. evt->processed = time(nullptr);
  197. }
  198. } else {
  199. qDebug() << "Received event:" << name << "without handler";
  200. qDebug() << "Available handlers:" << eventHandlers.keys();
  201. }
  202. }
  203. globalMemory.unlock();
  204. timer.start();
  205. }
  206. bool IPC::isCurrentOwnerNoLock()
  207. {
  208. const void* const data = globalMemory.data();
  209. if (!data) {
  210. qWarning() << "isCurrentOwnerNoLock failed to access the memory, returning false";
  211. return false;
  212. }
  213. return (*static_cast<const uint64_t*>(data) == globalId);
  214. }
  215. IPC::IPCMemory* IPC::global()
  216. {
  217. return static_cast<IPCMemory*>(globalMemory.data());
  218. }