| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
|---|---|
| 2 | |
| 3 | #pragma once |
| 4 | |
| 5 | #include "units/device.hpp" |
| 6 | #include "units/mount.hpp" |
| 7 | #include "units/path.hpp" |
| 8 | #include "units/service.hpp" |
| 9 | #include "units/symlink.hpp" |
| 10 | #include "units/target.hpp" |
| 11 | #include "units/unit.hpp" |
| 12 | |
| 13 | #include <memory> |
| 14 | #include <shared_mutex> |
| 15 | #include <string> |
| 16 | #include <toml++/impl/table.hpp> |
| 17 | #include <vector> |
| 18 | |
| 19 | template<typename T> |
| 20 | struct Locked |
| 21 | { |
| 22 | Locked() = default; |
| 23 | explicit Locked(T item) : item(item) {}; |
| 24 | |
| 25 | public: |
| 26 | std::pair<T &, std::unique_lock<std::shared_mutex>> BeginWrite() |
| 27 | { |
| 28 | return { item, std::unique_lock(lock) }; |
| 29 | } |
| 30 | |
| 31 | std::pair<const T &, std::shared_lock<std::shared_mutex>> BeginRead() const |
| 32 | { |
| 33 | return { item, std::shared_lock(lock) }; |
| 34 | } |
| 35 | |
| 36 | T Clone() const |
| 37 | { |
| 38 | std::shared_lock<std::shared_mutex> l(lock); |
| 39 | return item; |
| 40 | } |
| 41 | |
| 42 | private: |
| 43 | T item; |
| 44 | mutable std::shared_mutex lock; |
| 45 | }; |
| 46 | |
| 47 | class ServiceManagerImpl final |
| 48 | { |
| 49 | friend Unit; |
| 50 | friend Service; |
| 51 | friend Symlink; |
| 52 | friend Mount; |
| 53 | friend Path; |
| 54 | friend Target; |
| 55 | friend Device; |
| 56 | |
| 57 | public: |
| 58 | explicit ServiceManagerImpl() = default; |
| 59 | |
| 60 | public: |
| 61 | bool StartUnit(const std::string &id) const; |
| 62 | bool StopUnit(const std::string &id) const; |
| 63 | |
| 64 | bool StartDefaultTarget() const; |
| 65 | |
| 66 | void OnProcessExit(pid_t pid, int status); |
| 67 | |
| 68 | private: |
| 69 | void OnUnitStarted(Unit *unit); |
| 70 | void OnUnitStopped(Unit *unit); |
| 71 | |
| 72 | private: |
| 73 | std::vector<std::string> GetStartupOrder(const std::string &id) const; |
| 74 | |
| 75 | private: |
| 76 | Locked<std::vector<std::thread>> startup_jobs; |
| 77 | }; |
| 78 | |
| 79 | inline const std::unique_ptr<ServiceManagerImpl> ServiceManager = std::make_unique<ServiceManagerImpl>(); |
| 80 |