ctkCmdLineModuleManager.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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 "ctkCmdLineModuleManager.h"
  16. #include "ctkCmdLineModuleBackend.h"
  17. #include "ctkCmdLineModuleFrontend.h"
  18. #include "ctkCmdLineModuleCache_p.h"
  19. #include "ctkCmdLineModuleFuture.h"
  20. #include "ctkCmdLineModuleXmlValidator.h"
  21. #include "ctkCmdLineModuleReference.h"
  22. #include "ctkCmdLineModuleReference_p.h"
  23. #include "ctkCmdLineModuleRunException.h"
  24. #include "ctkCmdLineModuleXmlException.h"
  25. #include "ctkCmdLineModuleTimeoutException.h"
  26. #include <ctkException.h>
  27. #include <QFileInfo>
  28. #include <QDir>
  29. #include <QStringList>
  30. #include <QBuffer>
  31. #include <QUrl>
  32. #include <QHash>
  33. #include <QList>
  34. #include <QMutex>
  35. #include <QDebug>
  36. #include <QFuture>
  37. #if (QT_VERSION < QT_VERSION_CHECK(4,7,0))
  38. extern int qHash(const QUrl& url);
  39. #endif
  40. //----------------------------------------------------------------------------
  41. struct ctkCmdLineModuleManagerPrivate
  42. {
  43. ctkCmdLineModuleManagerPrivate(ctkCmdLineModuleManager::ValidationMode mode, const QString& cacheDir)
  44. : ValidationMode(mode)
  45. {
  46. QFileInfo fileInfo(cacheDir);
  47. if (!fileInfo.exists())
  48. {
  49. if (!QDir().mkpath(cacheDir))
  50. {
  51. qWarning() << "Command line module cache disabled. Directory" << cacheDir << "could not be created.";
  52. return;
  53. }
  54. }
  55. if (fileInfo.isWritable())
  56. {
  57. ModuleCache.reset(new ctkCmdLineModuleCache(cacheDir));
  58. }
  59. else
  60. {
  61. qWarning() << "Command line module cache disabled. Directory" << cacheDir << "is not writable.";
  62. }
  63. }
  64. void checkBackends_unlocked(const QUrl& location)
  65. {
  66. if (!this->SchemeToBackend.contains(location.scheme()))
  67. {
  68. throw ctkInvalidArgumentException(QString("No suitable backend registered for module at ") + location.toString());
  69. }
  70. }
  71. QMutex Mutex;
  72. QHash<QString, ctkCmdLineModuleBackend*> SchemeToBackend;
  73. QHash<QUrl, ctkCmdLineModuleReference> LocationToRef;
  74. QScopedPointer<ctkCmdLineModuleCache> ModuleCache;
  75. ctkCmdLineModuleManager::ValidationMode ValidationMode;
  76. };
  77. //----------------------------------------------------------------------------
  78. ctkCmdLineModuleManager::ctkCmdLineModuleManager(ValidationMode validationMode, const QString& cacheDir)
  79. : d(new ctkCmdLineModuleManagerPrivate(validationMode, cacheDir))
  80. {
  81. }
  82. //----------------------------------------------------------------------------
  83. ctkCmdLineModuleManager::~ctkCmdLineModuleManager()
  84. {
  85. }
  86. //----------------------------------------------------------------------------
  87. ctkCmdLineModuleManager::ValidationMode ctkCmdLineModuleManager::validationMode() const
  88. {
  89. return d->ValidationMode;
  90. }
  91. //----------------------------------------------------------------------------
  92. void ctkCmdLineModuleManager::setValidationMode(const ValidationMode& mode)
  93. {
  94. d->ValidationMode = mode;
  95. }
  96. //----------------------------------------------------------------------------
  97. void ctkCmdLineModuleManager::registerBackend(ctkCmdLineModuleBackend *backend)
  98. {
  99. QMutexLocker lock(&d->Mutex);
  100. QList<QString> supportedSchemes = backend->schemes();
  101. // Check if there is already a backend registerd for any of the
  102. // supported schemes. We only supported one backend per scheme.
  103. foreach (QString scheme, supportedSchemes)
  104. {
  105. if (d->SchemeToBackend.contains(scheme))
  106. {
  107. throw ctkInvalidArgumentException(QString("A backend for scheme %1 is already registered.").arg(scheme));
  108. }
  109. }
  110. // All good
  111. foreach (QString scheme, supportedSchemes)
  112. {
  113. d->SchemeToBackend[scheme] = backend;
  114. }
  115. }
  116. //----------------------------------------------------------------------------
  117. void ctkCmdLineModuleManager::replaceBackend(ctkCmdLineModuleBackend* backend)
  118. {
  119. if (d->SchemeToBackend.size() == 0)
  120. {
  121. this->registerBackend(backend);
  122. }
  123. // Check if new backend has exactly matching list of schemes to an existing backend.
  124. ctkCmdLineModuleBackend* matchingBackend = NULL;
  125. QList<QString> supportedSchemes = backend->schemes();
  126. QList<ctkCmdLineModuleBackend*> existingBackends = d->SchemeToBackend.values();
  127. foreach (ctkCmdLineModuleBackend* existingBackend, existingBackends)
  128. {
  129. QList<QString> schemes = existingBackend->schemes();
  130. if (schemes == supportedSchemes)
  131. {
  132. matchingBackend = existingBackend;
  133. }
  134. }
  135. if (matchingBackend != NULL)
  136. {
  137. foreach (QString scheme, supportedSchemes)
  138. {
  139. d->SchemeToBackend[scheme] = backend;
  140. }
  141. }
  142. else
  143. {
  144. this->registerBackend(backend);
  145. }
  146. }
  147. //----------------------------------------------------------------------------
  148. ctkCmdLineModuleReference
  149. ctkCmdLineModuleManager::registerModule(const QUrl &location)
  150. {
  151. QByteArray xml;
  152. ctkCmdLineModuleBackend* backend = NULL;
  153. {
  154. QMutexLocker lock(&d->Mutex);
  155. d->checkBackends_unlocked(location);
  156. // If the module is already registered, just return the reference
  157. if (d->LocationToRef.contains(location))
  158. {
  159. return d->LocationToRef[location];
  160. }
  161. backend = d->SchemeToBackend[location.scheme()];
  162. }
  163. bool fromCache = false;
  164. qint64 newTimeStamp = 0;
  165. qint64 cacheTimeStamp = 0;
  166. if (d->ModuleCache)
  167. {
  168. newTimeStamp = backend->timeStamp(location);
  169. cacheTimeStamp = d->ModuleCache->timeStamp(location);
  170. if (cacheTimeStamp < 0 // i.e. timestamp is invalid
  171. || cacheTimeStamp < newTimeStamp) // i.e. timestamp is genuinely out of date
  172. {
  173. // newly fetch the XML description
  174. try
  175. {
  176. xml = backend->rawXmlDescription(location);
  177. }
  178. catch (const ctkCmdLineModuleTimeoutException& e)
  179. {
  180. qDebug() << "Extracting XML from " << location.toString() << " timed-out, with message:" << e.what();
  181. throw;
  182. }
  183. catch (...)
  184. {
  185. // cache the failed attempt
  186. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, QByteArray());
  187. throw;
  188. }
  189. }
  190. else
  191. {
  192. // use the cached XML description
  193. xml = d->ModuleCache->rawXmlDescription(location);
  194. fromCache = true;
  195. }
  196. }
  197. else
  198. {
  199. try
  200. {
  201. xml = backend->rawXmlDescription(location);
  202. }
  203. catch (const ctkCmdLineModuleRunException& e)
  204. {
  205. qDebug() << "Extracting XML from " << e.location().toString() << " failed with errorCode " << e.errorCode() << " and return string " << e.errorString();
  206. throw;
  207. }
  208. catch (const ctkException& e)
  209. {
  210. qDebug() << e.what();
  211. throw;
  212. }
  213. }
  214. if (xml.isEmpty())
  215. {
  216. if (!fromCache && d->ModuleCache)
  217. {
  218. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, QByteArray());
  219. }
  220. throw ctkInvalidArgumentException(QString("No XML output available from ") + location.toString());
  221. }
  222. ctkCmdLineModuleReference ref;
  223. ref.d->Location = location;
  224. ref.d->RawXmlDescription = xml;
  225. ref.d->Backend = backend;
  226. if (d->ValidationMode != SKIP_VALIDATION)
  227. {
  228. // validate the outputted xml description
  229. QBuffer input(&xml);
  230. input.open(QIODevice::ReadOnly);
  231. ctkCmdLineModuleXmlValidator validator(&input);
  232. if (!validator.validateInput())
  233. {
  234. if (d->ModuleCache)
  235. {
  236. // validation failed, cache the description anyway
  237. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, xml);
  238. }
  239. if (d->ValidationMode == STRICT_VALIDATION)
  240. {
  241. throw ctkInvalidArgumentException(QString("Validating module at %1 failed: %2")
  242. .arg(location.toString()).arg(validator.errorString()));
  243. }
  244. else
  245. {
  246. ref.d->XmlValidationErrorString = validator.errorString();
  247. }
  248. }
  249. else
  250. {
  251. if (d->ModuleCache && newTimeStamp > 0 && !fromCache)
  252. {
  253. // successfully validated the xml, cache it
  254. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, xml);
  255. }
  256. }
  257. }
  258. else
  259. {
  260. if (!fromCache && d->ModuleCache)
  261. {
  262. // cache it
  263. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, xml);
  264. }
  265. }
  266. {
  267. QMutexLocker lock(&d->Mutex);
  268. // Check that we don't have a race condition
  269. if (d->LocationToRef.contains(location))
  270. {
  271. // Another thread registered a module with the same location
  272. return d->LocationToRef[location];
  273. }
  274. d->LocationToRef[location] = ref;
  275. }
  276. emit moduleRegistered(ref);
  277. return ref;
  278. }
  279. //----------------------------------------------------------------------------
  280. void ctkCmdLineModuleManager::unregisterModule(const ctkCmdLineModuleReference& ref)
  281. {
  282. if (!ref) return;
  283. {
  284. QMutexLocker lock(&d->Mutex);
  285. if (!d->LocationToRef.contains(ref.location()))
  286. {
  287. return;
  288. }
  289. d->LocationToRef.remove(ref.location());
  290. if (d->ModuleCache)
  291. {
  292. d->ModuleCache->removeCacheEntry(ref.location());
  293. }
  294. }
  295. emit moduleUnregistered(ref);
  296. }
  297. //----------------------------------------------------------------------------
  298. void ctkCmdLineModuleManager::clearCache()
  299. {
  300. d->ModuleCache->clearCache();
  301. }
  302. //----------------------------------------------------------------------------
  303. void ctkCmdLineModuleManager::reloadModules()
  304. {
  305. foreach(const QUrl &location, d->LocationToRef.keys())
  306. {
  307. ctkCmdLineModuleReference ref = d->LocationToRef[location];
  308. this->unregisterModule(ref);
  309. this->registerModule(location);
  310. }
  311. }
  312. //----------------------------------------------------------------------------
  313. ctkCmdLineModuleReference ctkCmdLineModuleManager::moduleReference(const QUrl &location) const
  314. {
  315. QMutexLocker lock(&d->Mutex);
  316. QHash<QUrl, ctkCmdLineModuleReference>::const_iterator iter = d->LocationToRef.find(location);
  317. return (iter == d->LocationToRef.end()) ? ctkCmdLineModuleReference() : iter.value();
  318. }
  319. //----------------------------------------------------------------------------
  320. QList<ctkCmdLineModuleReference> ctkCmdLineModuleManager::moduleReferences() const
  321. {
  322. QMutexLocker lock(&d->Mutex);
  323. return d->LocationToRef.values();
  324. }
  325. //----------------------------------------------------------------------------
  326. ctkCmdLineModuleFuture ctkCmdLineModuleManager::run(ctkCmdLineModuleFrontend *frontend)
  327. {
  328. QMutexLocker lock(&d->Mutex);
  329. d->checkBackends_unlocked(frontend->location());
  330. ctkCmdLineModuleFuture future = d->SchemeToBackend[frontend->location().scheme()]->run(frontend);
  331. frontend->setFuture(future);
  332. emit frontend->started();
  333. return future;
  334. }