ctkCmdLineModuleManager.cpp 9.9 KB

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