| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | // Copyright 2019 Juan Palacios <[email protected]> |
| 3 | |
| 4 | #include "processmonitor.h" |
| 5 | |
| 6 | #include "iappregistry.h" |
| 7 | #include "ipidsolver.h" |
| 8 | #include "ipmonmsgdispatcher.h" |
| 9 | #include "processevent.h" |
| 10 | #include "processregistry.h" |
| 11 | #include <utility> |
| 12 | |
| 13 | ProcessMonitor::ProcessMonitor( |
| 14 | std::shared_ptr<IAppRegistry> appRegistry, |
| 15 | std::unique_ptr<IPIDSolver> &&pidSolver, |
| 16 | std::unique_ptr<IPMonMsgDispatcher> &&msgDispatcher) noexcept |
| 17 | : appRegistry_(std::move(appRegistry)) |
| 18 | , pidSolver_(std::move(pidSolver)) |
| 19 | , msgDispatcher_(std::move(msgDispatcher)) |
| 20 | { |
| 21 | procRegistry_ = std::make_unique<ProcessRegistry>(this->appRegistry_); |
| 22 | } |
| 23 | |
| 24 | ProcessMonitor::~ProcessMonitor() = default; |
| 25 | |
| 26 | void ProcessMonitor::start() |
| 27 | { |
| 28 | while (!stopSignal_.load(std::memory_order_relaxed)) { |
| 29 | ProcessEvent const e = waitProcessEvent(); |
| 30 | |
| 31 | switch (e.event) { |
| 32 | case ProcessEvent::Type::IGNORE: |
| 33 | continue; |
| 34 | |
| 35 | case ProcessEvent::Type::EXEC: |
| 36 | processExec(e.pid); |
| 37 | break; |
| 38 | |
| 39 | case ProcessEvent::Type::EXIT: |
| 40 | processExit(e.pid); |
| 41 | break; |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | void ProcessMonitor::stop() |
| 47 | { |
| 48 | stopSignal_.store(true, std::memory_order_relaxed); |
| 49 | } |
| 50 | |
| 51 | void ProcessMonitor::processExec(int pid) |
| 52 | { |
| 53 | auto const app = pidSolver_->app(pid); |
| 54 | |
| 55 | if (!appRegistry_->registered(app)) |
| 56 | return; |
| 57 | |
| 58 | if (!procRegistry_->running(app)) |
| 59 | msgDispatcher_->sendExec(app); |
| 60 | |
| 61 | procRegistry_->add(pid, app); |
| 62 | } |
| 63 | |
| 64 | void ProcessMonitor::processExit(int pid) |
| 65 | { |
| 66 | auto app = procRegistry_->findApp(pid); |
| 67 | if (!app) // no app registered to that PID |
| 68 | return; |
| 69 | |
| 70 | procRegistry_->remove(pid); |
| 71 | |
| 72 | if (!procRegistry_->running(app.value())) |
| 73 | msgDispatcher_->sendExit(app.value()); |
| 74 | } |