ctkPluginPrivate.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. QSharedPointer<ctkPlugin> snp = fwCtx->plugins->getPlugin(symbolicName, version);
  197. // TBD! Should we allow update to same version?
  198. if (!snp.isNull() && snp->d_func() != this)
  199. {
  200. throw std::invalid_argument(std::string("Plugin with same symbolic name and version is already installed (")
  201. + symbolicName.toStdString() + ", " + version.toString().toStdString() + ")");
  202. }
  203. QString ap = archive->getAttribute(ctkPluginConstants::PLUGIN_ACTIVATIONPOLICY);
  204. if (ctkPluginConstants::ACTIVATION_EAGER == ap)
  205. {
  206. eagerActivation = true;
  207. }
  208. }
  209. //----------------------------------------------------------------------------
  210. void ctkPluginPrivate::finalizeActivation()
  211. {
  212. switch (getUpdatedState())
  213. {
  214. case ctkPlugin::INSTALLED:
  215. // we shouldn't be here, getUpdatedState should have thrown
  216. // an exception during resolving the plugin
  217. throw ctkPluginException("Internal error: expected exception on plugin resolve not thrown!");
  218. case ctkPlugin::STARTING:
  219. if (activating) return; // finalization already in progress.
  220. // Lazy activation; fall through to RESOLVED.
  221. case ctkPlugin::RESOLVED:
  222. //6:
  223. state = ctkPlugin::STARTING;
  224. activating = true;
  225. qDebug() << "activating #" << this->id;
  226. //7:
  227. if (!pluginContext)
  228. {
  229. pluginContext.reset(new ctkPluginContext(this));
  230. }
  231. try
  232. {
  233. // start dependencies
  234. startDependencies();
  235. //TODO maybe call this in its own thread
  236. start0();
  237. }
  238. catch (...)
  239. {
  240. //8:
  241. state = ctkPlugin::STOPPING;
  242. // NYI, call outside lock
  243. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, this->q_func()));
  244. removePluginResources();
  245. pluginContext.reset();
  246. state = ctkPlugin::RESOLVED;
  247. // NYI, call outside lock
  248. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, this->q_func()));
  249. activating = false;
  250. throw;
  251. }
  252. activating = false;
  253. break;
  254. case ctkPlugin::ACTIVE:
  255. break;
  256. case ctkPlugin::STOPPING:
  257. // This happens if start is called from inside the ctkPluginActivator::stop method.
  258. // Don't allow it.
  259. throw ctkPluginException("start called from ctkPluginActivator::stop",
  260. ctkPluginException::ACTIVATOR_ERROR);
  261. case ctkPlugin::UNINSTALLED:
  262. throw std::logic_error("ctkPlugin is in UNINSTALLED state");
  263. }
  264. }
  265. //----------------------------------------------------------------------------
  266. void ctkPluginPrivate::stop0(bool wasStarted)
  267. {
  268. //5:
  269. state = ctkPlugin::STOPPING;
  270. deactivating = true;
  271. //6-13:
  272. ctkPluginActivator* activator = 0;
  273. const std::exception* savedException = 0;
  274. try
  275. {
  276. //6:
  277. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPING, q_func()));
  278. //7:
  279. if (wasStarted && pluginActivator)
  280. {
  281. try
  282. {
  283. pluginActivator->stop(pluginContext.data());
  284. }
  285. catch (const std::exception& e)
  286. {
  287. savedException = new ctkPluginException("ctkPlugin::stop: PluginActivator stop failed",
  288. ctkPluginException::ACTIVATOR_ERROR, &e);
  289. }
  290. if (state == ctkPlugin::UNINSTALLED)
  291. {
  292. throw std::logic_error("Plugin is uninstalled");
  293. }
  294. activator = pluginActivator;
  295. pluginActivator = 0;
  296. }
  297. // Call hooks after we've called PluginActivator::stop(), but before we've cleared all resources
  298. // TODO service listener hooks
  299. //fwCtx->listeners.serviceListeners.hooksBundleStopped(this);
  300. if (pluginContext)
  301. {
  302. pluginContext->d_func()->invalidate();
  303. pluginContext.reset();
  304. }
  305. //8-10:
  306. removePluginResources();
  307. }
  308. catch (const std::exception* exc)
  309. {
  310. savedException = exc;
  311. }
  312. delete activator;
  313. if (state != ctkPlugin::UNINSTALLED)
  314. {
  315. state = ctkPlugin::RESOLVED;
  316. deactivating = false;
  317. //fwCtx.packages.notifyAll();
  318. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STOPPED, q_func()));
  319. }
  320. if (savedException)
  321. {
  322. throw savedException;
  323. }
  324. }
  325. //----------------------------------------------------------------------------
  326. QStringList ctkPluginPrivate::findResourceEntries(const QString& path,
  327. const QString& pattern, bool recurse) const
  328. {
  329. QStringList result;
  330. QStringList resources = archive->findResourcesPath(path);
  331. foreach(QString fp, resources)
  332. {
  333. QString lastComponentOfPath = fp.section('/', -1);
  334. bool isDirectory = fp.endsWith("/");
  335. if (!isDirectory &&
  336. (pattern.isNull() || ctkPluginFrameworkUtil::filterMatch(pattern, lastComponentOfPath)))
  337. {
  338. result << (path + fp);
  339. }
  340. if (isDirectory && recurse)
  341. {
  342. QStringList subResources = findResourceEntries(fp, pattern, recurse);
  343. foreach (QString subResource, subResources)
  344. {
  345. result << (path + subResource);
  346. }
  347. }
  348. }
  349. return result;
  350. }
  351. //----------------------------------------------------------------------------
  352. void ctkPluginPrivate::startDependencies()
  353. {
  354. QListIterator<ctkRequirePlugin*> i(this->require);
  355. while (i.hasNext())
  356. {
  357. ctkRequirePlugin* pr = i.next();
  358. QList<ctkPlugin*> pl = fwCtx->plugins->getPlugins(pr->name, pr->pluginRange);
  359. if (pl.isEmpty())
  360. {
  361. if (pr->resolution == ctkPluginConstants::RESOLUTION_MANDATORY)
  362. {
  363. // We should never get here, since the plugin can only be
  364. // started if all its dependencies could be resolved.
  365. throw ctkPluginException(
  366. QString("Internal error: dependent plugin %1 inside version range %2 is not installed.").
  367. arg(pr->name).arg(pr->pluginRange.toString()));
  368. }
  369. else
  370. {
  371. continue;
  372. }
  373. }
  374. // We take the first plugin in the list (highest version number)
  375. // Immediately start the dependencies (no lazy activation) but do not
  376. // change the autostart setting of the plugin.
  377. pl.front()->start(ctkPlugin::START_TRANSIENT);
  378. }
  379. }
  380. //----------------------------------------------------------------------------
  381. void ctkPluginPrivate::start0()
  382. {
  383. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTING, this->q_func()));
  384. try {
  385. pluginLoader.load();
  386. if (!pluginLoader.isLoaded())
  387. {
  388. throw ctkPluginException(QString("Loading plugin %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  389. ctkPluginException::ACTIVATOR_ERROR);
  390. }
  391. pluginActivator = qobject_cast<ctkPluginActivator*>(pluginLoader.instance());
  392. if (!pluginActivator)
  393. {
  394. throw ctkPluginException(QString("Creating ctkPluginActivator instance from %1 failed: %2").arg(pluginLoader.fileName()).arg(pluginLoader.errorString()),
  395. ctkPluginException::ACTIVATOR_ERROR);
  396. }
  397. pluginActivator->start(pluginContext.data());
  398. if (ctkPlugin::UNINSTALLED == state)
  399. {
  400. throw ctkPluginException("ctkPlugin uninstalled during start()", ctkPluginException::STATECHANGE_ERROR);
  401. }
  402. state = ctkPlugin::ACTIVE;
  403. }
  404. catch (const std::exception& e)
  405. {
  406. throw ctkPluginException("ctkPlugin start failed", ctkPluginException::ACTIVATOR_ERROR, &e);
  407. }
  408. qDebug() << "activating #" << id << "completed.";
  409. //10:
  410. fwCtx->listeners.emitPluginChanged(ctkPluginEvent(ctkPluginEvent::STARTED, this->q_func()));
  411. }
  412. //----------------------------------------------------------------------------
  413. void ctkPluginPrivate::removePluginResources()
  414. {
  415. // automatic disconnect due to Qt signal slot
  416. //fwCtx->listeners.removeAllListeners(this);
  417. QList<ctkServiceRegistration> srs = fwCtx->services->getRegisteredByPlugin(this);
  418. QMutableListIterator<ctkServiceRegistration> i(srs);
  419. while (i.hasNext())
  420. {
  421. try
  422. {
  423. i.next().unregister();
  424. }
  425. catch (const std::logic_error& /*ignore*/)
  426. {
  427. // Someone has unregistered the service after stop completed.
  428. // This should not occur, but we don't want get stuck in
  429. // an illegal state so we catch it.
  430. }
  431. }
  432. QList<ctkServiceRegistration> s = fwCtx->services->getUsedByPlugin(q_func());
  433. QListIterator<ctkServiceRegistration> i2(s);
  434. while (i2.hasNext())
  435. {
  436. i2.next().getReference().d_func()->ungetService(q_func(), false);
  437. }
  438. }