ctkPluginPrivate.cpp 15 KB

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