ctkPluginPrivate.cpp 12 KB

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