29#include <linux/limits.h>
40 : ctxt(ctxt), serviceThread(nullptr) {}
53 *
this, engineTypeName, idPath, details, clients);
58 std::unique_ptr<Engine> engine,
61 auto [engineIter, _] =
ownedEngines.emplace(idPath, std::move(engine));
65 Engine *enginePtr = engineIter->second.get();
68 if (prefix.size() > 0)
71 for (
const auto &client : clients) {
72 AppIDPath fullClientPath = prefix + client.relPath;
73 for (
const auto &channel : client.channelAssignments)
74 clientEngines[fullClientPath].setEngine(channel.first, enginePtr);
83 std::unique_ptr<Service> &cacheEntry =
serviceCache[make_tuple(&svcType,
id)];
84 if (cacheEntry ==
nullptr) {
91 cacheEntry = std::unique_ptr<Service>(svc);
93 return cacheEntry.get();
99 throw std::runtime_error(
100 "AcceleratorConnection already owns an accelerator");
108 char result[PATH_MAX];
109 ssize_t count = readlink(
"/proc/self/exe", result, PATH_MAX);
111 throw std::runtime_error(
"Could not get executable path");
112 return std::filesystem::path(std::string(result, count));
114 char buffer[MAX_PATH];
115 DWORD length = GetModuleFileNameA(NULL, buffer, MAX_PATH);
117 throw std::runtime_error(
"Could not get executable path");
118 return std::filesystem::path(std::string(buffer, length));
120#eror "Unsupported platform"
129 return std::filesystem::path(std::string(dl_info.dli_fname));
131 HMODULE hModule = NULL;
132 if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
133 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
134 reinterpret_cast<LPCSTR
>(&
getLibPath), &hModule)) {
136 return std::filesystem::path();
139 char buffer[MAX_PATH];
140 DWORD length = GetModuleFileNameA(hModule, buffer, MAX_PATH);
142 throw std::runtime_error(
"Could not get library path");
144 return std::filesystem::path(std::string(buffer, length));
146#eror "Unsupported platform"
152 std::vector<std::filesystem::path> directories;
155 directories.push_back(std::filesystem::current_path());
158 const char *esiBackends = std::getenv(
"ESI_BACKENDS");
162 const char separator =
';';
164 const char separator =
':';
167 std::string pathsStr(esiBackends);
168 std::stringstream ss(pathsStr);
171 while (std::getline(ss, path, separator))
173 directories.emplace_back(path);
177 directories.push_back(
getExePath().parent_path());
179 directories.push_back(
getLibPath().parent_path());
189 Logger &logger = ctxt.getLogger();
190 backend[0] = toupper(backend[0]);
194 std::string backendFileName =
"lib" + backend +
"Backend.so";
196 std::string backendFileName = backend +
"Backend.dll";
198#eror "Unsupported platform"
202 std::filesystem::path backendPath;
204 std::vector<std::filesystem::path> esiBackendDirs =
207 for (
const auto &dir : esiBackendDirs) {
208 backendPath = dir / backendFileName;
209 logger.
debug(
"CONNECT",
210 "trying to find backend plugin: " + backendPath.string());
211 if (std::filesystem::exists(backendPath)) {
219 backendPath = std::filesystem::absolute(backendPath);
220 logger.
debug(
"CONNECT",
"found backend plugin: " + backendPath.string());
223 backendPath = backendFileName;
224 logger.
debug(
"CONNECT",
225 "trying to find backend plugin: " + backendFileName);
230 void *handle = dlopen(backendPath.string().c_str(), RTLD_NOW | RTLD_GLOBAL);
232 std::string error(dlerror());
233 logger.
error(
"CONNECT",
234 "while attempting to load backend plugin: " + error);
235 throw std::runtime_error(
"While attempting to load backend plugin: " +
242 std::filesystem::path backendPathParent = backendPath.parent_path();
247 if (backendPathParent.empty())
248 backendPathParent = std::filesystem::current_path();
249 logger.
debug(
"CONNECT",
"setting DLL search directory to: " +
250 backendPathParent.string());
251 if (SetDllDirectoryA(backendPathParent.string().c_str()) == 0)
252 throw std::runtime_error(
"While setting DLL directory: " +
253 std::to_string(GetLastError()));
257 HMODULE handle = LoadLibraryA(backendPath.string().c_str());
259 DWORD error = GetLastError();
261 LPSTR messageBuffer =
nullptr;
262 size_t size = FormatMessageA(
263 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
264 FORMAT_MESSAGE_IGNORE_INSERTS,
265 nullptr, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
266 (LPSTR)&messageBuffer, 0,
nullptr);
268 std::string errorMessage;
269 if (size > 0 && messageBuffer !=
nullptr) {
270 errorMessage = std::string(messageBuffer, size);
271 LocalFree(messageBuffer);
273 errorMessage =
"Unknown error";
276 std::string fullError =
"While attempting to load backend plugin '" +
277 backendPath.string() +
"': " + errorMessage +
278 " (error code: " + std::to_string(error) +
")";
280 logger.
error(
"CONNECT", fullError);
281 throw std::runtime_error(fullError);
284#eror "Unsupported platform"
286 logger.
info(
"CONNECT",
"loaded backend plugin: " + backendPath.string());
294 static std::map<std::string, BackendCreate> &
get() {
305 if (registry.count(name))
306 throw std::runtime_error(
"Backend already exists in registry");
307 registry[name] = create;
312 const std::string &backend,
313 const std::string &connection) {
315 auto f = registry.find(backend);
316 if (f == registry.end()) {
319 f = registry.find(backend);
320 if (f == registry.end()) {
322 details[
"backend"] = backend;
323 std::ostringstream loaded_backends;
325 for (
const auto &b : registry) {
327 loaded_backends <<
", ";
328 loaded_backends << b.first;
331 details[
"loaded_backends"] = loaded_backends.str();
332 ctxt.getLogger().error(
"CONNECT",
"backend '" + backend +
"' not found",
334 throw std::runtime_error(
"Backend '" + backend +
"' not found");
337 ctxt.getLogger().info(
"CONNECT",
"connecting to backend " + backend +
338 " via '" + connection +
"'");
339 return f->second(ctxt, connection);
346 void start() {
me = std::thread(&Impl::loop,
this); }
354 addListener(std::initializer_list<ReadChannelPort *> listenPorts,
357 void addTask(std::function<
void(
void)> task) {
358 std::lock_guard<std::mutex> g(
m);
373 std::future<MessageData>>>
380void AcceleratorServiceThread::Impl::loop() {
387 std::vector<std::function<void(
void)>> taskListCopy;
395 std::this_thread::yield();
400 std::lock_guard<std::mutex> g(
m);
401 for (
auto &[channel, cbfPair] :
listeners) {
402 assert(channel &&
"Null channel in listener list");
403 std::future<MessageData> &f = cbfPair.second;
404 if (f.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
405 portUnlockWorkList.emplace_back(channel, cbfPair.first, f.get());
406 f = channel->readAsync();
412 for (
auto [channel, cb, data] : portUnlockWorkList)
413 cb(channel, std::move(data));
416 portUnlockWorkList.clear();
421 std::lock_guard<std::mutex> g(
m);
424 for (
auto &task : taskListCopy)
429void AcceleratorServiceThread::Impl::addListener(
430 std::initializer_list<ReadChannelPort *> listenPorts,
432 std::lock_guard<std::mutex> g(m);
433 for (
auto port : listenPorts) {
434 if (listeners.count(port))
435 throw std::runtime_error(
"Port already has a listener");
436 listeners[port] = std::make_pair(callback, port->readAsync());
443 : impl(std::make_unique<
Impl>()) {
459 std::initializer_list<ReadChannelPort *> listenPorts,
462 impl->addListener(listenPorts, callback);
467 impl->addTask([&module]() {
module.poll(); });
assert(baseType &&"element must be base type")
virtual void disconnect()
Disconnect from the accelerator cleanly.
virtual Service * createService(Service::Type service, AppIDPath idPath, std::string implName, const ServiceImplDetails &details, const HWClientDetails &clients)=0
Called by getServiceImpl exclusively.
ServiceClass * getService(AppIDPath id={}, std::string implName={}, ServiceImplDetails details={}, HWClientDetails clients={})
Get a typed reference to a particular service type.
std::map< AppIDPath, BundleEngineMap > clientEngines
Mapping of clients to their servicing engines.
void registerEngine(AppIDPath idPath, std::unique_ptr< Engine > engine, const HWClientDetails &clients)
If createEngine is overridden, this method should be called to register the engine and all of the cha...
std::map< ServiceCacheKey, std::unique_ptr< Service > > serviceCache
std::unique_ptr< AcceleratorServiceThread > serviceThread
std::unique_ptr< Accelerator > ownedAccelerator
Accelerator object owned by this connection.
std::map< AppIDPath, std::unique_ptr< Engine > > ownedEngines
Collection of owned engines.
virtual void createEngine(const std::string &engineTypeName, AppIDPath idPath, const ServiceImplDetails &details, const HWClientDetails &clients)
Create a new engine for channel communication with the accelerator.
virtual ~AcceleratorConnection()
AcceleratorServiceThread * getServiceThread()
Return a pointer to the accelerator 'service' thread (or threads).
AcceleratorConnection(Context &ctxt)
Accelerator * takeOwnership(std::unique_ptr< Accelerator > accel)
Assume ownership of an accelerator object.
Background thread which services various requests.
void stop()
Instruct the service thread to stop running.
void addListener(std::initializer_list< ReadChannelPort * > listenPorts, std::function< void(ReadChannelPort *, MessageData)> callback)
When there's data on any of the listenPorts, call the callback.
AcceleratorServiceThread()
std::unique_ptr< Impl > impl
void addPoll(HWModule &module)
Poll this module.
~AcceleratorServiceThread()
Top level accelerator class.
AcceleratorConnections, Accelerators, and Manifests must all share a context.
Engines implement the actual channel communication between the host and the accelerator.
Represents either the top level or an instance of a hardware module.
virtual void error(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report an error.
virtual void info(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report an informational message.
void debug(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report a debug message.
A logical chunk of data representing serialized data.
A ChannelPort which reads data from the accelerator.
std::map< std::string, BackendCreate > backendRegistry
static std::map< std::string, BackendCreate > & get()
static Service * createService(AcceleratorConnection *acc, Service::Type svcType, AppIDPath id, std::string implName, ServiceImplDetails details, HWClientDetails clients)
Create a service instance from the given details.
Parent class of all APIs modeled as 'services'.
const std::type_info & Type
void registerBackend(const std::string &name, BackendCreate create)
std::function< std::unique_ptr< AcceleratorConnection >(Context &, std::string)> BackendCreate
Backends can register themselves to be connected via a connection string.
std::unique_ptr< AcceleratorConnection > connect(Context &ctxt, const std::string &backend, const std::string &connection)
std::unique_ptr< Engine > createEngine(AcceleratorConnection &conn, const std::string &dmaEngineName, AppIDPath idPath, const ServiceImplDetails &details, const HWClientDetails &clients)
Create an engine by name.
static std::filesystem::path getExePath()
Get the path to the currently running executable.
std::map< std::string, std::any > ServiceImplDetails
static void loadBackend(Context &ctxt, std::string backend)
Load a backend plugin dynamically.
static std::filesystem::path getLibPath()
Get the path to the currently running shared library.
static std::vector< std::filesystem::path > getESIBackendDirectories()
Get the list of directories to search for backend plugins.
std::vector< HWClientDetail > HWClientDetails
std::map< ReadChannelPort *, std::pair< std::function< void(ReadChannelPort *, MessageData)>, std::future< MessageData > > > listeners
void addTask(std::function< void(void)> task)
void addListener(std::initializer_list< ReadChannelPort * > listenPorts, std::function< void(ReadChannelPort *, MessageData)> callback)
When there's data on any of the listenPorts, call the callback.
std::vector< std::function< void(void)> > taskList
Tasks which should be called on every loop iteration.