ctkCmdLineModuleManager.cpp 11 KB

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