-
Notifications
You must be signed in to change notification settings - Fork 355
/
Copy pathmythcorecontext.cpp
2130 lines (1800 loc) · 59.5 KB
/
mythcorecontext.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Qt
#include <QtGlobal>
#include <QCoreApplication>
#include <QUrl>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <QMutex>
#include <QRunnable>
#include <QWaitCondition>
#include <QAbstractSocket>
#include <QHostAddress>
#include <QHostInfo>
#include <QNetworkInterface>
#include <QNetworkAddressEntry>
#include <QLocale>
#include <QPair>
#include <QDateTime>
// Std
#include <algorithm>
#include <cmath>
#include <cstdarg>
#include <queue>
#include <unistd.h> // for usleep()
#ifdef _WIN32
#include <winsock2.h>
#else
#include <clocale>
#include <utility>
#endif
// MythTV
#include "compat.h"
#include "mythdownloadmanager.h"
#include "mythcorecontext.h"
#include "mythsocket.h"
#include "mythsystemlegacy.h"
#include "mthreadpool.h"
#include "exitcodes.h"
#include "mythlogging.h"
#include "mythversion.h"
#include "logging.h"
#include "mthread.h"
#include "serverpool.h"
#include "mythdate.h"
#include "mythplugin.h"
#include "mythmiscutil.h"
#include "mythpower.h"
#define LOC QString("MythCoreContext::%1(): ").arg(__func__)
MythCoreContext *gCoreContext = nullptr;
class MythCoreContextPrivate : public QObject
{
public:
MythCoreContextPrivate(MythCoreContext *lparent, QString binversion,
QObject *guicontext);
~MythCoreContextPrivate() override;
bool WaitForWOL(std::chrono::milliseconds timeout = std::chrono::milliseconds::max());
public:
MythCoreContext *m_parent { nullptr };
QObject *m_guiContext { nullptr };
QObject *m_guiObject { nullptr };
QString m_appBinaryVersion;
QMutex m_localHostLock; ///< Locking for m_localHostname
QString m_localHostname; ///< hostname from config.xml or gethostname()
QMutex m_masterHostLock; ///< Locking for m_masterHostname
QString m_masterHostname; ///< master backend hostname
QMutex m_scopesLock; ///< Locking for m_masterHostname
QMap<QString, QString> m_scopes;///< Scope Id cache for Link-Local addresses
QMutex m_sockLock; ///< protects both m_serverSock and m_eventSock
MythSocket *m_serverSock { nullptr }; ///< socket for sending MythProto requests
MythSocket *m_eventSock { nullptr }; ///< socket events arrive on
QMutex m_wolInProgressLock;
QWaitCondition m_wolInProgressWaitCondition;
bool m_wolInProgress { false };
bool m_isWOLAllowed { true };
bool m_backend { false };
bool m_frontend { false };
MythDB *m_database { nullptr };
QThread *m_uiThread { nullptr };
MythLocale *m_locale { nullptr };
QString m_language;
MythScheduler *m_scheduler { nullptr };
bool m_blockingClient { true };
QMap<QObject *, MythCoreContext::PlaybackStartCb> m_playbackClients;
QMutex m_playbackLock;
bool m_inwanting { false };
bool m_intvwanting { false };
bool m_announcedProtocol { false };
MythPluginManager *m_pluginmanager { nullptr };
bool m_isexiting { false };
QMap<QString, QPair<int64_t, uint64_t> > m_fileswritten;
QMutex m_fileslock;
MythSessionManager *m_sessionManager { nullptr };
QList<QHostAddress> m_approvedIps;
QList<QHostAddress> m_deniedIps;
MythPower *m_power { nullptr };
};
MythCoreContextPrivate::MythCoreContextPrivate(MythCoreContext *lparent,
QString binversion,
QObject *guicontext)
: m_parent(lparent),
m_guiContext(guicontext),
m_appBinaryVersion(std::move(binversion)),
m_database(GetMythDB()),
m_uiThread(QThread::currentThread())
{
MThread::ThreadSetup("CoreContext");
}
static void delete_sock(
#if QT_VERSION < QT_VERSION_CHECK(6,0,0)
QMutexLocker &locker,
#else
QMutexLocker<QMutex> &locker,
#endif
MythSocket **s)
{
if (*s)
{
MythSocket *tmp = *s;
*s = nullptr;
locker.unlock();
tmp->DecrRef();
locker.relock();
}
}
MythCoreContextPrivate::~MythCoreContextPrivate()
{
if (m_power)
MythPower::AcquireRelease(this, false);
MThreadPool::StopAllPools();
{
QMutexLocker locker(&m_sockLock);
delete_sock(locker, &m_serverSock);
delete_sock(locker, &m_eventSock);
}
delete m_locale;
delete m_sessionManager;
MThreadPool::ShutdownAllPools();
ShutdownMythSystemLegacy();
ShutdownMythDownloadManager();
// This has already been run in the MythContext dtor. Do we need it here
// too?
#if 0
logStop(); // need to shutdown db logger before we kill db
#endif
MThread::Cleanup();
GetMythDB()->GetDBManager()->CloseDatabases();
if (m_database) {
DestroyMythDB();
m_database = nullptr;
}
loggingDeregisterThread();
}
/// If another thread has already started WOL process, wait on them...
///
/// Note: Caller must be holding m_WOLInProgressLock.
bool MythCoreContextPrivate::WaitForWOL(std::chrono::milliseconds timeout)
{
std::chrono::milliseconds timeout_remaining = timeout;
while (m_wolInProgress && (timeout_remaining > 0ms))
{
LOG(VB_GENERAL, LOG_INFO, LOC + "Wake-On-LAN in progress, waiting...");
std::chrono::milliseconds max_wait = std::min(1000ms, timeout_remaining);
m_wolInProgressWaitCondition.wait(&m_wolInProgressLock, max_wait.count());
timeout_remaining -= max_wait;
}
return !m_wolInProgress;
}
MythCoreContext::MythCoreContext(const QString &binversion,
QObject *guiContext)
{
d = new MythCoreContextPrivate(this, binversion, guiContext);
}
bool MythCoreContext::Init(void)
{
if (!d)
{
LOG(VB_GENERAL, LOG_EMERG, LOC + "Out-of-memory");
return false;
}
if (d->m_appBinaryVersion != MYTH_BINARY_VERSION)
{
LOG(VB_GENERAL, LOG_CRIT,
QString("Application binary version (%1) does not "
"match libraries (%2)")
.arg(d->m_appBinaryVersion, MYTH_BINARY_VERSION));
QString warning = tr("This application is not compatible with the "
"installed MythTV libraries. Please recompile "
"after a make distclean");
LOG(VB_GENERAL, LOG_WARNING, warning);
return false;
}
#ifndef _WIN32
QString lang_variables("");
QString lc_value = setlocale(LC_CTYPE, nullptr);
if (lc_value.isEmpty())
{
// try fallback to environment variables for non-glibc systems
// LC_ALL, then LC_CTYPE
lc_value = qEnvironmentVariable("LC_ALL");
if (lc_value.isEmpty())
lc_value = qEnvironmentVariable("LC_CTYPE");
}
if (!lc_value.contains("UTF-8", Qt::CaseInsensitive))
lang_variables.append("LC_ALL or LC_CTYPE");
lc_value = qEnvironmentVariable("LANG");
if (!lc_value.contains("UTF-8", Qt::CaseInsensitive))
{
if (!lang_variables.isEmpty())
lang_variables.append(", and ");
lang_variables.append("LANG");
}
LOG(VB_GENERAL, LOG_INFO, QString("Assumed character encoding: %1")
.arg(lc_value));
if (!lang_variables.isEmpty())
{
LOG(VB_GENERAL, LOG_WARNING, QString("This application expects to "
"be running a locale that specifies a UTF-8 codeset, and many "
"features may behave improperly with your current language "
"settings. Please set the %1 variable(s) in the environment "
"in which this program is executed to include a UTF-8 codeset "
"(such as 'en_US.UTF-8').").arg(lang_variables));
}
#endif
return true;
}
MythCoreContext::~MythCoreContext()
{
delete d;
d = nullptr;
}
void MythCoreContext::setTestIntSettings(QMap<QString,int> &overrides)
{
m_testOverrideInts = std::move(overrides);
}
void MythCoreContext::setTestFloatSettings(QMap<QString,double> &overrides)
{
m_testOverrideFloats = std::move(overrides);
}
void MythCoreContext::setTestStringSettings(QMap<QString,QString> &overrides)
{
m_testOverrideStrings = std::move(overrides);
}
bool MythCoreContext::SetupCommandSocket(MythSocket *serverSock,
const QString &announcement,
[[maybe_unused]] std::chrono::milliseconds timeout,
bool &proto_mismatch)
{
proto_mismatch = false;
#ifndef IGNORE_PROTO_VER_MISMATCH
if (!CheckProtoVersion(serverSock, timeout, true))
{
proto_mismatch = true;
return false;
}
#endif
QStringList strlist(announcement);
if (!serverSock->WriteStringList(strlist))
{
LOG(VB_GENERAL, LOG_ERR, LOC + "Connecting server socket to "
"master backend, socket write failed");
return false;
}
if (!serverSock->ReadStringList(strlist, MythSocket::kShortTimeout) ||
strlist.empty() || (strlist[0] == "ERROR"))
{
if (!strlist.empty())
{
LOG(VB_GENERAL, LOG_ERR, LOC + "Problem connecting "
"server socket to master backend");
}
else
{
LOG(VB_GENERAL, LOG_ERR, LOC + "Timeout connecting "
"server socket to master backend");
}
return false;
}
return true;
}
// Connects to master server safely (i.e. by taking m_sockLock)
bool MythCoreContext::SafeConnectToMasterServer(bool blockingClient,
bool openEventSocket)
{
QMutexLocker locker(&d->m_sockLock);
bool success = ConnectToMasterServer(blockingClient, openEventSocket);
return success;
}
// Assumes that either m_sockLock is held, or the app is still single
// threaded (i.e. during startup).
bool MythCoreContext::ConnectToMasterServer(bool blockingClient,
bool openEventSocket)
{
if (IsMasterBackend())
{
// Should never get here unless there is a bug in the code somewhere.
// If this happens, it can cause endless event loops.
LOG(VB_GENERAL, LOG_ERR, LOC + "ERROR: Master backend tried to connect back "
"to itself!");
return false;
}
if (IsExiting())
return false;
QString server = GetMasterServerIP();
if (server.isEmpty())
return false;
int port = GetMasterServerPort();
bool proto_mismatch = false;
if (d->m_serverSock && !d->m_serverSock->IsConnected())
{
d->m_serverSock->DecrRef();
d->m_serverSock = nullptr;
}
if (!d->m_serverSock)
{
QString type = IsFrontend() ? "Frontend" : (blockingClient ? "Playback" : "Monitor");
QString ann = QString("ANN %1 %2 %3")
.arg(type, d->m_localHostname, QString::number(static_cast<int>(false)));
d->m_serverSock = ConnectCommandSocket(
server, port, ann, &proto_mismatch);
}
if (!d->m_serverSock)
return false;
d->m_blockingClient = blockingClient;
if (!openEventSocket)
return true;
if (!IsBackend())
{
if (d->m_eventSock && !d->m_eventSock->IsConnected())
{
d->m_eventSock->DecrRef();
d->m_eventSock = nullptr;
}
if (!d->m_eventSock)
d->m_eventSock = ConnectEventSocket(server, port);
if (!d->m_eventSock)
{
d->m_serverSock->DecrRef();
d->m_serverSock = nullptr;
QCoreApplication::postEvent(
d->m_guiContext, new MythEvent("CONNECTION_FAILURE"));
return false;
}
}
return true;
}
MythSocket *MythCoreContext::ConnectCommandSocket(
const QString &hostname, int port, const QString &announce,
bool *p_proto_mismatch, int maxConnTry, std::chrono::milliseconds setup_timeout)
{
MythSocket *serverSock = nullptr;
{
QMutexLocker locker(&d->m_wolInProgressLock);
d->WaitForWOL();
}
QString WOLcmd;
if (IsWOLAllowed())
WOLcmd = GetSetting("WOLbackendCommand", "");
if (maxConnTry < 1)
maxConnTry = std::max(GetNumSetting("BackendConnectRetry", 1), 1);
std::chrono::seconds WOLsleepTime = 0s;
int WOLmaxConnTry = 0;
if (!WOLcmd.isEmpty())
{
WOLsleepTime = GetDurSetting<std::chrono::seconds>("WOLbackendReconnectWaitTime", 0s);
WOLmaxConnTry = std::max(GetNumSetting("WOLbackendConnectRetry", 1), 1);
maxConnTry = std::max(maxConnTry, WOLmaxConnTry);
}
bool we_attempted_wol = false;
if (setup_timeout <= 0ms)
setup_timeout = MythSocket::kShortTimeout;
bool proto_mismatch = false;
for (int cnt = 1; cnt <= maxConnTry; cnt++)
{
LOG(VB_GENERAL, LOG_INFO, LOC +
QString("Connecting to backend server: %1:%2 (try %3 of %4)")
.arg(hostname).arg(port).arg(cnt).arg(maxConnTry));
serverSock = new MythSocket();
std::chrono::microseconds sleepus = 0us;
if (serverSock->ConnectToHost(hostname, port))
{
if (SetupCommandSocket(
serverSock, announce, setup_timeout, proto_mismatch))
{
break;
}
if (proto_mismatch)
{
if (p_proto_mismatch)
*p_proto_mismatch = true;
serverSock->DecrRef();
serverSock = nullptr;
break;
}
setup_timeout += setup_timeout / 2;
}
else if (!WOLcmd.isEmpty() && (cnt < maxConnTry))
{
if (!we_attempted_wol)
{
QMutexLocker locker(&d->m_wolInProgressLock);
if (d->m_wolInProgress)
{
d->WaitForWOL();
continue;
}
d->m_wolInProgress = we_attempted_wol = true;
}
MythWakeup(WOLcmd, kMSDontDisableDrawing | kMSDontBlockInputDevs |
kMSProcessEvents);
sleepus = WOLsleepTime;
}
serverSock->DecrRef();
serverSock = nullptr;
if (cnt == 1)
{
QCoreApplication::postEvent(
d->m_guiContext, new MythEvent("CONNECTION_FAILURE"));
}
if (sleepus != 0us)
usleep(sleepus.count());
}
if (we_attempted_wol)
{
QMutexLocker locker(&d->m_wolInProgressLock);
d->m_wolInProgress = false;
d->m_wolInProgressWaitCondition.wakeAll();
}
if (!serverSock && !proto_mismatch)
{
LOG(VB_GENERAL, LOG_ERR,
"Connection to master server timed out.\n\t\t\t"
"Either the server is down or the master server settings"
"\n\t\t\t"
"in mythtv-settings does not contain the proper IP address\n");
}
else
{
QCoreApplication::postEvent(
d->m_guiContext, new MythEvent("CONNECTION_RESTABLISHED"));
}
return serverSock;
}
MythSocket *MythCoreContext::ConnectEventSocket(const QString &hostname,
int port)
{
auto *eventSock = new MythSocket(-1, this);
// Assume that since we _just_ connected the command socket,
// this one won't need multiple retries to work...
if (!eventSock->ConnectToHost(hostname, port))
{
LOG(VB_GENERAL, LOG_ERR, LOC + "Failed to connect event "
"socket to master backend");
eventSock->DecrRef();
return nullptr;
}
QString str = QString("ANN Monitor %1 %2")
.arg(d->m_localHostname).arg(static_cast<int>(true));
QStringList strlist(str);
eventSock->WriteStringList(strlist);
bool ok = true;
if (!eventSock->ReadStringList(strlist) || strlist.empty() ||
(strlist[0] == "ERROR"))
{
if (!strlist.empty())
{
LOG(VB_GENERAL, LOG_ERR, LOC +
"Problem connecting event socket to master backend");
}
else
{
LOG(VB_GENERAL, LOG_ERR, LOC +
"Timeout connecting event socket to master backend");
}
ok = false;
}
if (!ok)
{
eventSock->DecrRef();
eventSock = nullptr;
}
return eventSock;
}
bool MythCoreContext::IsConnectedToMaster(void)
{
QMutexLocker locker(&d->m_sockLock);
return d->m_serverSock;
}
void MythCoreContext::BlockShutdown(void)
{
QStringList strlist;
QMutexLocker locker(&d->m_sockLock);
if (d->m_serverSock == nullptr)
return;
strlist << "BLOCK_SHUTDOWN";
d->m_serverSock->SendReceiveStringList(strlist);
d->m_blockingClient = true;
}
void MythCoreContext::AllowShutdown(void)
{
QStringList strlist;
QMutexLocker locker(&d->m_sockLock);
if (d->m_serverSock == nullptr)
return;
strlist << "ALLOW_SHUTDOWN";
d->m_serverSock->SendReceiveStringList(strlist);
d->m_blockingClient = false;
}
bool MythCoreContext::IsBlockingClient(void) const
{
return d->m_blockingClient;
}
void MythCoreContext::SetWOLAllowed(bool allow)
{
d->m_isWOLAllowed = allow;
}
bool MythCoreContext::IsWOLAllowed() const
{
return d->m_isWOLAllowed;
}
void MythCoreContext::SetAsBackend(bool backend)
{
d->m_backend = backend;
}
bool MythCoreContext::IsBackend(void) const
{
return d->m_backend;
}
void MythCoreContext::SetAsFrontend(bool frontend)
{
d->m_frontend = frontend;
}
bool MythCoreContext::IsFrontend(void) const
{
return d->m_frontend;
}
bool MythCoreContext::IsMasterHost(void)
{
QString host = GetHostName();
return IsMasterHost(host);
}
bool MythCoreContext::IsMasterHost(const QString &host)
{
// Temporary code here only to facilitate the upgrade
// from 1346 or earlier. The way of determining master host is
// changing, and the new way of determning master host
// will not work with earlier databases.
// This code can be removed when updating from prior to
// 1347 is no longer allowed.
// Note that we are deprecating some settings including
// MasterServerIP, and can remove them at a future time.
if (GetNumSetting("DBSchemaVer") < 1347)
{
// Temporary copy of code from old version of
// IsThisHost(Qstring&,QString&)
QString addr(resolveSettingAddress("MasterServerIP"));
if (addr.toLower() == host.toLower())
return true;
QHostAddress addrfix(addr);
addrfix.setScopeId(QString());
QString addrstr = addrfix.toString();
if (addrfix.isNull())
addrstr = resolveAddress(addr);
QString thisip = GetBackendServerIP4(host);
QString thisip6 = GetBackendServerIP6(host);
return !addrstr.isEmpty()
&& ((addrstr == thisip) || (addrstr == thisip6));
}
return GetSetting("MasterServerName") == host;
}
bool MythCoreContext::IsMasterBackend(void)
{
return (IsBackend() && IsMasterHost());
}
bool MythCoreContext::BackendIsRunning(void)
{
#if defined(Q_OS_DARWIN) || defined(__FreeBSD__) || defined(__OpenBSD__)
const char *command = "ps -axc | grep -i mythbackend | grep -v grep > /dev/null";
#elif defined _WIN32
const char *command = "%systemroot%\\system32\\tasklist.exe "
" | %systemroot%\\system32\\find.exe /i \"mythbackend.exe\" ";
#else
const char *command = "ps ch -C mythbackend -o pid > /dev/null";
#endif
uint res = myth_system(command, kMSDontBlockInputDevs |
kMSDontDisableDrawing |
kMSProcessEvents);
return (res == GENERIC_EXIT_OK);
}
bool MythCoreContext::IsThisBackend(const QString &addr)
{
return IsBackend() && IsThisHost(addr);
}
bool MythCoreContext::IsThisHost(const QString &addr)
{
return IsThisHost(addr, GetHostName());
}
bool MythCoreContext::IsThisHost(const QString &addr, const QString &host)
{
if (addr.toLower() == host.toLower())
return true;
QHostAddress addrfix(addr);
addrfix.setScopeId(QString());
QString addrstr = addrfix.toString();
if (addrfix.isNull())
{
addrstr = resolveAddress(addr);
}
QString thisip = GetBackendServerIP(host);
return !addrstr.isEmpty() && ((addrstr == thisip));
}
bool MythCoreContext::IsFrontendOnly(void)
{
// find out if a backend runs on this host...
bool backendOnLocalhost = false;
QStringList strlist("QUERY_IS_ACTIVE_BACKEND");
strlist << GetHostName();
SendReceiveStringList(strlist);
backendOnLocalhost = strlist[0] != "FALSE";
return !backendOnLocalhost;
}
QString MythCoreContext::GenMythURL(const QString& host, int port, QString path, const QString& storageGroup)
{
QUrl ret;
QString m_host;
QHostAddress addr(host);
if (!addr.isNull())
{
LOG(VB_GENERAL, LOG_CRIT, LOC + QString("(%1/%2): Given "
"IP address instead of hostname "
"(ID). This is invalid.").arg(host, path));
}
m_host = host;
// Basically if it appears to be an IPv6 IP surround the IP with [] otherwise don't bother
if (!addr.isNull() && addr.protocol() == QAbstractSocket::IPv6Protocol)
m_host = "[" + addr.toString().toLower() + "]";
ret.setScheme("myth");
if (!storageGroup.isEmpty())
ret.setUserName(storageGroup);
ret.setHost(m_host);
if (port > 0 && port != 6543)
ret.setPort(port);
if (!path.startsWith("/"))
path = QString("/") + path;
ret.setPath(path);
#if 0
LOG(VB_GENERAL, LOG_DEBUG, LOC +
QString("GenMythURL returning %1").arg(ret.toString()));
#endif
return ret.toString();
}
QString MythCoreContext::GetMasterHostPrefix(const QString &storageGroup,
const QString &path)
{
return GenMythURL(GetMasterHostName(),
GetMasterServerPort(),
path,
storageGroup);
}
QString MythCoreContext::GetMasterHostName(void)
{
QMutexLocker locker(&d->m_masterHostLock);
if (d->m_masterHostname.isEmpty())
{
if (IsMasterBackend())
d->m_masterHostname = d->m_localHostname;
else
{
QStringList strlist("QUERY_HOSTNAME");
if (SendReceiveStringList(strlist))
d->m_masterHostname = strlist[0];
}
}
return d->m_masterHostname;
}
void MythCoreContext::ClearSettingsCache(const QString &myKey)
{
d->m_database->ClearSettingsCache(myKey);
}
void MythCoreContext::ActivateSettingsCache(bool activate)
{
d->m_database->ActivateSettingsCache(activate);
}
QString MythCoreContext::GetHostName(void)
{
QMutexLocker locker(&d->m_localHostLock);
return d->m_localHostname;
}
QString MythCoreContext::GetFilePrefix(void)
{
return GetSetting("RecordFilePrefix");
}
void MythCoreContext::GetResolutionSetting(const QString &type,
int &width, int &height,
double &forced_aspect,
double &refresh_rate,
int index)
{
d->m_database->GetResolutionSetting(type, width, height, forced_aspect,
refresh_rate, index);
}
void MythCoreContext::GetResolutionSetting(const QString &t, int &w,
int &h, int i)
{
d->m_database->GetResolutionSetting(t, w, h, i);
}
MDBManager *MythCoreContext::GetDBManager(void)
{
return d->m_database->GetDBManager();
}
/** /brief Returns true if database is being ignored.
*
* This was created for some command line only programs which
* still need MythTV libraries, such as channel scanners, channel
* change programs, and the off-line commercial flagger.
*/
bool MythCoreContext::IsDatabaseIgnored(void) const
{
return d->m_database->IsDatabaseIgnored();
}
void MythCoreContext::SaveSetting(const QString &key, int newValue)
{
d->m_database->SaveSetting(key, newValue);
}
void MythCoreContext::SaveSetting(const QString &key, const QString &newValue)
{
d->m_database->SaveSetting(key, newValue);
}
bool MythCoreContext::SaveSettingOnHost(const QString &key,
const QString &newValue,
const QString &host)
{
return d->m_database->SaveSettingOnHost(key, newValue, host);
}
QString MythCoreContext::GetSetting(const QString &key,
const QString &defaultval)
{
if (!m_testOverrideStrings.empty())
return m_testOverrideStrings[key];
return d->m_database->GetSetting(key, defaultval);
}
bool MythCoreContext::GetBoolSetting(const QString &key, bool defaultval)
{
int result = GetNumSetting(key, static_cast<int>(defaultval));
return result > 0;
}
int MythCoreContext::GetNumSetting(const QString &key, int defaultval)
{
if (!m_testOverrideInts.empty())
return m_testOverrideInts[key];
return d->m_database->GetNumSetting(key, defaultval);
}
double MythCoreContext::GetFloatSetting(const QString &key, double defaultval)
{
if (!m_testOverrideFloats.empty())
return m_testOverrideFloats[key];
return d->m_database->GetFloatSetting(key, defaultval);
}
QString MythCoreContext::GetSettingOnHost(const QString &key,
const QString &host,
const QString &defaultval)
{
if (!m_testOverrideStrings.empty())
return m_testOverrideStrings[key];
return d->m_database->GetSettingOnHost(key, host, defaultval);
}
bool MythCoreContext::GetBoolSettingOnHost(const QString &key,
const QString &host,
bool defaultval)
{
int result = GetNumSettingOnHost(key, host, static_cast<int>(defaultval));
return result > 0;
}
int MythCoreContext::GetNumSettingOnHost(const QString &key,
const QString &host,
int defaultval)
{
if (!m_testOverrideInts.empty())
return m_testOverrideInts[key];
return d->m_database->GetNumSettingOnHost(key, host, defaultval);
}
double MythCoreContext::GetFloatSettingOnHost(const QString &key,
const QString &host,
double defaultval)
{
if (!m_testOverrideFloats.empty())
return m_testOverrideFloats[key];
return d->m_database->GetFloatSettingOnHost(key, host, defaultval);
}
/**
* Returns the Master Backend IP address
* If the address is an IPv6 address, the scope Id is removed.
* If no master server address has been defined in the database, return localhost
*/
QString MythCoreContext::GetMasterServerIP(void)
{
QString masterserver = gCoreContext->GetSetting("MasterServerName");
QString masterip = resolveSettingAddress("BackendServerAddr",masterserver);
// Even if empty, return it here if we were to assume that localhost
// should be used it just causes a lot of unnecessary error messages.
return masterip;
}
/**
* Returns the Master Backend control port
* If no master server port has been defined in the database, return the default
* 6543
*/
int MythCoreContext::GetMasterServerPort(void)
{
QString masterserver = gCoreContext->GetSetting
("MasterServerName");
return gCoreContext->GetNumSettingOnHost
("BackendServerPort", masterserver, 6543);
}
/**
* Returns the Master Backend status port
* If no master server status port has been defined in the database,
* return the default 6544
*/
int MythCoreContext::GetMasterServerStatusPort(void)
{
QString masterhost = GetMasterHostName();
return GetBackendStatusPort(masterhost);
}
/**
* Returns the IP address of the locally defined backend IP.
* See GetBackendServerIP(host)
*/
QString MythCoreContext::GetBackendServerIP(void)