swift
Loading...
Searching...
No Matches
backgrounddataupdater.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2017 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QElapsedTimer>
7
8#include "core/application.h"
12#include "misc/eventloop.h"
13#include "misc/logmessage.h"
15#include "misc/threadutils.h"
16
17using namespace swift::misc;
18using namespace swift::misc::network;
19using namespace swift::misc::simulation;
20using namespace swift::misc::simulation::data;
21using namespace swift::core;
22using namespace swift::core::db;
23
24namespace swift::core::db
25{
32
34 : CContinuousWorker(owner, "Background data updater"), m_updateTimer(this, "Background data updater")
35 {
36 connect(&m_updateTimer, &misc::CThreadedTimer::timeout, this, &CBackgroundDataUpdater::doWork);
37 if (sApp && sApp->hasWebDataServices())
38 {
39 connect(sApp->getWebDataServices()->getDatabaseWriter(), &CDatabaseWriter::publishedModelsSimplified, this,
40 &CBackgroundDataUpdater::onModelsPublished, Qt::QueuedConnection);
41 }
42 }
43
45 {
46 QReadLocker l(&m_lockMsg);
47 return m_messageHistory;
48 }
49
50 void CBackgroundDataUpdater::startUpdating(std::chrono::milliseconds ms)
51 {
52 Q_ASSERT_X(this->hasStarted(), Q_FUNC_INFO, "Worker not started yet");
53 m_updateTimer.startTimer(ms);
54 }
55
56 void CBackgroundDataUpdater::doWork()
57 {
58 if (!this->doWorkCheck())
59 {
60 return;
61 }
62 if (m_inWork)
63 {
64 return;
65 }
66 m_inWork = true;
67
68 emit this->consolidating(true);
69 int cycle = m_cycle;
70 this->addHistory(CLogMessage(this).info(u"Background consolidation cycle %1") << cycle);
71
72 switch (cycle)
73 {
74 case 0:
75 // normally redundant, will be read in other places as well
76 // new metadata for next comparison
77 this->addHistory(CLogMessage(this).info(u"Triggered info reads from DB"));
78 this->triggerInfoReads();
79 break;
80 case 1:
81 this->addHistory(CLogMessage(this).info(u"Synchronize DB entities"));
82 this->syncDbEntity(CEntityFlags::AirlineIcaoEntity);
83 this->syncDbEntity(CEntityFlags::LiveryEntity);
84 this->syncDbEntity(CEntityFlags::ModelEntity);
85 this->syncDbEntity(CEntityFlags::DistributorEntity);
86 this->syncDbEntity(CEntityFlags::AircraftIcaoEntity);
87 break;
88 case 2:
89 this->addHistory(CLogMessage(this).info(u"Synchronize %1") << this->modelCaches(true).getDescription());
90 this->syncModelOrModelSetCacheWithDbData(true); // set
91 break;
92 case 3:
93 this->addHistory(CLogMessage(this).info(u"Synchronize %1") << this->modelCaches(false).getDescription());
94 this->syncModelOrModelSetCacheWithDbData(false);
95 break;
96 default: break;
97 }
98
99 ++cycle %= 4;
100 m_cycle = cycle;
101 m_inWork = false;
102 emit this->consolidating(false);
103 }
104
105 void CBackgroundDataUpdater::triggerInfoReads()
106 {
107 if (!this->doWorkCheck())
108 {
109 return;
110 }
113 }
114
115 void CBackgroundDataUpdater::syncModelOrModelSetCacheWithDbData(bool modelSetFlag,
116 const CAircraftModelList &dbModelsConsidered)
117 {
118 if (!this->doWorkCheck())
119 {
120 return;
121 }
122 IMultiSimulatorModelCaches &modelCaches = this->modelCaches(modelSetFlag);
123 const QDateTime latestDbModelsTs =
125 dbModelsConsidered.latestTimestamp();
126 if (!latestDbModelsTs.isValid())
127 {
128 return;
129 }
130
131 // newer DB models as cache
132 const QDateTime dbModelsLatestSync = m_syncedModelsLatestChange.value(modelCaches.getDescription());
133 if (dbModelsLatestSync.isValid() && latestDbModelsTs <= dbModelsLatestSync)
134 {
135 return;
136 }
137
138 const QString description = modelCaches.getDescription();
139 m_syncedModelsLatestChange[description] = latestDbModelsTs;
140 const CSimulatorInfo simulators = modelCaches.simulatorsWithInitializedCache(); // simulators ever used
141 if (simulators.isNoSimulator())
142 {
143 return;
144 }
145
146 const CAircraftModelList dbModels =
147 dbModelsConsidered.isEmpty() ? sApp->getWebDataServices()->getModels() : dbModelsConsidered;
148 if (dbModels.isEmpty())
149 {
150 return;
151 }
152 const QSet<CSimulatorInfo> simulatorsSet = simulators.asSingleSimulatorSet();
153 QElapsedTimer time;
154 for (const CSimulatorInfo &singleSimulator : simulatorsSet)
155 {
156 if (!this->doWorkCheck())
157 {
158 return;
159 }
160 CAircraftModelList simulatorModels = modelCaches.getSynchronizedCachedModels(singleSimulator);
161 if (simulatorModels.isEmpty())
162 {
163 continue;
164 }
165 time.restart();
166 const CAircraftModelList dbModelsForSimulator = dbModels.matchesSimulator(singleSimulator);
167 if (dbModelsForSimulator.isEmpty())
168 {
169 continue;
170 }
171
172 // time consuming part
173 const int c = CDatabaseUtils::consolidateModelsWithDbData(dbModelsForSimulator, simulatorModels, true);
174 if (c > 0)
175 {
176 const CStatusMessage m = modelCaches.setCachedModels(simulatorModels, singleSimulator);
177 const qint64 msElapsed = time.elapsed();
178 this->addHistory(CLogMessage(this).info(u"Consolidated %1 models (%2) for '%3' in %4ms")
179 << c << description << singleSimulator.convertToQString() << msElapsed);
181 this->addHistory(m);
182 }
183 else
184 {
185 this->addHistory(CLogMessage(this).info(u"Synchronized, no changes for '%1'")
186 << singleSimulator.convertToQString());
187 }
188
189 if (simulatorsSet.size() > 1)
190 {
191 // just give the system some time to relax, consolidation is time consuming
192 if (!this->doWorkCheck())
193 {
194 return;
195 }
196 CEventLoop eventLoop(this);
197 eventLoop.exec(1000);
198 }
199 }
200 }
201
202 void CBackgroundDataUpdater::syncDbEntity(CEntityFlags::Entity entity)
203 {
204 if (!this->doWorkCheck())
205 {
206 return;
207 }
208 const QDateTime latestCacheTs = sApp->getWebDataServices()->getCacheTimestamp(entity);
209 if (!latestCacheTs.isValid())
210 {
211 return;
212 }
213
214 const QDateTime latestDbTs = sApp->getWebDataServices()->getLatestDbEntityTimestamp(entity);
215 const QString entityStr = CEntityFlags::entitiesToString(entity);
216 const QString latestCacheTsStr = latestCacheTs.toString(Qt::ISODate);
217
218 if (!latestDbTs.isValid())
219 {
220 return;
221 }
222 if (latestDbTs <= latestCacheTs)
223 {
224 this->addHistory(
225 CLogMessage(this).info(
226 u"Background updater (%1), no auto synchronization with DB, entity '%2', DB ts: %3 cache ts: %4")
227 << CThreadUtils::currentThreadInfo() << entityStr << latestDbTs.toString(Qt::ISODate)
228 << latestCacheTsStr);
229 return;
230 }
231
232 this->addHistory(CLogMessage(this).info(u"Background updater (%1) triggering read of '%2' since '%3'")
233 << CThreadUtils::currentThreadInfo() << entityStr << latestCacheTsStr);
234 sApp->getWebDataServices()->triggerLoadingDirectlyFromDb(entity, latestCacheTs);
235 }
236
237 bool CBackgroundDataUpdater::doWorkCheck() const
238 {
240 {
241 return false;
242 }
243 if (!this->isEnabled())
244 {
245 return false;
246 }
247 return true;
248 }
249
250 void CBackgroundDataUpdater::onModelsPublished(const CAircraftModelList &modelsPublished, bool directWrite)
251 {
252 if (!this->doWorkCheck())
253 {
254 return;
255 }
256 if (modelsPublished.isEmpty())
257 {
258 return;
259 }
260 if (!m_updatePublishedModels)
261 {
262 return;
263 }
264 if (!directWrite)
265 {
266 return;
267 } // those models are CRs and have to be released first
268 if (m_inWork)
269 {
270 return;
271 } // no 2 updates at the same time
272
273 emit this->consolidating(true);
274 this->syncModelOrModelSetCacheWithDbData(true, modelsPublished);
275 this->syncModelOrModelSetCacheWithDbData(false, modelsPublished);
276 emit this->consolidating(false);
277 }
278
279 IMultiSimulatorModelCaches &CBackgroundDataUpdater::modelCaches(bool modelSetFlag)
280 {
281 if (modelSetFlag)
282 {
283 return m_modelSets;
284 }
285 return m_modelCaches;
286 }
287
288 void CBackgroundDataUpdater::addHistory(const CStatusMessage &msg)
289 {
290 QWriteLocker l(&m_lockMsg);
291 m_messageHistory.push_frontMaxElements(msg, 100); // latest
292 }
293} // namespace swift::core::db
SWIFT_CORE_EXPORT swift::core::CApplication * sApp
Single instance of application object.
bool hasWebDataServices() const
Web data services available?
bool isShuttingDown() const
Is application shutting down?
CWebDataServices * getWebDataServices() const
Get the web data services.
QDateTime getLatestDbEntityTimestamp(swift::misc::network::CEntityFlags::Entity entity) const
Corresponding DB timestamp if applicable.
swift::misc::simulation::CAircraftModelList getModels() const
Models.
QDateTime getCacheTimestamp(swift::misc::network::CEntityFlags::Entity entity) const
Corresponding cache timestamp if applicable.
swift::misc::network::CEntityFlags::Entity triggerLoadingDirectlyFromDb(swift::misc::network::CEntityFlags::Entity whatToRead, const QDateTime &newerThan=QDateTime())
Trigger reload from DB, loads the DB data and bypasses the caches checks and info objects.
void triggerReadOfSharedInfoObjects()
Trigger read of shared info objects.
void triggerReadOfDbInfoObjects()
Trigger read of DB info objects.
void consolidating(bool running)
Consolidation.
CBackgroundDataUpdater(QObject *owner)
Constructor.
swift::misc::CStatusMessageList getMessageHistory() const
The message history.
static const QStringList & getLogCategories()
Log categories.
void startUpdating(std::chrono::milliseconds ms)
Start the updating timer.
static int consolidateModelsWithDbData(swift::misc::simulation::CAircraftModelList &models, bool force)
Consolidate models with DB data.
void publishedModelsSimplified(const swift::misc::simulation::CAircraftModelList &modelsPublished, bool directWrite)
Published models, simplified version of publishedModels.
bool isEnabled() const
Enabled (running)?
Definition worker.h:346
const QObject * owner() const
Owner of the worker.
Definition worker.h:352
CContinuousWorker(QObject *owner, const QString &name)
Constructor.
Definition worker.cpp:168
static const QString & modelCache()
Model cache.
static const QString & worker()
Background task.
static const QString & modelSetCache()
Model set cache.
Class for emitting a log message.
Definition logmessage.h:27
static void preformatted(const CStatusMessage &statusMessage)
Sends a verbatim, preformatted message to the log.
bool isEmpty() const
Synonym for empty.
Definition sequence.h:285
Status messages, e.g. from Core -> GUI.
static QString currentThreadInfo()
Info about current thread, for debug messages.
void timeout()
Timer timed out.
bool hasStarted() const
True if the worker has started.
Definition worker.h:200
QDateTime latestTimestamp() const
Latest timestamp.
@ AirlineIcaoEntity
ICAO codes for airlines.
Definition entityflags.h:31
@ AircraftIcaoEntity
ICAO codes for aircraft.
Definition entityflags.h:30
static QString entitiesToString(CEntityFlags::Entity entities, const QString &separator=", ")
Entities to string list.
CAircraftModelList matchesSimulator(const CSimulatorInfo &simulator) const
Find for given simulator.
QSet< CSimulatorInfo > asSingleSimulatorSet() const
As a set of single simulator info objects.
bool isNoSimulator() const
No simulator?
Classes interacting with the swift database (aka "datastore").
Backend services of the swift project, like dealing with the network or the simulators.
Definition actionbind.cpp:7
Free functions in swift::misc.
bool isValid() const const
QString toString(QStringView format) const const
qint64 elapsed() const const
qint64 restart()
QObject(QObject *parent)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
QueuedConnection