owncloudpropagator.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /*
  2. * Copyright (C) by Olivier Goffart <ogoffart@owncloud.com>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  11. * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  12. * for more details.
  13. */
  14. #ifndef OWNCLOUDPROPAGATOR_H
  15. #define OWNCLOUDPROPAGATOR_H
  16. #include <QHash>
  17. #include <QObject>
  18. #include <QMap>
  19. #include <QLinkedList>
  20. #include <QElapsedTimer>
  21. #include <QTimer>
  22. #include <QPointer>
  23. #include <QIODevice>
  24. #include <QMutex>
  25. #include "syncfileitem.h"
  26. #include "syncjournaldb.h"
  27. #include "bandwidthmanager.h"
  28. #include "accountfwd.h"
  29. namespace OCC {
  30. /** Free disk space threshold below which syncs will abort and not even start.
  31. */
  32. qint64 criticalFreeSpaceLimit();
  33. /** The client will not intentionally reduce the available free disk space below
  34. * this limit.
  35. *
  36. * Uploads will still run and downloads that are small enough will continue too.
  37. */
  38. qint64 freeSpaceLimit();
  39. class SyncJournalDb;
  40. class OwncloudPropagator;
  41. /**
  42. * @brief the base class of propagator jobs
  43. *
  44. * This can either be a job, or a container for jobs.
  45. * If it is a composite job, it then inherits from PropagateDirectory
  46. *
  47. * @ingroup libsync
  48. */
  49. class PropagatorJob : public QObject {
  50. Q_OBJECT
  51. public:
  52. explicit PropagatorJob(OwncloudPropagator* propagator);
  53. enum JobState {
  54. NotYetStarted,
  55. Running,
  56. Finished
  57. };
  58. JobState _state;
  59. enum JobParallelism {
  60. /** Jobs can be run in parallel to this job */
  61. FullParallelism,
  62. /** No other job shall be started until this one has finished.
  63. So this job is guaranteed to finish before any jobs below it
  64. are executed. */
  65. WaitForFinished,
  66. };
  67. virtual JobParallelism parallelism() { return FullParallelism; }
  68. /**
  69. * For "small" jobs
  70. */
  71. virtual bool isLikelyFinishedQuickly() { return false; }
  72. /** The space that the running jobs need to complete but don't actually use yet.
  73. *
  74. * Note that this does *not* include the disk space that's already
  75. * in use by running jobs for things like a download-in-progress.
  76. */
  77. virtual qint64 committedDiskSpace() const { return 0; }
  78. public slots:
  79. virtual void abort() {}
  80. /** Starts this job, or a new subjob
  81. * returns true if a job was started.
  82. */
  83. virtual bool scheduleSelfOrChild() = 0;
  84. signals:
  85. /**
  86. * Emitted when the job is fully finished
  87. */
  88. void finished(SyncFileItem::Status);
  89. protected:
  90. OwncloudPropagator *propagator() const;
  91. };
  92. /*
  93. * Abstract class to propagate a single item
  94. */
  95. class PropagateItemJob : public PropagatorJob {
  96. Q_OBJECT
  97. protected:
  98. void done(SyncFileItem::Status status, const QString &errorString = QString());
  99. bool checkForProblemsWithShared(int httpStatusCode, const QString& msg);
  100. /*
  101. * set a custom restore job message that is used if the restore job succeeded.
  102. * It is displayed in the activity view.
  103. */
  104. QString restoreJobMsg() const {
  105. return _item->_isRestoration ? _item->_errorString : QString();
  106. }
  107. void setRestoreJobMsg( const QString& msg = QString() ) {
  108. _item->_isRestoration = true;
  109. _item->_errorString = msg;
  110. }
  111. protected slots:
  112. void slotRestoreJobFinished(SyncFileItem::Status status);
  113. private:
  114. QScopedPointer<PropagateItemJob> _restoreJob;
  115. public:
  116. PropagateItemJob(OwncloudPropagator* propagator, const SyncFileItemPtr &item)
  117. : PropagatorJob(propagator), _item(item) {}
  118. bool scheduleSelfOrChild() Q_DECL_OVERRIDE {
  119. if (_state != NotYetStarted) {
  120. return false;
  121. }
  122. _state = Running;
  123. QMetaObject::invokeMethod(this, "start"); // We could be in a different thread (neon jobs)
  124. return true;
  125. }
  126. SyncFileItemPtr _item;
  127. public slots:
  128. virtual void start() = 0;
  129. };
  130. /**
  131. * @brief Job that runs subjobs. It becomes finished only when all subjobs are finished.
  132. * @ingroup libsync
  133. */
  134. class PropagatorCompositeJob : public PropagatorJob {
  135. Q_OBJECT
  136. public:
  137. QVector<PropagatorJob *> _jobsToDo;
  138. SyncFileItemVector _tasksToDo;
  139. QVector<PropagatorJob *> _runningJobs;
  140. SyncFileItem::Status _hasError; // NoStatus, or NormalError / SoftError if there was an error
  141. explicit PropagatorCompositeJob(OwncloudPropagator *propagator)
  142. : PropagatorJob(propagator)
  143. , _hasError(SyncFileItem::NoStatus)
  144. { }
  145. virtual ~PropagatorCompositeJob() {
  146. qDeleteAll(_jobsToDo);
  147. qDeleteAll(_runningJobs);
  148. }
  149. void appendJob(PropagatorJob *job) {
  150. _jobsToDo.append(job);
  151. }
  152. void appendTask(const SyncFileItemPtr &item) {
  153. _tasksToDo.append(item);
  154. }
  155. virtual bool scheduleSelfOrChild() Q_DECL_OVERRIDE;
  156. virtual JobParallelism parallelism() Q_DECL_OVERRIDE;
  157. virtual void abort() Q_DECL_OVERRIDE {
  158. foreach (PropagatorJob *j, _runningJobs)
  159. j->abort();
  160. }
  161. qint64 committedDiskSpace() const Q_DECL_OVERRIDE;
  162. private slots:
  163. bool possiblyRunNextJob(PropagatorJob *next) {
  164. if (next->_state == NotYetStarted) {
  165. connect(next, SIGNAL(finished(SyncFileItem::Status)), this, SLOT(slotSubJobFinished(SyncFileItem::Status)));
  166. }
  167. return next->scheduleSelfOrChild();
  168. }
  169. void slotSubJobFinished(SyncFileItem::Status status);
  170. void finalize();
  171. };
  172. /**
  173. * @brief Propagate a directory, and all its sub entries.
  174. * @ingroup libsync
  175. */
  176. class OWNCLOUDSYNC_EXPORT PropagateDirectory : public PropagatorJob {
  177. Q_OBJECT
  178. public:
  179. SyncFileItemPtr _item;
  180. // e.g: create the directory
  181. QScopedPointer<PropagateItemJob>_firstJob;
  182. PropagatorCompositeJob _subJobs;
  183. explicit PropagateDirectory(OwncloudPropagator *propagator, const SyncFileItemPtr &item = SyncFileItemPtr(new SyncFileItem));
  184. void appendJob(PropagatorJob *job) {
  185. _subJobs.appendJob(job);
  186. }
  187. void appendTask(const SyncFileItemPtr &item) {
  188. _subJobs.appendTask(item);
  189. }
  190. virtual bool scheduleSelfOrChild() Q_DECL_OVERRIDE;
  191. virtual JobParallelism parallelism() Q_DECL_OVERRIDE;
  192. virtual void abort() Q_DECL_OVERRIDE {
  193. if (_firstJob)
  194. _firstJob->abort();
  195. _subJobs.abort();
  196. }
  197. void increaseAffectedCount() {
  198. _firstJob->_item->_affectedItems++;
  199. }
  200. qint64 committedDiskSpace() const Q_DECL_OVERRIDE {
  201. return _subJobs.committedDiskSpace();
  202. }
  203. private slots:
  204. void slotFirstJobFinished(SyncFileItem::Status status);
  205. void slotSubJobsFinished(SyncFileItem::Status status);
  206. };
  207. /**
  208. * @brief Dummy job that just mark it as completed and ignored
  209. * @ingroup libsync
  210. */
  211. class PropagateIgnoreJob : public PropagateItemJob {
  212. Q_OBJECT
  213. public:
  214. PropagateIgnoreJob(OwncloudPropagator* propagator,const SyncFileItemPtr& item)
  215. : PropagateItemJob(propagator, item) {}
  216. void start() Q_DECL_OVERRIDE {
  217. SyncFileItem::Status status = _item->_status;
  218. done(status == SyncFileItem::NoStatus ? SyncFileItem::FileIgnored : status, _item->_errorString);
  219. }
  220. };
  221. class OwncloudPropagator : public QObject {
  222. Q_OBJECT
  223. QScopedPointer<PropagateDirectory> _rootJob;
  224. public:
  225. const QString _localDir; // absolute path to the local directory. ends with '/'
  226. const QString _remoteFolder; // remote folder, ends with '/'
  227. SyncJournalDb * const _journal;
  228. bool _finishedEmited; // used to ensure that finished is only emitted once
  229. public:
  230. OwncloudPropagator(AccountPtr account, const QString &localDir,
  231. const QString &remoteFolder, SyncJournalDb *progressDb)
  232. : _localDir((localDir.endsWith(QChar('/'))) ? localDir : localDir+'/' )
  233. , _remoteFolder((remoteFolder.endsWith(QChar('/'))) ? remoteFolder : remoteFolder+'/' )
  234. , _journal(progressDb)
  235. , _finishedEmited(false)
  236. , _bandwidthManager(this)
  237. , _anotherSyncNeeded(false)
  238. , _account(account)
  239. { }
  240. ~OwncloudPropagator();
  241. void start(const SyncFileItemVector &_syncedItems);
  242. QAtomicInt _downloadLimit;
  243. QAtomicInt _uploadLimit;
  244. BandwidthManager _bandwidthManager;
  245. QAtomicInt _abortRequested; // boolean set by the main thread to abort.
  246. /** The list of currently active jobs.
  247. This list contains the jobs that are currently using ressources and is used purely to
  248. know how many jobs there is currently running for the scheduler.
  249. Jobs add themself to the list when they do an assynchronous operation.
  250. Jobs can be several time on the list (example, when several chunks are uploaded in parallel)
  251. */
  252. QList<PropagateItemJob*> _activeJobList;
  253. /** We detected that another sync is required after this one */
  254. bool _anotherSyncNeeded;
  255. /* the maximum number of jobs using bandwidth (uploads or downloads, in parallel) */
  256. int maximumActiveTransferJob();
  257. /* The maximum number of active jobs in parallel */
  258. int hardMaximumActiveJob();
  259. bool isInSharedDirectory(const QString& file);
  260. bool localFileNameClash(const QString& relfile);
  261. QString getFilePath(const QString& tmp_file_name) const;
  262. PropagateItemJob *createJob(const SyncFileItemPtr& item);
  263. void scheduleNextJob();
  264. void reportProgress(const SyncFileItem&, quint64 bytes);
  265. void abort() {
  266. _abortRequested.fetchAndStoreOrdered(true);
  267. if (_rootJob) {
  268. // We're possibly already in an item's finished stack
  269. QMetaObject::invokeMethod(_rootJob.data(), "abort", Qt::QueuedConnection);
  270. }
  271. // abort() of all jobs will likely have already resulted in finished being emitted, but just in case.
  272. QMetaObject::invokeMethod(this, "emitFinished", Qt::QueuedConnection, Q_ARG(SyncFileItem::Status, SyncFileItem::NormalError));
  273. }
  274. // timeout in seconds
  275. static int httpTimeout();
  276. /** returns the size of chunks in bytes */
  277. static quint64 chunkSize();
  278. AccountPtr account() const;
  279. enum DiskSpaceResult
  280. {
  281. DiskSpaceOk,
  282. DiskSpaceFailure,
  283. DiskSpaceCritical
  284. };
  285. /** Checks whether there's enough disk space available to complete
  286. * all jobs that are currently running.
  287. */
  288. DiskSpaceResult diskSpaceCheck() const;
  289. private slots:
  290. /** Emit the finished signal and make sure it is only emitted once */
  291. void emitFinished(SyncFileItem::Status status) {
  292. if (!_finishedEmited)
  293. emit finished(status == SyncFileItem::Success);
  294. _finishedEmited = true;
  295. }
  296. void scheduleNextJobImpl();
  297. signals:
  298. void itemCompleted(const SyncFileItemPtr &);
  299. void progress(const SyncFileItem&, quint64 bytes);
  300. void finished(bool success);
  301. /** Emitted when propagation has problems with a locked file. */
  302. void seenLockedFile(const QString &fileName);
  303. /** Emitted when propagation touches a file.
  304. *
  305. * Used to track our own file modifications such that notifications
  306. * from the file watcher about these can be ignored.
  307. */
  308. void touchedFile(const QString &fileName);
  309. private:
  310. AccountPtr _account;
  311. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  312. // access to signals which are protected in Qt4
  313. friend class PropagateDownloadFile;
  314. friend class PropagateItemJob;
  315. friend class PropagateLocalMkdir;
  316. friend class PropagateLocalRename;
  317. friend class PropagateRemoteMove;
  318. friend class PropagateUploadFileV1;
  319. friend class PropagateUploadFileNG;
  320. #endif
  321. };
  322. /**
  323. * @brief Job that wait for all the poll jobs to be completed
  324. * @ingroup libsync
  325. */
  326. class CleanupPollsJob : public QObject {
  327. Q_OBJECT
  328. QVector< SyncJournalDb::PollInfo > _pollInfos;
  329. AccountPtr _account;
  330. SyncJournalDb *_journal;
  331. QString _localPath;
  332. public:
  333. explicit CleanupPollsJob(const QVector< SyncJournalDb::PollInfo > &pollInfos, AccountPtr account,
  334. SyncJournalDb *journal, const QString &localPath, QObject* parent = 0)
  335. : QObject(parent), _pollInfos(pollInfos), _account(account), _journal(journal), _localPath(localPath) {}
  336. ~CleanupPollsJob();
  337. /**
  338. * Start the job. After the job is completed, it will emit either finished or aborted, and it
  339. * will destroy itself.
  340. */
  341. void start();
  342. signals:
  343. void finished();
  344. void aborted(const QString &error);
  345. private slots:
  346. void slotPollFinished();
  347. };
  348. }
  349. #endif