ctkCmdLineModuleManager.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. void ctkCmdLineModuleManager::replaceBackend(ctkCmdLineModuleBackend* backend)
  131. {
  132. if (d->SchemeToBackend.size() == 0)
  133. {
  134. this->registerBackend(backend);
  135. }
  136. // Check if new backend has exactly matching list of schemes to an existing backend.
  137. ctkCmdLineModuleBackend* matchingBackend = NULL;
  138. QList<QString> supportedSchemes = backend->schemes();
  139. QList<ctkCmdLineModuleBackend*> existingBackends = d->SchemeToBackend.values();
  140. foreach (ctkCmdLineModuleBackend* existingBackend, existingBackends)
  141. {
  142. QList<QString> schemes = existingBackend->schemes();
  143. if (schemes == supportedSchemes)
  144. {
  145. matchingBackend = existingBackend;
  146. }
  147. }
  148. if (matchingBackend != NULL)
  149. {
  150. foreach (QString scheme, supportedSchemes)
  151. {
  152. d->SchemeToBackend[scheme] = backend;
  153. }
  154. }
  155. else
  156. {
  157. this->registerBackend(backend);
  158. }
  159. }
  160. //----------------------------------------------------------------------------
  161. ctkCmdLineModuleReference
  162. ctkCmdLineModuleManager::registerModule(const QUrl &location)
  163. {
  164. QByteArray xml;
  165. ctkCmdLineModuleBackend* backend = NULL;
  166. {
  167. QMutexLocker lock(&d->Mutex);
  168. d->checkBackends_unlocked(location);
  169. // If the module is already registered, just return the reference
  170. if (d->LocationToRef.contains(location))
  171. {
  172. return d->LocationToRef[location];
  173. }
  174. backend = d->SchemeToBackend[location.scheme()];
  175. }
  176. bool fromCache = false;
  177. qint64 newTimeStamp = 0;
  178. qint64 cacheTimeStamp = 0;
  179. int timeout = backend->timeOutForXmlRetrieval();
  180. if (timeout == 0)
  181. {
  182. timeout = d->XmlTimeOut;
  183. }
  184. if (d->ModuleCache)
  185. {
  186. newTimeStamp = backend->timeStamp(location);
  187. cacheTimeStamp = d->ModuleCache->timeStamp(location);
  188. if (cacheTimeStamp < 0 // i.e. timestamp is invalid
  189. || cacheTimeStamp < newTimeStamp) // i.e. timestamp is genuinely out of date
  190. {
  191. // newly fetch the XML description
  192. try
  193. {
  194. xml = backend->rawXmlDescription(location, timeout);
  195. }
  196. catch (const ctkCmdLineModuleTimeoutException&)
  197. {
  198. // in case of a time-out, do not cache it as a failed attempt
  199. // by recording an empty QByteArray in the cache
  200. throw;
  201. }
  202. catch (...)
  203. {
  204. // cache the failed attempt
  205. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, QByteArray());
  206. throw;
  207. }
  208. }
  209. else
  210. {
  211. // use the cached XML description
  212. xml = d->ModuleCache->rawXmlDescription(location);
  213. fromCache = true;
  214. }
  215. }
  216. else
  217. {
  218. try
  219. {
  220. xml = backend->rawXmlDescription(location, timeout);
  221. }
  222. catch (const ctkCmdLineModuleRunException& e)
  223. {
  224. qDebug() << "Extracting XML from " << e.location().toString() << " failed with errorCode " << e.errorCode() << " and return string " << e.errorString();
  225. throw;
  226. }
  227. catch (const ctkException& e)
  228. {
  229. qDebug() << e.what();
  230. throw;
  231. }
  232. }
  233. if (xml.isEmpty())
  234. {
  235. if (!fromCache && d->ModuleCache)
  236. {
  237. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, QByteArray());
  238. }
  239. throw ctkInvalidArgumentException(QString("No XML output available from ") + location.toString());
  240. }
  241. ctkCmdLineModuleReference ref;
  242. ref.d->Location = location;
  243. ref.d->RawXmlDescription = xml;
  244. ref.d->Backend = backend;
  245. if (d->ValidationMode != SKIP_VALIDATION)
  246. {
  247. // validate the outputted xml description
  248. QBuffer input(&xml);
  249. input.open(QIODevice::ReadOnly);
  250. ctkCmdLineModuleXmlValidator validator(&input);
  251. if (!validator.validateInput())
  252. {
  253. if (d->ModuleCache)
  254. {
  255. // validation failed, cache the description anyway
  256. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, xml);
  257. }
  258. if (d->ValidationMode == STRICT_VALIDATION)
  259. {
  260. throw ctkInvalidArgumentException(QString("Validating module at %1 failed: %2")
  261. .arg(location.toString()).arg(validator.errorString()));
  262. }
  263. else
  264. {
  265. ref.d->XmlValidationErrorString = validator.errorString();
  266. }
  267. }
  268. else
  269. {
  270. if (d->ModuleCache && newTimeStamp > 0 && !fromCache)
  271. {
  272. // successfully validated the xml, cache it
  273. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, xml);
  274. }
  275. }
  276. }
  277. else
  278. {
  279. if (!fromCache && d->ModuleCache)
  280. {
  281. // cache it
  282. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, xml);
  283. }
  284. }
  285. {
  286. QMutexLocker lock(&d->Mutex);
  287. // Check that we don't have a race condition
  288. if (d->LocationToRef.contains(location))
  289. {
  290. // Another thread registered a module with the same location
  291. return d->LocationToRef[location];
  292. }
  293. d->LocationToRef[location] = ref;
  294. }
  295. emit moduleRegistered(ref);
  296. return ref;
  297. }
  298. //----------------------------------------------------------------------------
  299. void ctkCmdLineModuleManager::unregisterModule(const ctkCmdLineModuleReference& ref)
  300. {
  301. if (!ref) return;
  302. {
  303. QMutexLocker lock(&d->Mutex);
  304. if (!d->LocationToRef.contains(ref.location()))
  305. {
  306. return;
  307. }
  308. d->LocationToRef.remove(ref.location());
  309. if (d->ModuleCache)
  310. {
  311. d->ModuleCache->removeCacheEntry(ref.location());
  312. }
  313. }
  314. emit moduleUnregistered(ref);
  315. }
  316. //----------------------------------------------------------------------------
  317. void ctkCmdLineModuleManager::clearCache()
  318. {
  319. d->ModuleCache->clearCache();
  320. }
  321. //----------------------------------------------------------------------------
  322. ctkCmdLineModuleReference ctkCmdLineModuleManager::moduleReference(const QUrl &location) const
  323. {
  324. QMutexLocker lock(&d->Mutex);
  325. QHash<QUrl, ctkCmdLineModuleReference>::const_iterator iter = d->LocationToRef.find(location);
  326. return (iter == d->LocationToRef.end()) ? ctkCmdLineModuleReference() : iter.value();
  327. }
  328. //----------------------------------------------------------------------------
  329. QList<ctkCmdLineModuleReference> ctkCmdLineModuleManager::moduleReferences() const
  330. {
  331. QMutexLocker lock(&d->Mutex);
  332. return d->LocationToRef.values();
  333. }
  334. //----------------------------------------------------------------------------
  335. ctkCmdLineModuleFuture ctkCmdLineModuleManager::run(ctkCmdLineModuleFrontend *frontend)
  336. {
  337. QMutexLocker lock(&d->Mutex);
  338. d->checkBackends_unlocked(frontend->location());
  339. ctkCmdLineModuleFuture future = d->SchemeToBackend[frontend->location().scheme()]->run(frontend);
  340. frontend->setFuture(future);
  341. emit frontend->started();
  342. return future;
  343. }