ctkCmdLineModuleManager.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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::setXmlTimeout(int xmlTimeout)
  101. {
  102. d->XmlTimeOut = xmlTimeout;
  103. }
  104. //----------------------------------------------------------------------------
  105. int ctkCmdLineModuleManager::xmlTimeout() 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. if (d->ModuleCache)
  180. {
  181. newTimeStamp = backend->timeStamp(location);
  182. cacheTimeStamp = d->ModuleCache->timeStamp(location);
  183. if (cacheTimeStamp < 0 // i.e. timestamp is invalid
  184. || cacheTimeStamp < newTimeStamp) // i.e. timestamp is genuinely out of date
  185. {
  186. // newly fetch the XML description
  187. try
  188. {
  189. xml = backend->rawXmlDescription(location, d->XmlTimeOut);
  190. }
  191. catch (const ctkCmdLineModuleTimeoutException&)
  192. {
  193. // in case of a time-out, do not cache it as a failed attempt
  194. // by recording an empty QByteArray in the cache
  195. throw;
  196. }
  197. catch (...)
  198. {
  199. // cache the failed attempt
  200. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, QByteArray());
  201. throw;
  202. }
  203. }
  204. else
  205. {
  206. // use the cached XML description
  207. xml = d->ModuleCache->rawXmlDescription(location);
  208. fromCache = true;
  209. }
  210. }
  211. else
  212. {
  213. try
  214. {
  215. xml = backend->rawXmlDescription(location);
  216. }
  217. catch (const ctkCmdLineModuleRunException& e)
  218. {
  219. qDebug() << "Extracting XML from " << e.location().toString() << " failed with errorCode " << e.errorCode() << " and return string " << e.errorString();
  220. throw;
  221. }
  222. catch (const ctkException& e)
  223. {
  224. qDebug() << e.what();
  225. throw;
  226. }
  227. }
  228. if (xml.isEmpty())
  229. {
  230. if (!fromCache && d->ModuleCache)
  231. {
  232. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, QByteArray());
  233. }
  234. throw ctkInvalidArgumentException(QString("No XML output available from ") + location.toString());
  235. }
  236. ctkCmdLineModuleReference ref;
  237. ref.d->Location = location;
  238. ref.d->RawXmlDescription = xml;
  239. ref.d->Backend = backend;
  240. if (d->ValidationMode != SKIP_VALIDATION)
  241. {
  242. // validate the outputted xml description
  243. QBuffer input(&xml);
  244. input.open(QIODevice::ReadOnly);
  245. ctkCmdLineModuleXmlValidator validator(&input);
  246. if (!validator.validateInput())
  247. {
  248. if (d->ModuleCache)
  249. {
  250. // validation failed, cache the description anyway
  251. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, xml);
  252. }
  253. if (d->ValidationMode == STRICT_VALIDATION)
  254. {
  255. throw ctkInvalidArgumentException(QString("Validating module at %1 failed: %2")
  256. .arg(location.toString()).arg(validator.errorString()));
  257. }
  258. else
  259. {
  260. ref.d->XmlValidationErrorString = validator.errorString();
  261. }
  262. }
  263. else
  264. {
  265. if (d->ModuleCache && newTimeStamp > 0 && !fromCache)
  266. {
  267. // successfully validated the xml, cache it
  268. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, xml);
  269. }
  270. }
  271. }
  272. else
  273. {
  274. if (!fromCache && d->ModuleCache)
  275. {
  276. // cache it
  277. d->ModuleCache->cacheXmlDescription(location, newTimeStamp, xml);
  278. }
  279. }
  280. {
  281. QMutexLocker lock(&d->Mutex);
  282. // Check that we don't have a race condition
  283. if (d->LocationToRef.contains(location))
  284. {
  285. // Another thread registered a module with the same location
  286. return d->LocationToRef[location];
  287. }
  288. d->LocationToRef[location] = ref;
  289. }
  290. emit moduleRegistered(ref);
  291. return ref;
  292. }
  293. //----------------------------------------------------------------------------
  294. void ctkCmdLineModuleManager::unregisterModule(const ctkCmdLineModuleReference& ref)
  295. {
  296. if (!ref) return;
  297. {
  298. QMutexLocker lock(&d->Mutex);
  299. if (!d->LocationToRef.contains(ref.location()))
  300. {
  301. return;
  302. }
  303. d->LocationToRef.remove(ref.location());
  304. if (d->ModuleCache)
  305. {
  306. d->ModuleCache->removeCacheEntry(ref.location());
  307. }
  308. }
  309. emit moduleUnregistered(ref);
  310. }
  311. //----------------------------------------------------------------------------
  312. void ctkCmdLineModuleManager::clearCache()
  313. {
  314. d->ModuleCache->clearCache();
  315. }
  316. //----------------------------------------------------------------------------
  317. ctkCmdLineModuleReference ctkCmdLineModuleManager::moduleReference(const QUrl &location) const
  318. {
  319. QMutexLocker lock(&d->Mutex);
  320. QHash<QUrl, ctkCmdLineModuleReference>::const_iterator iter = d->LocationToRef.find(location);
  321. return (iter == d->LocationToRef.end()) ? ctkCmdLineModuleReference() : iter.value();
  322. }
  323. //----------------------------------------------------------------------------
  324. QList<ctkCmdLineModuleReference> ctkCmdLineModuleManager::moduleReferences() const
  325. {
  326. QMutexLocker lock(&d->Mutex);
  327. return d->LocationToRef.values();
  328. }
  329. //----------------------------------------------------------------------------
  330. ctkCmdLineModuleFuture ctkCmdLineModuleManager::run(ctkCmdLineModuleFrontend *frontend)
  331. {
  332. QMutexLocker lock(&d->Mutex);
  333. d->checkBackends_unlocked(frontend->location());
  334. ctkCmdLineModuleFuture future = d->SchemeToBackend[frontend->location().scheme()]->run(frontend);
  335. frontend->setFuture(future);
  336. emit frontend->started();
  337. return future;
  338. }