summaryrefslogtreecommitdiff
path: root/src/CommonAPI/Runtime.cpp
blob: 9a6cb4f10f9b74a7d321bbfa35be416d18bc7afd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Copyright (C) 2015 BMW Group
// Author: Lutz Bichler (lutz.bichler@bmw.de)
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifdef WIN32
#include <Windows.h>
#else
#include <dlfcn.h>
#include <unistd.h>
#endif

#include <sys/stat.h>

#include <algorithm>

#include <CommonAPI/Factory.hpp>
#include <CommonAPI/IniFileReader.hpp>
#include <CommonAPI/Logger.hpp>
#include <CommonAPI/Runtime.hpp>

namespace CommonAPI {

const char *COMMONAPI_DEFAULT_BINDING = "dbus";
const char *COMMONAPI_DEFAULT_FOLDER = "/usr/local/lib/commonapi";
const char *COMMONAPI_DEFAULT_CONFIG_FILE = "commonapi.ini";
const char *COMMONAPI_DEFAULT_CONFIG_FOLDER = "/etc";

std::shared_ptr<Runtime> Runtime::get() {
	static std::shared_ptr<Runtime> theRuntime = std::make_shared<Runtime>();
	return theRuntime;
}

Runtime::Runtime()
	: defaultBinding_(COMMONAPI_DEFAULT_BINDING),
	  defaultFolder_(COMMONAPI_DEFAULT_FOLDER) {
	init();
}

Runtime::~Runtime() {
	// intentionally left empty
}

bool
Runtime::registerFactory(const std::string &_binding, std::shared_ptr<Factory> _factory) {
	COMMONAPI_DEBUG("Registering factory for binding=", _binding);
	bool isRegistered(false);
	std::lock_guard<std::mutex> itsLock(factoriesMutex_);
	auto foundFactory = factories_.find(_binding);
	if (foundFactory == factories_.end()) {
		factories_[_binding] = _factory;
		isRegistered = true;
	}
	return isRegistered;
}

bool
Runtime::unregisterFactory(const std::string &_binding) {
	COMMONAPI_DEBUG("Unregistering factory for binding=", _binding);
	std::lock_guard<std::mutex> itsLock(factoriesMutex_);
	factories_.erase(_binding);
	return true;
}

/*
 * Private
 */
void Runtime::init() {
	// Determine default configuration file
	const char *config = getenv("COMMONAPI_CONFIG");
	if (config) {
		defaultConfig_ = config;
	} else {
		defaultConfig_ = COMMONAPI_DEFAULT_CONFIG_FOLDER;
		defaultConfig_ += "/";
		defaultConfig_ += COMMONAPI_DEFAULT_CONFIG_FILE;
	}

	// TODO: evaluate return parameter and decide what to do
	(void)readConfiguration();

	// Determine default ipc & shared library folder
	const char *binding = getenv("COMMONAPI_DEFAULT_BINDING");
	if (binding)
		defaultBinding_ = binding;

	const char *folder = getenv("COMMONAPI_DEFAULT_FOLDER");
	if (folder)
		defaultFolder_ = folder;

	// Log settings
	COMMONAPI_INFO("Using default binding \'", defaultBinding_, "\'");
	COMMONAPI_INFO("Using default shared library folder \'", defaultFolder_, "\'");
	COMMONAPI_INFO("Using default configuration file \'", defaultConfig_, "\'");
}

bool
Runtime::readConfiguration() {
#define MAX_PATH_LEN 255
	std::string config;
	char currentDirectory[MAX_PATH_LEN];
#ifdef WIN32
	if (GetCurrentDirectory(MAX_PATH_LEN, currentDirectory)) {
#else
	if (getcwd(currentDirectory, MAX_PATH_LEN)) {
#endif
		config = currentDirectory;
		config += "/";
		config += COMMONAPI_DEFAULT_CONFIG_FILE;

		struct stat s;
		if (stat(config.c_str(), &s) != 0) {
			config = defaultConfig_;
		}
	}

	IniFileReader reader;
	if (!reader.load(config))
		return false;

	std::shared_ptr<IniFileReader::Section> section
		= reader.getSection("default");
	if (section) {
		std::string binding = section->getValue("binding");
		if ("" != binding)
			defaultBinding_ = binding;

		std::string folder = section->getValue("folder");
		if ("" != folder)
			defaultFolder_ = folder;
	}

	section = reader.getSection("proxy");
	if (section) {
		for (auto m : section->getMappings()) {
			COMMONAPI_DEBUG("Adding proxy mapping: ", m.first, " --> ", m.second);
			libraries_[m.first][true] = m.second;
		}
	}

	section = reader.getSection("stub");
	if (section) {
		for (auto m : section->getMappings()) {
			COMMONAPI_DEBUG("Adding stub mapping: ", m.first, " --> ", m.second);
			libraries_[m.first][false] = m.second;
		}
	}

	return true;
}

std::shared_ptr<Proxy>
Runtime::createProxy(
		const std::string &_domain, const std::string &_interface, const std::string &_instance,
		const ConnectionId &_connectionId) {

	// Check whether we already know how to create such proxies...
	std::shared_ptr<Proxy> proxy = createProxyHelper(_domain, _interface, _instance, _connectionId);
	if (!proxy) {
		// ...it seems do not, lets try to load a library that does...
		std::lock_guard<std::mutex> itsGuard(loadMutex_);
		std::string library = getLibrary(_domain, _interface, _instance, true);
		if (loadLibrary(library)) {
			proxy = createProxyHelper(_domain, _interface, _instance, _connectionId);
		}
	}
	return proxy;
}

std::shared_ptr<Proxy>
Runtime::createProxy(
		const std::string &_domain, const std::string &_interface, const std::string &_instance,
		std::shared_ptr<MainLoopContext> _context) {

	// Check whether we already know how to create such proxies...
	std::shared_ptr<Proxy> proxy = createProxyHelper(_domain, _interface, _instance, _context);
	if (!proxy) {
		// ...it seems do not, lets try to load a library that does...
		std::lock_guard<std::mutex> itsGuard(loadMutex_);
		std::string library = getLibrary(_domain, _interface, _instance, true);
		if (loadLibrary(library)) {
			proxy = createProxyHelper(_domain, _interface, _instance, _context);
		}
	}
	return proxy;
}


bool
Runtime::registerStub(const std::string &_domain, const std::string &_interface, const std::string &_instance,
				  	  std::shared_ptr<StubBase> _stub, const ConnectionId &_connectionId) {

	bool isRegistered = registerStubHelper(_domain, _interface, _instance, _stub, _connectionId);
	if (!isRegistered) {
		std::string library = getLibrary(_domain, _interface, _instance, false);
		std::lock_guard<std::mutex> itsGuard(loadMutex_);
		if (loadLibrary(library)) {
			isRegistered = registerStubHelper(_domain, _interface, _instance, _stub, _connectionId);
		}
	}
	return isRegistered;
}

bool
Runtime::registerStub(const std::string &_domain, const std::string &_interface, const std::string &_instance,
				  	  std::shared_ptr<StubBase> _stub, std::shared_ptr<MainLoopContext> _context) {

	bool isRegistered = registerStubHelper(_domain, _interface, _instance, _stub, _context);
	if (!isRegistered) {
		std::string library = getLibrary(_domain, _interface, _instance, false);
		std::lock_guard<std::mutex> itsGuard(loadMutex_);
		if (loadLibrary(library)) {
			isRegistered = registerStubHelper(_domain, _interface, _instance, _stub, _context);
		}
	}
	return isRegistered;
}

bool 
Runtime::unregisterStub(const std::string &_domain, const std::string &_interface, const std::string &_instance) {
	for (auto factory : factories_) {
		if (factory.second->unregisterStub(_domain, _interface, _instance))
			return true;
	}

	return false;
}

std::string
Runtime::getLibrary(
	const std::string &_domain, const std::string &_interface, const std::string &_instance,
	bool _isProxy) {

	std::string library;

	std::string address = _domain + ":" + _interface + ":" + _instance;

	COMMONAPI_DEBUG("Loading proxy library for ", address);

	auto libraryIterator = libraries_.find(address);
	if (libraryIterator != libraries_.end()) {
		auto addressIterator = libraryIterator->second.find(_isProxy);
		if (addressIterator != libraryIterator->second.end()) {
			library = addressIterator->second;
		}
	}

	// If no library was found, create default name
	if ("" == library) {
		library = "lib" + _domain + "__" + _interface + "__" + _instance;
		std::replace(library.begin(), library.end(), '.', '_');
	}

	return library;
}

bool
Runtime::loadLibrary(const std::string &_library) {
	std::string itsLibrary(_library);

	// TODO: decide whether this really is a good idea...
	#ifdef WIN32
	if (itsLibrary.find(".dll") != itsLibrary.length() - 4) {
		itsLibrary += ".dll";
	}
	#else
	if (itsLibrary.find(".so") != itsLibrary.length() - 3) {
		itsLibrary += ".so";
	}
	#endif

	bool isLoaded(true);
	if (loadedLibraries_.end() == loadedLibraries_.find(itsLibrary)) {
		#ifdef WIN32
		if (LoadLibrary(itsLibrary.c_str()) != 0) {
			loadedLibraries_.insert(itsLibrary);
			COMMONAPI_DEBUG("Loading interface library \"", itsLibrary, "\" succeeded.");
		} else {
			COMMONAPI_ERROR("Loading interface library \"", itsLibrary, "\" failed (", GetLastError(), ")");
			isLoaded = false;
		}
		#else
		if (dlopen(itsLibrary.c_str(), RTLD_LAZY | RTLD_GLOBAL) != 0) {
			loadedLibraries_.insert(itsLibrary);
			COMMONAPI_DEBUG("Loading interface library \"", itsLibrary, "\" succeeded.");
		}
		else {
			COMMONAPI_ERROR("Loading interface library \"", itsLibrary, "\" failed (", dlerror(), ")");
			isLoaded = false;
		}
		#endif
	}
	return isLoaded;
}

std::shared_ptr<Proxy>
Runtime::createProxyHelper(const std::string &_domain, const std::string &_interface, const std::string &_instance,
						   const std::string &_connectionId) {
	std::lock_guard<std::mutex> itsLock(factoriesMutex_);
	for (auto factory : factories_) {
		std::shared_ptr<Proxy> proxy
			= factory.second->createProxy(_domain, _interface, _instance, _connectionId);
		if (proxy)
			return proxy;
	}
	return nullptr;
}

std::shared_ptr<Proxy>
Runtime::createProxyHelper(const std::string &_domain, const std::string &_interface, const std::string &_instance,
						   std::shared_ptr<MainLoopContext> _context ) {
	std::lock_guard<std::mutex> itsLock(factoriesMutex_);
	for (auto factory : factories_) {
		std::shared_ptr<Proxy> proxy
			= factory.second->createProxy(_domain, _interface, _instance, _context);
		if (proxy)
			return proxy;
	}
	return nullptr;
}

bool
Runtime::registerStubHelper(const std::string &_domain, const std::string &_interface, const std::string &_instance,
	  	  	  	  	  	    std::shared_ptr<StubBase> _stub, const std::string &_connectionId) {
	bool isRegistered(false);
	std::lock_guard<std::mutex> itsLock(factoriesMutex_);
	for (auto factory : factories_) {
		isRegistered = factory.second->registerStub(_domain, _interface, _instance, _stub, _connectionId);
	}
	return isRegistered;
}

bool
Runtime::registerStubHelper(const std::string &_domain, const std::string &_interface, const std::string &_instance,
	  	  	  	  	  	    std::shared_ptr<StubBase> _stub, std::shared_ptr<MainLoopContext> _context) {
	bool isRegistered(false);
	std::lock_guard<std::mutex> itsLock(factoriesMutex_);
	for (auto factory : factories_) {
		isRegistered = factory.second->registerStub(_domain, _interface, _instance, _stub, _context);
	}
	return isRegistered;
}

} //Namespace CommonAPI