ctkPluginPrivate.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. /*=============================================================================
  2. Library: CTK
  3. Copyright (c) German Cancer Research Center,
  4. Division of Medical and Biological Informatics
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. =============================================================================*/
  15. #include "ctkPluginPrivate_p.h"
  16. #include "ctkPluginConstants.h"
  17. #include "ctkPluginDatabaseException.h"
  18. #include "ctkPluginArchive_p.h"
  19. #include "ctkPluginFrameworkContext_p.h"
  20. #include "ctkPluginFrameworkUtil_p.h"
  21. #include "ctkPluginActivator.h"
  22. #include "ctkPluginContext_p.h"
  23. #include "ctkServices_p.h"
  24. #include "ctkServiceReferencePrivate.h"
  25. #include "ctkServiceRegistration.h"
  26. const ctkPlugin::States ctkPluginPrivate::RESOLVED_FLAGS = ctkPlugin::RESOLVED | ctkPlugin::STARTING | ctkPlugin::ACTIVE | ctkPlugin::STOPPING;
  27. //----------------------------------------------------------------------------
  28. ctkPluginPrivate::ctkPluginPrivate(
  29. QWeakPointer<ctkPlugin> qq,
  30. ctkPluginFrameworkContext* fw,
  31. ctkPluginArchive* pa)
  32. : q_ptr(qq), fwCtx(fw), id(pa->getPluginId()),
  33. location(pa->getPluginLocation().toString()), state(ctkPlugin::INSTALLED),
  34. archive(pa), pluginContext(0), pluginActivator(0), pluginLoader(pa->getLibLocation()),
  35. eagerActivation(false), activating(false), deactivating(false)
  36. {
  37. //TODO
  38. //checkCertificates(pa);
  39. // Older gcc versions need to be told to make external symbols and RTTI information
  40. // available to other libraries when loading a library with dlopen
  41. pluginLoader.setLoadHints(QLibrary::ExportExternalSymbolsHint);
  42. checkManifestHeaders();
  43. pluginDir = fwCtx->getDataStorage(id);
  44. // int oldStartLevel = archive->getStartLevel();
  45. try
  46. {
  47. //TODO: StartLevel Service
  48. //if (fwCtx->startLevelController == 0)
  49. //{
  50. archive->setStartLevel(0);
  51. //}
  52. // else
  53. // {
  54. // if (oldStartLevel == -1)
  55. // {
  56. // archive->setStartLevel(fwCtx->startLevelController->getInitialPluginStartLevel());
  57. // }
  58. // }
  59. }
  60. catch (const std::exception& e)
  61. {
  62. qDebug() << "Failed to set start level on #" << id << ":" << e.what();
  63. }
  64. lastModified = archive->getLastModified();
  65. if (lastModified.isNull())
  66. {
  67. modified();
  68. }
  69. // fill require list
  70. QString requireString = archive->getAttribute(ctkPluginConstants::REQUIRE_PLUGIN);
  71. QList<QMap<QString, QStringList> > requireList = ctkPluginFrameworkUtil::parseEntries(ctkPluginConstants::REQUIRE_PLUGIN,
  72. requireString, true, true, false);
  73. QListIterator<QMap<QString, QStringList> > i(requireList);
  74. while (i.hasNext())
  75. {
  76. const QMap<QString, QStringList>& e = i.next();
  77. const QStringList& res = e.value(ctkPluginConstants::RESOLUTION_DIRECTIVE);
  78. const QStringList& version = e.value(ctkPluginConstants::PLUGIN_VERSION_ATTRIBUTE);
  79. ctkRequirePlugin* rp = new ctkRequirePlugin(this, e.value("$key").front(),
  80. res.empty() ? QString() : res.front(),
  81. version.empty() ? QString() : version.front());
  82. require.push_back(rp);
  83. }
  84. }
  85. //----------------------------------------------------------------------------
  86. ctkPluginPrivate::ctkPluginPrivate(QWeakPointer<ctkPlugin> qq,
  87. ctkPluginFrameworkContext* fw,
  88. long id, const QString& loc, const QString& sym, const ctkVersion& ver)
  89. : q_ptr(qq), fwCtx(fw), id(id), location(loc), symbolicName(sym), version(ver),
  90. state(ctkPlugin::INSTALLED), archive(0), pluginContext(0),
  91. pluginActivator(0), eagerActivation(false), activating(false),
  92. deactivating(false)
  93. {
  94. modified();
  95. }
  96. //----------------------------------------------------------------------------
  97. ctkPluginPrivate::~ctkPluginPrivate()
  98. {
  99. qDeleteAll(require);
  100. delete archive;
  101. }
  102. //----------------------------------------------------------------------------
  103. ctkPlugin::State ctkPluginPrivate::getUpdatedState()
  104. {
  105. if (state & ctkPlugin::INSTALLED)
  106. {
  107. try
  108. {
  109. if (state == ctkPlugin::INSTALLED)
  110. {
  111. fwCtx->resolvePlugin(this);
  112. state = ctkPlugin::RESOLVED;
  113. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::RESOLVED, this->q_func()));
  114. }
  115. }
  116. catch (const ctkPluginException& pe)
  117. {
  118. this->fwCtx->listeners.frameworkError(this->q_func(), pe);
  119. throw;
  120. }
  121. }
  122. return state;
  123. }
  124. //----------------------------------------------------------------------------
  125. QFileInfo ctkPluginPrivate::getDataRoot()
  126. {
  127. return pluginDir;
  128. }
  129. //----------------------------------------------------------------------------
  130. void ctkPluginPrivate::setAutostartSetting(const ctkPlugin::StartOptions& setting) {
  131. try
  132. {
  133. if (archive)
  134. {
  135. archive->setAutostartSetting(setting);
  136. }
  137. }
  138. catch (const ctkPluginDatabaseException& e)
  139. {
  140. this->fwCtx->listeners.frameworkError(this->q_func(), e);
  141. }
  142. }
  143. //----------------------------------------------------------------------------
  144. void ctkPluginPrivate::ignoreAutostartSetting()
  145. {
  146. try
  147. {
  148. if (archive)
  149. {
  150. archive->setAutostartSetting(-1);
  151. }
  152. }
  153. catch (const ctkPluginDatabaseException& e)
  154. {
  155. this->fwCtx->listeners.frameworkError(this->q_func(), e);
  156. }
  157. }
  158. //----------------------------------------------------------------------------
  159. void ctkPluginPrivate::modified()
  160. {
  161. lastModified = QDateTime::currentDateTime();
  162. if (archive)
  163. {
  164. archive->setLastModified(lastModified);
  165. }
  166. }
  167. //----------------------------------------------------------------------------
  168. void ctkPluginPrivate::checkManifestHeaders()
  169. {
  170. symbolicName = archive->getAttribute(ctkPluginConstants::PLUGIN_SYMBOLICNAME);
  171. if (symbolicName.isEmpty())
  172. {
  173. throw std::invalid_argument(std::string("ctkPlugin has no symbolic name, location=") +
  174. qPrintable(location));
  175. }
  176. QString mpv = archive->getAttribute(ctkPluginConstants::PLUGIN_VERSION);
  177. if (!mpv.isEmpty())
  178. {
  179. try
  180. {
  181. version = ctkVersion(mpv);
  182. }
  183. catch (const std::exception& e)
  184. {
  185. throw std::invalid_argument(std::string("ctkPlugin does not specify a valid ") +
  186. qPrintable(ctkPluginConstants::PLUGIN_VERSION) + " header. Got exception: " + e.what());
  187. }
  188. }
  189. QString ap = archive->getAttribute(ctkPluginConstants::PLUGIN_ACTIVATIONPOLICY);
  190. if (ctkPluginConstants::ACTIVATION_EAGER == ap)
  191. {
  192. eagerActivation = true;
  193. }
  194. }
  195. //----------------------------------------------------------------------------
  196. void ctkPluginPrivate::finalizeActivation()
  197. {
  198. switch (getUpdatedState())
  199. {
  200. case ctkPlugin::INSTALLED:
  201. // we shouldn't be here, getUpdatedState should have thrown
  202. // an exception during resolving the plugin
  203. throw ctkPluginException("Internal error: expected exception on plugin resolve not thrown!");
  204. case ctkPlugin::STARTING:
  205. if (activating) return; // finalization already in progress.
  206. // Lazy activation; fall through to RESOLVED.
  207. case ctkPlugin::RESOLVED:
  208. //6:
  209. state = ctkPlugin::STARTING;
  210. activating = true;
  211. qDebug() << "activating #" << this->id;
  212. //7:
  213. if (!pluginContext)
  214. {
  215. pluginContext.reset(new ctkPluginContext(this));
  216. }
  217. try
  218. {
  219. // start dependencies
  220. startDependencies();
  221. //TODO maybe call this in its own thread
  222. start0();
  223. }
  224. catch (...)
  225. {
  226. //8:
  227. state = ctkPlugin::STOPPING;
  228. // NYI, call outside lock
  229. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, this->q_func()));
  230. removePluginResources();
  231. pluginContext.reset();
  232. state = ctkPlugin::RESOLVED;
  233. // NYI, call outside lock
  234. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, this->q_func()));
  235. activating = false;
  236. throw;
  237. }
  238. activating = false;
  239. break;
  240. case ctkPlugin::ACTIVE:
  241. break;
  242. case ctkPlugin::STOPPING:
  243. // This happens if start is called from inside the ctkPluginActivator::stop method.
  244. // Don't allow it.
  245. throw ctkPluginException("start called from ctkPluginActivator::stop",
  246. ctkPluginException::ACTIVATOR_ERROR);
  247. case ctkPlugin::UNINSTALLED:
  248. throw std::logic_error("ctkPlugin is in UNINSTALLED state");
  249. }
  250. }
  251. //----------------------------------------------------------------------------
  252. void ctkPluginPrivate::stop0(bool wasStarted)
  253. {
  254. //5:
  255. state = ctkPlugin::STOPPING;
  256. deactivating = true;
  257. //6-13:
  258. ctkPluginActivator* activator = 0;
  259. const std::exception* savedException = 0;
  260. try
  261. {
  262. //6:
  263. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, q_func()));
  264. //7:
  265. if (wasStarted && pluginActivator)
  266. {
  267. try
  268. {
  269. pluginActivator->stop(pluginContext.data());
  270. }
  271. catch (const std::exception& e)
  272. {
  273. savedException = new ctkPluginException("ctkPlugin::stop: PluginActivator stop failed",
  274. ctkPluginException::ACTIVATOR_ERROR, &e);
  275. }
  276. if (state == ctkPlugin::UNINSTALLED)
  277. {
  278. throw std::logic_error("Plugin is uninstalled");
  279. }
  280. activator = pluginActivator;
  281. pluginActivator = 0;
  282. }
  283. // Call hooks after we've called PluginActivator::stop(), but before we've cleared all resources
  284. // TODO service listener hooks
  285. //fwCtx->listeners.serviceListeners.hooksBundleStopped(this);
  286. if (pluginContext)
  287. {
  288. pluginContext->d_func()->invalidate();
  289. pluginContext.reset();
  290. }
  291. //8-10:
  292. removePluginResources();
  293. }
  294. catch (const std::exception* exc)
  295. {
  296. savedException = exc;
  297. }
  298. delete activator;
  299. if (state != ctkPlugin::UNINSTALLED)
  300. {
  301. state = ctkPlugin::RESOLVED;
  302. deactivating = false;
  303. //fwCtx.packages.notifyAll();
  304. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, q_func()));
  305. }
  306. if (savedException)
  307. {
  308. throw savedException;
  309. }
  310. }
  311. //----------------------------------------------------------------------------
  312. QStringList ctkPluginPrivate::findResourceEntries(const QString& path,
  313. const QString& pattern, bool recurse) const
  314. {
  315. QStringList result;
  316. QStringList resources = archive->findResourcesPath(path);
  317. foreach(QString fp, resources)
  318. {
  319. QString lastComponentOfPath = fp.section('/', -1);
  320. bool isDirectory = fp.endsWith("/");
  321. if (!isDirectory &&
  322. (pattern.isNull() || ctkPluginFrameworkUtil::filterMatch(pattern, lastComponentOfPath)))
  323. {
  324. result << (path + fp);
  325. }
  326. if (isDirectory && recurse)
  327. {
  328. QStringList subResources = findResourceEntries(fp, pattern, recurse);
  329. foreach (QString subResource, subResources)
  330. {
  331. result << (path + subResource);
  332. }
  333. }
  334. }
  335. return result;
  336. }
  337. //----------------------------------------------------------------------------
  338. void ctkPluginPrivate::startDependencies()
  339. {
  340. QListIterator<ctkRequirePlugin*> i(this->require);
  341. while (i.hasNext())
  342. {
  343. ctkRequirePlugin* pr = i.next();
  344. QList<ctkPlugin*> pl = fwCtx->plugins->getPlugins(pr->name, pr->pluginRange);
  345. if (pl.isEmpty())
  346. {
  347. if (pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY)
  348. {
  349. // We should never get here, since the plugin can only be
  350. // started if all its dependencies could be resolved.
  351. throw ctkPluginException(
  352. QString("Internal error: dependent plugin %1 inside version range %2 is not installed.").
  353. arg(pr->name).arg(pr->pluginRange.toString()));
  354. }
  355. else
  356. {
  357. continue;
  358. }
  359. }
  360. // We take the first plugin in the list (highest version number)
  361. // Immediately start the dependencies (no lazy activation) but do not
  362. // change the autostart setting of the plugin.
  363. pl.front()->start(ctkPlugin::START_TRANSIENT);
  364. }
  365. }
  366. //----------------------------------------------------------------------------
  367. void ctkPluginPrivate::start0()
  368. {
  369. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTING, this->q_func()));
  370. try {
  371. pluginLoader.load();
  372. if (!pluginLoader.isLoaded())
  373. {
  374. throw ctkPluginException(QString("Loading plugin %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  375. ctkPluginException::ACTIVATOR_ERROR);
  376. }
  377. pluginActivator = qobject_cast<ctkPluginActivator*>(pluginLoader.instance());
  378. if (!pluginActivator)
  379. {
  380. throw ctkPluginException(QString("Creating ctkPluginActivator instance from %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  381. ctkPluginException::ACTIVATOR_ERROR);
  382. }
  383. pluginActivator->start(pluginContext.data());
  384. if (ctkPlugin::UNINSTALLED == state)
  385. {
  386. throw ctkPluginException("ctkPlugin uninstalled during start()", ctkPluginException::STATECHANGE_ERROR);
  387. }
  388. state = ctkPlugin::ACTIVE;
  389. }
  390. catch (const std::exception& e)
  391. {
  392. throw ctkPluginException("ctkPlugin start failed", ctkPluginException::ACTIVATOR_ERROR, &e);
  393. }
  394. qDebug() << "activating #" << id << "completed.";
  395. //10:
  396. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTED, this->q_func()));
  397. }
  398. //----------------------------------------------------------------------------
  399. void ctkPluginPrivate::removePluginResources()
  400. {
  401. // automatic disconnect due to Qt signal slot
  402. //fwCtx->listeners.removeAllListeners(this);
  403. QList<ctkServiceRegistration> srs = fwCtx->services->getRegisteredByPlugin(this);
  404. QMutableListIterator<ctkServiceRegistration> i(srs);
  405. while (i.hasNext())
  406. {
  407. try
  408. {
  409. i.next().unregister();
  410. }
  411. catch (const std::logic_error& /*ignore*/)
  412. {
  413. // Someone has unregistered the service after stop completed.
  414. // This should not occur, but we don't want get stuck in
  415. // an illegal state so we catch it.
  416. }
  417. }
  418. QList<ctkServiceRegistration> s = fwCtx->services->getUsedByPlugin(q_func());
  419. QListIterator<ctkServiceRegistration> i2(s);
  420. while (i2.hasNext())
  421. {
  422. i2.next().getReference().d_func()->ungetService(q_func(), false);
  423. }
  424. }