forked from MythTV/mythtv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mythcontext.cpp
1639 lines (1398 loc) · 49.3 KB
/
mythcontext.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
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <QMutex>
#include <QDateTime>
#include <QTcpSocket>
#include <QEventLoop>
#include <cmath>
#include <iostream>
#include <queue>
#include <algorithm>
#include <thread>
using namespace std;
#include "config.h"
#include "mythcontext.h"
#include "exitcodes.h"
#include "mythdate.h"
#include "remotefile.h"
#include "backendselect.h"
#include "dbsettings.h"
#include "langsettings.h"
#include "mythtranslation.h"
#include "mythxdisplay.h"
#include "mythevent.h"
#include "dbutil.h"
#include "DisplayRes.h"
#include "mythmediamonitor.h"
#include "mythdb.h"
#include "mythdirs.h"
#include "mythversion.h"
#include "mythdialogbox.h"
#include "mythmainwindow.h"
#include "mythuihelper.h"
#include "mythimage.h"
#include "mythxmlclient.h"
#include "upnp.h"
#include "mythlogging.h"
#include "mythsystemlegacy.h"
#include "mythmiscutil.h"
#include "mythplugin.h"
#include "portchecker.h"
#include "guistartup.h"
#include <unistd.h> // for usleep(), gethostname
#ifdef _WIN32
#include "compat.h"
#endif
#define LOC QString("MythContext: ")
MythContext *gContext = NULL;
static const QString _Location = "MythContext";
class MythContextPrivate : public QObject
{
friend class MythContextSlotHandler;
public:
MythContextPrivate(MythContext *lparent);
~MythContextPrivate();
bool Init (const bool gui,
const bool prompt, const bool noPrompt,
const bool ignoreDB);
bool FindDatabase(const bool prompt, const bool noPrompt);
void TempMainWindow(bool languagePrompt = true);
void EndTempWindow(void);
bool LoadDatabaseSettings(void);
bool SaveDatabaseParams(const DatabaseParams ¶ms, bool force);
bool PromptForDatabaseParams(const QString &error);
QString TestDBconnection(bool prompt=true);
void SilenceDBerrors(void);
void EnableDBerrors(void);
void ResetDatabase(void);
int ChooseBackend(const QString &error);
int UPnPautoconf(const int milliSeconds = 2000);
bool DefaultUPnP(QString &error);
bool UPnPconnect(const DeviceLocation *device, const QString &PIN);
void ShowGuiStartup(void);
bool checkPort(QString &host, int port, int wakeupTime);
void processEvents(void);
bool saveSettingsCache(void);
void loadSettingsCacheOverride(void);
void clearSettingsCacheOverride(void);
protected:
bool event(QEvent*);
void ShowConnectionFailurePopup(bool persistent);
void HideConnectionFailurePopup(void);
void ShowVersionMismatchPopup(uint remoteVersion);
public slots:
void OnCloseDialog();
public:
MythContext *parent;
bool m_gui; ///< Should this context use GUI elements?
QString m_masterhostname; ///< master backend hostname
DatabaseParams m_DBparams; ///< Current database host & WOL details
QString m_DBhostCp; ///< dbHostName backup
Configuration *m_pConfig;
bool disableeventpopup;
MythUIHelper *m_ui;
MythContextSlotHandler *m_sh;
GUIStartup *m_guiStartup;
QEventLoop *m_loop;
bool needsBackend;
bool m_settingsCacheDirty;
private:
MythConfirmationDialog *MBEversionPopup;
int m_registration;
QDateTime m_lastCheck;
QTcpSocket *m_socket;
static const QString settingsToSave[];
};
static void exec_program_cb(const QString &cmd)
{
myth_system(cmd);
}
static void exec_program_tv_cb(const QString &cmd)
{
QString s = cmd;
QStringList tokens = cmd.simplified().split(" ");
QStringList strlist;
bool cardidok;
int wantcardid = tokens[0].toInt(&cardidok, 10);
if (cardidok && wantcardid > 0)
{
strlist << QString("LOCK_TUNER %1").arg(wantcardid);
s = s.replace(0, tokens[0].length() + 1, "");
}
else
strlist << "LOCK_TUNER";
gCoreContext->SendReceiveStringList(strlist);
int cardid = strlist[0].toInt();
if (cardid >= 0)
{
s = s.sprintf(qPrintable(s),
qPrintable(strlist[1]),
qPrintable(strlist[2]),
qPrintable(strlist[3]));
myth_system(s);
strlist = QStringList(QString("FREE_TUNER %1").arg(cardid));
gCoreContext->SendReceiveStringList(strlist);
QString ret = strlist[0];
}
else
{
QString label;
if (cardidok)
{
if (cardid == -1)
label = QObject::tr("Could not find specified tuner (%1).")
.arg(wantcardid);
else
label = QObject::tr("Specified tuner (%1) is already in use.")
.arg(wantcardid);
}
else
{
label = QObject::tr("All tuners are currently in use. If you want "
"to watch TV, you can cancel one of the "
"in-progress recordings from the delete menu");
}
LOG(VB_GENERAL, LOG_ALERT, QString("exec_program_tv: ") + label);
ShowOkPopup(label);
}
}
static void configplugin_cb(const QString &cmd)
{
MythPluginManager *pmanager = gCoreContext->GetPluginManager();
if (!pmanager)
return;
if (GetNotificationCenter() && pmanager->config_plugin(cmd.trimmed()))
{
ShowNotificationError(cmd, _Location,
QObject::tr("Failed to configure plugin"));
}
}
static void plugin_cb(const QString &cmd)
{
MythPluginManager *pmanager = gCoreContext->GetPluginManager();
if (!pmanager)
return;
if (GetNotificationCenter() && pmanager->run_plugin(cmd.trimmed()))
{
ShowNotificationError(QObject::tr("Plugin failure"),
_Location,
QObject::tr("%1 failed to run for some reason").arg(cmd));
}
}
static void eject_cb(void)
{
MediaMonitor::ejectOpticalDisc();
}
MythContextPrivate::MythContextPrivate(MythContext *lparent)
: parent(lparent),
m_gui(false),
m_pConfig(NULL),
disableeventpopup(false),
m_ui(NULL),
m_sh(new MythContextSlotHandler(this)),
m_guiStartup(0),
needsBackend(false),
m_settingsCacheDirty(false),
MBEversionPopup(NULL),
m_registration(-1),
m_socket(0)
{
m_loop = new QEventLoop(this);
InitializeMythDirs();
}
MythContextPrivate::~MythContextPrivate()
{
if (m_pConfig)
delete m_pConfig;
if (GetNotificationCenter() && m_registration > 0)
{
GetNotificationCenter()->UnRegister(this, m_registration, true);
}
if (m_loop)
{
delete m_loop;
}
if (m_ui)
DestroyMythUI();
if (m_sh)
m_sh->deleteLater();
}
/**
* \brief Setup a minimal themed main window, and prompt for user's language.
*
* Used for warnings before the database is opened, or bootstrapping pages.
* After using the window, call EndTempWindow().
*
* \bug Some of these settings (<i>e.g.</I> window size, theme)
* seem to be used after the temp window is destroyed.
*
*/
void MythContextPrivate::TempMainWindow(bool languagePrompt)
{
if (HasMythMainWindow())
return;
SilenceDBerrors();
loadSettingsCacheOverride();
#ifdef Q_OS_MAC
// Qt 4.4 has window-focus problems
gCoreContext->OverrideSettingForSession("RunFrontendInWindow", "1");
#endif
GetMythUI()->Init();
GetMythUI()->LoadQtConfig();
MythMainWindow *mainWindow = MythMainWindow::getMainWindow(false);
mainWindow->Init();
if (languagePrompt)
{
// ask user for language settings
LanguageSelection::prompt();
MythTranslation::load("mythfrontend");
}
}
void MythContextPrivate::EndTempWindow(void)
{
if (HasMythMainWindow())
{
if (m_guiStartup && !m_guiStartup->m_Exit)
{
MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack();
if (mainStack) {
mainStack->PopScreen(m_guiStartup, false);
m_guiStartup = 0;
}
}
}
EnableDBerrors();
}
/**
* Check if a port is open and sort out the link-local scope.
*
* \param host Host or IP address. Will be updated with link-local
* scope if needed.
*/
bool MythContextPrivate::checkPort(QString &host, int port, int timeLimit)
{
PortChecker checker;
if (m_guiStartup)
QObject::connect(m_guiStartup,SIGNAL(cancelPortCheck()),&checker,SLOT(cancelPortCheck()));
return checker.checkPort(host, port, timeLimit*1000);
}
bool MythContextPrivate::Init(const bool gui,
const bool promptForBackend,
const bool noPrompt,
const bool ignoreDB)
{
gCoreContext->GetDB()->IgnoreDatabase(ignoreDB);
m_gui = gui;
if (gCoreContext->IsFrontend())
needsBackend = true;
// We don't have a database yet, so lets use the config.xml file.
m_pConfig = new XmlConfiguration("config.xml");
// Creates screen saver control if we will have a GUI
if (gui)
m_ui = GetMythUI();
// ---- database connection stuff ----
if (!ignoreDB && !FindDatabase(promptForBackend, noPrompt))
{
EndTempWindow();
return false;
}
// ---- keep all DB-using stuff below this line ----
// Prompt for language if this is a first time install and
// we didn't already do so.
if (m_gui && !gCoreContext->GetDB()->HaveSchema())
{
TempMainWindow(false);
LanguageSelection::prompt();
MythTranslation::load("mythfrontend");
}
gCoreContext->InitLocale();
gCoreContext->SaveLocaleDefaults();
// Close GUI Startup Window.
if (m_guiStartup) {
MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack();
if (mainStack)
mainStack->PopScreen(m_guiStartup, false);
m_guiStartup=0;
}
EndTempWindow();
if (gui)
{
MythUIMenuCallbacks cbs;
cbs.exec_program = exec_program_cb;
cbs.exec_program_tv = exec_program_tv_cb;
cbs.configplugin = configplugin_cb;
cbs.plugin = plugin_cb;
cbs.eject = eject_cb;
m_ui->Init(cbs);
}
return true;
}
/**
* Get database connection settings and test connectivity.
*
* Can use UPnP AutoDiscovery to locate backends, and get their DB settings.
* The user can force the AutoDiscovery chooser with the --prompt argument,
* and disable it by using the --disable-autodiscovery argument.
* There is also an autoconfigure function, which counts the backends,
* and if there is exactly one, uses it as above.
*
* Despite its name, the disable argument currently only disables the chooser.
* If set, autoconfigure will still be attempted in some situations.
*/
bool MythContextPrivate::FindDatabase(bool prompt, bool noAutodetect)
{
// We can only prompt if autodiscovery is enabled..
bool manualSelect = prompt && !noAutodetect;
QString failure;
// 1. Either load config.xml or use sensible "localhost" defaults:
bool loaded = LoadDatabaseSettings();
DatabaseParams dbParamsFromFile = m_DBparams;
// In addition to the UI chooser, we can also try to autoSelect later,
// but only if we're not doing manualSelect and there was no
// valid config.xml
bool autoSelect = !manualSelect && !loaded && !noAutodetect;
// 2. If the user isn't forcing up the chooser UI, look for a default
// backend in config.xml, then test DB settings we've got so far:
if (!manualSelect)
{
// config.xml may contain a backend host UUID and PIN.
// If so, try to AutoDiscover UPnP server, and use its DB settings:
if (DefaultUPnP(failure)) // Probably a valid backend,
autoSelect = manualSelect = false; // so disable any further UPnP
else
if (failure.length())
LOG(VB_GENERAL, LOG_ALERT, failure);
failure = TestDBconnection(loaded);
if (failure.isEmpty())
goto DBfound;
if (m_guiStartup && m_guiStartup->m_Exit)
return false;
if (m_guiStartup && m_guiStartup->m_Search)
autoSelect=true;
}
// 3. Try to automatically find the single backend:
if (autoSelect)
{
int count = UPnPautoconf();
if (count == 0)
failure = QObject::tr("No UPnP backends found", "Backend Setup");
if (count == 1)
{
failure = TestDBconnection();
if (failure.isEmpty())
goto DBfound;
if (m_guiStartup && m_guiStartup->m_Exit)
return false;
}
// Multiple BEs, or needs PIN.
manualSelect |= (count > 1 || count == -1);
// Search requested
if (m_guiStartup && m_guiStartup->m_Search)
manualSelect=true;
}
manualSelect &= m_gui; // no interactive command-line chooser yet
// Queries the user for the DB info
do
{
if (manualSelect)
{
// Get the user to select a backend from a possible list:
BackendSelection::Decision d = (BackendSelection::Decision)
ChooseBackend(failure);
switch (d)
{
case BackendSelection::kAcceptConfigure:
break;
case BackendSelection::kManualConfigure:
manualSelect = false;
break;
case BackendSelection::kCancelConfigure:
goto NoDBfound;
}
}
if (!manualSelect)
{
if (!PromptForDatabaseParams(failure))
goto NoDBfound;
}
failure = TestDBconnection();
if (!failure.isEmpty())
LOG(VB_GENERAL, LOG_ALERT, failure);
if (m_guiStartup && m_guiStartup->m_Exit)
return false;
if (m_guiStartup && m_guiStartup->m_Search)
manualSelect=true;
if (m_guiStartup && m_guiStartup->m_Setup)
manualSelect=false;
}
while (!failure.isEmpty());
DBfound:
LOG(VB_GENERAL, LOG_DEBUG, "FindDatabase() - Success!");
// If we got the database from UPNP then the wakeup settings are lost.
// Restore them.
m_DBparams.wolEnabled = dbParamsFromFile.wolEnabled;
m_DBparams.wolReconnect = dbParamsFromFile.wolReconnect;
m_DBparams.wolRetry = dbParamsFromFile.wolRetry;
m_DBparams.wolCommand = dbParamsFromFile.wolCommand;
SaveDatabaseParams(m_DBparams,
!loaded || m_DBparams.forceSave ||
dbParamsFromFile != m_DBparams);
EnableDBerrors();
ResetDatabase();
return true;
NoDBfound:
LOG(VB_GENERAL, LOG_DEBUG, "FindDatabase() - failed");
return false;
}
/** Load database and host settings from config.xml, or set some defaults.
* \return true if config.xml was parsed
*/
bool MythContextPrivate::LoadDatabaseSettings(void)
{
// try new format first
m_DBparams.LoadDefaults();
m_DBparams.localHostName = m_pConfig->GetValue("LocalHostName", "");
m_DBparams.dbHostPing = m_pConfig->GetValue(kDefaultDB + "PingHost", true);
m_DBparams.dbHostName = m_pConfig->GetValue(kDefaultDB + "Host", "");
m_DBparams.dbUserName = m_pConfig->GetValue(kDefaultDB + "UserName", "");
m_DBparams.dbPassword = m_pConfig->GetValue(kDefaultDB + "Password", "");
m_DBparams.dbName = m_pConfig->GetValue(kDefaultDB + "DatabaseName", "");
m_DBparams.dbPort = m_pConfig->GetValue(kDefaultDB + "Port", 0);
m_DBparams.wolEnabled =
m_pConfig->GetValue(kDefaultWOL + "Enabled", false);
m_DBparams.wolReconnect =
m_pConfig->GetValue(kDefaultWOL + "SQLReconnectWaitTime", 0);
m_DBparams.wolRetry =
m_pConfig->GetValue(kDefaultWOL + "SQLConnectRetry", 5);
m_DBparams.wolCommand =
m_pConfig->GetValue(kDefaultWOL + "Command", "");
bool ok = m_DBparams.IsValid("config.xml");
if (!ok) // if new format fails, try legacy format
{
m_DBparams.LoadDefaults();
m_DBparams.dbHostName = m_pConfig->GetValue(
kDefaultMFE + "DBHostName", "");
m_DBparams.dbUserName = m_pConfig->GetValue(
kDefaultMFE + "DBUserName", "");
m_DBparams.dbPassword = m_pConfig->GetValue(
kDefaultMFE + "DBPassword", "");
m_DBparams.dbName = m_pConfig->GetValue(
kDefaultMFE + "DBName", "");
m_DBparams.dbPort = m_pConfig->GetValue(
kDefaultMFE + "DBPort", 0);
m_DBparams.forceSave = true;
ok = m_DBparams.IsValid("config.xml");
}
if (!ok)
m_DBparams.LoadDefaults();
gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
QString hostname = m_DBparams.localHostName;
if (hostname.isEmpty() ||
hostname == "my-unique-identifier-goes-here")
{
char localhostname[1024];
if (gethostname(localhostname, 1024))
{
LOG(VB_GENERAL, LOG_ALERT,
"MCP: Error, could not determine host name." + ENO);
localhostname[0] = '\0';
}
hostname = localhostname;
LOG(VB_GENERAL, LOG_NOTICE, "Empty LocalHostName.");
}
else
{
m_DBparams.localEnabled = true;
}
LOG(VB_GENERAL, LOG_INFO, QString("Using localhost value of %1")
.arg(hostname));
gCoreContext->SetLocalHostname(hostname);
return ok;
}
bool MythContextPrivate::SaveDatabaseParams(
const DatabaseParams ¶ms, bool force)
{
bool ret = true;
// only rewrite file if it has changed
if (params != m_DBparams || force)
{
m_pConfig->SetValue(
"LocalHostName", params.localHostName);
m_pConfig->SetValue(
kDefaultDB + "PingHost", params.dbHostPing);
// If dbHostName is an IPV6 address with scope,
// remove the scope. Unescaped % signs are an
// xml violation
QString dbHostName(params.dbHostName);
QHostAddress addr;
if (addr.setAddress(dbHostName))
{
addr.setScopeId(QString());
dbHostName = addr.toString();
}
m_pConfig->SetValue(
kDefaultDB + "Host", dbHostName);
m_pConfig->SetValue(
kDefaultDB + "UserName", params.dbUserName);
m_pConfig->SetValue(
kDefaultDB + "Password", params.dbPassword);
m_pConfig->SetValue(
kDefaultDB + "DatabaseName", params.dbName);
m_pConfig->SetValue(
kDefaultDB + "Port", params.dbPort);
m_pConfig->SetValue(
kDefaultWOL + "Enabled", params.wolEnabled);
m_pConfig->SetValue(
kDefaultWOL + "SQLReconnectWaitTime", params.wolReconnect);
m_pConfig->SetValue(
kDefaultWOL + "SQLConnectRetry", params.wolRetry);
m_pConfig->SetValue(
kDefaultWOL + "Command", params.wolCommand);
// clear out any legacy nodes..
m_pConfig->ClearValue(kDefaultMFE + "DBHostName");
m_pConfig->ClearValue(kDefaultMFE + "DBUserName");
m_pConfig->ClearValue(kDefaultMFE + "DBPassword");
m_pConfig->ClearValue(kDefaultMFE + "DBName");
m_pConfig->ClearValue(kDefaultMFE + "DBPort");
m_pConfig->ClearValue(kDefaultMFE + "DBHostPing");
// actually save the file
m_pConfig->Save();
// Save the new settings:
m_DBparams = params;
gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
// If database has changed, force its use:
ResetDatabase();
}
return ret;
}
void MythContextSlotHandler::OnCloseDialog(void)
{
if (d && d->m_loop
&& d->m_loop->isRunning())
d->m_loop->exit();
}
bool MythContextPrivate::PromptForDatabaseParams(const QString &error)
{
bool accepted = false;
if (m_gui)
{
TempMainWindow();
// Tell the user what went wrong:
if (error.length())
ShowOkPopup(error);
// ask user for database parameters
EnableDBerrors();
MythScreenStack *mainStack = GetMythMainWindow()->GetMainStack();
DatabaseSettings *dbsetting = new DatabaseSettings();
StandardSettingDialog *ssd =
new StandardSettingDialog(mainStack, "databasesettings",
dbsetting);
if (ssd->Create())
{
mainStack->AddScreen(ssd);
connect(dbsetting, &DatabaseSettings::isClosing,
m_sh, &MythContextSlotHandler::OnCloseDialog);
if (!m_loop->isRunning())
m_loop->exec();
}
else
delete ssd;
SilenceDBerrors();
EndTempWindow();
accepted = true;
}
else
{
DatabaseParams params = parent->GetDatabaseParams();
QString response;
std::this_thread::sleep_for(std::chrono::seconds(1));
// give user chance to skip config
cout << endl << error.toLocal8Bit().constData() << endl << endl;
response = getResponse("Would you like to configure the database "
"connection now?",
"no");
if (!response.startsWith('y', Qt::CaseInsensitive))
return false;
params.dbHostName = getResponse("Database host name:",
params.dbHostName);
response = getResponse("Should I test connectivity to this host "
"using the ping command?", "yes");
params.dbHostPing = response.startsWith('y', Qt::CaseInsensitive);
params.dbPort = intResponse("Database non-default port:",
params.dbPort);
params.dbName = getResponse("Database name:",
params.dbName);
params.dbUserName = getResponse("Database user name:",
params.dbUserName);
params.dbPassword = getResponse("Database password:",
params.dbPassword);
params.localHostName = getResponse("Unique identifier for this machine "
"(if empty, the local host name "
"will be used):",
params.localHostName);
params.localEnabled = !params.localHostName.isEmpty();
response = getResponse("Would you like to use Wake-On-LAN to retry "
"database connections?",
(params.wolEnabled ? "yes" : "no"));
params.wolEnabled = response.startsWith('y', Qt::CaseInsensitive);
if (params.wolEnabled)
{
params.wolReconnect = intResponse("Seconds to wait for "
"reconnection:",
params.wolReconnect);
params.wolRetry = intResponse("Number of times to retry:",
params.wolRetry);
params.wolCommand = getResponse("Command to use to wake server:",
params.wolCommand);
}
accepted = parent->SaveDatabaseParams(params);
}
return accepted;
}
/**
* Some quick sanity checks before opening a database connection
*
* \todo Rationalise the WOL stuff. We should have one method to wake BEs
*/
QString MythContextPrivate::TestDBconnection(bool prompt)
{
QString err = QString::null;
QString host;
// Jan 20, 2017
// Changed to use port check instead of ping
int port;
// 1 = db awake, 2 = db listening, 3 = db connects,
// 4 = backend awake, 5 = backend listening
// 9 = all ok, 10 = quit
enum startupStates {
st_start = 0,
st_dbAwake = 1,
st_dbStarted = 2,
st_dbConnects = 3,
st_beWOL = 4,
st_beAwake = 5,
st_success = 6
} startupState = st_start;
static const QString guiStatuses[7] =
{"start","dbAwake","dbStarted","dbConnects","beWOL","beAwake",
"success" };
do
{
host = m_DBparams.dbHostName;
port = m_DBparams.dbPort;
if (port == 0)
port = 3306;
int wakeupTime = 3;
int attempts = 11;
if (m_DBparams.wolEnabled) {
wakeupTime = m_DBparams.wolReconnect;
attempts = m_DBparams.wolRetry + 1;
startupState = st_start;
}
else
startupState = st_dbAwake;
if (attempts < 6)
attempts = 6;
if (!prompt)
attempts=1;
if (wakeupTime < 5)
wakeupTime = 5;
int progressTotal = wakeupTime * attempts;
if (m_guiStartup && !m_guiStartup->m_Exit)
m_guiStartup->setTotal(progressTotal);
QString beWOLCmd = QString();
QString backendIP = QString();
int backendPort = 0;
QString masterserver;
for (int attempt = 0;
attempt < attempts && startupState != st_success;
++attempt)
{
// The first time do everything with minimum timeout and
// no GUI, for the normal case where all is OK
// After that show the GUI (if this is a GUI program)
LOG(VB_GENERAL, LOG_INFO,
QString("Start up testing connections. DB %1, BE %2, attempt %3, status %4")
.arg(host).arg(backendIP).arg(attempt).arg(guiStatuses[startupState]));
int useTimeout = wakeupTime;
if (attempt == 0)
useTimeout=1;
if (m_gui && !m_guiStartup)
{
if (attempt > 0)
{
ShowGuiStartup();
if (m_guiStartup)
m_guiStartup->setTotal(progressTotal);
}
}
if (m_guiStartup && !m_guiStartup->m_Exit)
{
if (attempt > 0)
m_guiStartup->setStatusState(guiStatuses[startupState]);
m_guiStartup->setMessageState("empty");
processEvents();
}
switch (startupState) {
case st_start:
if (m_DBparams.wolEnabled)
{
if (attempt > 0)
myth_system(m_DBparams.wolCommand);
if (!checkPort(host, port, useTimeout))
break;
}
startupState = st_dbAwake;
// Fall through to next case
case st_dbAwake:
if (!checkPort(host, port, useTimeout))
break;
startupState = st_dbStarted;
// Fall through to next case
case st_dbStarted:
// If the database is connecting with link-local
// address, it may have changed
if (m_DBparams.dbHostName != host)
{
m_DBparams.dbHostName = host;
gCoreContext->GetDB()->SetDatabaseParams(m_DBparams);
}
EnableDBerrors();
ResetDatabase();
if (!MSqlQuery::testDBConnection())
{
for (int temp = 0; temp < useTimeout * 2 ; temp++)
{
processEvents();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
break;
}
startupState = st_dbConnects;
// Fall through to next case
case st_dbConnects:
if (needsBackend)
{
beWOLCmd = gCoreContext->GetSetting("WOLbackendCommand", "");
if (!beWOLCmd.isEmpty())
{
wakeupTime += gCoreContext->GetNumSetting
("WOLbackendReconnectWaitTime", 0);
attempts += gCoreContext->GetNumSetting
("WOLbackendConnectRetry", 0);
useTimeout = wakeupTime;
if (m_gui && !m_guiStartup && attempt == 0)
useTimeout=1;
progressTotal = wakeupTime * attempts;
if (m_guiStartup && !m_guiStartup->m_Exit)
m_guiStartup->setTotal(progressTotal);
startupState = st_beWOL;
}
}
else {
startupState = st_success;
break;
}
masterserver = gCoreContext->GetSetting
("MasterServerName");
backendIP = gCoreContext->GetSettingOnHost
("BackendServerAddr", masterserver);
backendPort = gCoreContext->GetMasterServerPort();
// Fall through to next case
case st_beWOL:
if (!beWOLCmd.isEmpty()) {
if (attempt > 0)
myth_system(beWOLCmd);
if (!checkPort(backendIP, backendPort, useTimeout))
break;
}
startupState = st_beAwake;
// Fall through to next case
case st_beAwake:
if (!checkPort(backendIP, backendPort, useTimeout))
break;
startupState = st_success;
}
if (m_guiStartup)
{
if (m_guiStartup->m_Exit
|| m_guiStartup->m_Setup
|| m_guiStartup->m_Search
|| m_guiStartup->m_Retry)
break;
}
processEvents();
}
if (startupState == st_success)
break;
QString stateMsg = guiStatuses[startupState];
stateMsg.append("Fail");
LOG(VB_GENERAL, LOG_INFO,
QString("Start up failure. host %1, status %2")
.arg(host).arg(stateMsg));
if (m_guiStartup
&& !m_guiStartup->m_Exit
&& !m_guiStartup->m_Setup
&& !m_guiStartup->m_Search
&& !m_guiStartup->m_Retry)
{
m_guiStartup->updateProgress(true);
m_guiStartup->setStatusState(stateMsg);
m_guiStartup->setMessageState("makeselection");
m_loop->exec();
}
}
while (m_guiStartup && m_guiStartup->m_Retry);
if (startupState < st_dbAwake)
{
LOG(VB_GENERAL, LOG_WARNING, QString("Pinging to %1 failed, database will be unavailable").arg(host));
SilenceDBerrors();
err = QObject::tr(
"Cannot find (ping) database host %1 on the network",
"Backend Setup");
return err.arg(host);
}
if (startupState < st_dbConnects)
{
SilenceDBerrors();
return QObject::tr("Cannot login to database", "Backend Setup");
}
if (startupState < st_success)