ctkCmdLineModuleManager.cpp 11 KB

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