-
Notifications
You must be signed in to change notification settings - Fork 32
/
TempDbMySqlBase.cs
2262 lines (1972 loc) · 70.3 KB
/
TempDbMySqlBase.cs
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using PeanutButter.FileSystem;
using PeanutButter.Utils;
// ReSharper disable StaticMemberInGenericType
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IdentifierTypo
// ReSharper disable StringLiteralTypo
// ReSharper disable CommentTypo
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
namespace PeanutButter.TempDb.MySql.Base
{
// ReSharper disable once InconsistentNaming
/// <summary>
/// MySql flavor of TempDb
/// </summary>
public abstract class TempDBMySqlBase<T> : TempDB<T> where T : DbConnection
{
public string BootstrappedFromTemplateFolder { get; protected set; }
public string ServerCommandline =>
_serverProcess?.Commandline;
// ReSharper disable once StaticMemberInGenericType
/// <summary>
/// The maximum amount of time to wait for a mysqld process to be
/// listening for connections after starting up. Defaults to 45 seconds,
/// but left static so consumers can tweak the value as required.
/// </summary>
public static int DefaultStartupMaxWaitSeconds = 45;
// ReSharper disable once StaticMemberInGenericType
/// <summary>
/// Maximum number of times that TempDBMySql will automatically
/// re-attempt initial start. This may be useful in the case where
/// MySql isn't starting up but also isn't logging anything particularly
/// useful about _why_ it isn't starting up. Defaults to 5, but left
/// as a static so consumers can tweak the value as required.
/// </summary>
public static int MaxStartupAttempts = 5;
public static int MaxSecondsToWaitForMySqlToStart =>
DetermineMaxSecondsToWaitForMySqlToStart();
/// <summary>
/// After the server has been set up and started, this will reflect
/// the absolute path to the configuration file for the server
/// </summary>
public string ConfigFilePath { get; set; }
private static int DetermineMaxSecondsToWaitForMySqlToStart()
{
var env = Environment.GetEnvironmentVariable(
EnvironmentVariables.MYSQL_MAX_STARTUP_TIME_IN_SECONDS
);
if (env is null || !int.TryParse(env, out var value))
{
return DefaultStartupMaxWaitSeconds;
}
return value;
}
public bool VerboseLoggingEnabled
{
get
{
return _verboseLoggingEnabled ??= DetermineIfVerboseLoggingShouldBeEnabled();
}
set
{
_verboseLoggingEnabled = value;
}
}
private bool? _verboseLoggingEnabled;
private bool DetermineIfVerboseLoggingShouldBeEnabled()
{
var envValue = Environment.GetEnvironmentVariable(EnvironmentVariables.VERBOSE);
if (envValue is null)
{
return Settings?.Options?.EnableVerboseLogging ?? false;
}
return envValue.AsBoolean();
}
private bool ShouldAttemptGracefulShutdown
{
get
{
var envValue = Environment.GetEnvironmentVariable(EnvironmentVariables.GRACEFUL_SHUTDOWN);
if (envValue is null)
{
return Settings?.Options?.AttemptGracefulShutdown ?? true;
}
return envValue.AsBoolean();
}
}
private readonly object _debugLogLock = new();
private void DebugLog(string toLog)
{
if (!VerboseLoggingEnabled)
{
return;
}
lock (_debugLogLock)
{
File.AppendAllLines(
_debugLogFile,
new[]
{
toLog
}
);
}
}
/// <summary>
/// Set to true to see trace logging about discovery of a port to
/// instruct mysqld to bind to
/// </summary>
public TempDbMySqlServerSettings Settings { get; private set; }
public int? ServerProcessId => _serverProcess?.ProcessId;
public string ServerProcessCommand => _serverProcess?.Commandline;
private IProcessIO _serverProcess;
public int Port { get; protected set; }
public bool RootPasswordSet { get; private set; }
// ReSharper disable once StaticMemberInGenericType
private static readonly SemaphoreSlim MysqldLock = new(1, 1);
private static readonly SemaphoreSlim InstanceLock = new(1, 1);
// ReSharper disable once StaticMemberInGenericType
private static string _mysqld;
public Guid InstanceId =>
TryDetermineInstanceId();
public MySqlVersionInfo MySqlVersion =>
_mysqlVersion ??= QueryVersionOf(MySqld);
private MySqlVersionInfo _mysqlVersion;
private Guid TryDetermineInstanceId()
{
return ParseFirstGuidFromPath(DatabasePath);
}
private Guid ParseFirstGuidFromPath(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return Guid.Empty;
}
return InstanceIdCache.FindOrAdd(
path,
() =>
{
var parts = path.Split(
new[]
{
"\\",
"/"
},
StringSplitOptions.RemoveEmptyEntries
);
foreach (var part in parts)
{
var match = GuidMatcher.Match(part);
if (match.Success)
{
return Guid.Parse(match.Groups["guid"].Value);
}
}
throw new Exception(
$"Expected DatabasePath '{DatabasePath}' to contain a guid, somewhere."
);
}
);
}
private static readonly ConcurrentDictionary<string, Guid> InstanceIdCache = new();
private static readonly Regex GuidMatcher = new(
"(?<guid>[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})"
);
private int _conflictingPortRetries;
#if NETSTANDARD
private readonly FatalTempDbInitializationException _noMySqlFoundException =
new FatalTempDbInitializationException(
"Unable to detect an installed mysqld. Either supply a path as part of your initializing parameters or ensure that mysqld is in your PATH"
);
#else
private readonly FatalTempDbInitializationException _noMySqlFoundException =
new FatalTempDbInitializationException(
"Unable to detect an installed mysqld. Either supply a path as part of your initializing parameters or ensure that mysqld is in your PATH or install as a windows service"
);
#endif
protected string SchemaName;
private AutoDeleter _autoDeleter;
private string _debugLogFile = Path.GetTempFileName();
/// <summary>
/// Construct a TempDbMySql with zero or more creation scripts and default options
/// </summary>
/// <param name="creationScripts"></param>
public TempDBMySqlBase(params string[] creationScripts)
: this(new TempDbMySqlServerSettings(), creationScripts)
{
}
/// <summary>
/// Create a TempDbMySql instance with provided options and zero or more creation scripts
/// </summary>
/// <param name="settings"></param>
/// <param name="creationScripts"></param>
public TempDBMySqlBase(
TempDbMySqlServerSettings settings,
params string[] creationScripts
)
: this(
settings,
_ =>
{
},
creationScripts
)
{
}
/// <summary>
/// Create a TempDbMySql instance with provided options, an action to run before initializing and
/// zero or more creation scripts
/// </summary>
/// <param name="settings"></param>
/// <param name="beforeInit"></param>
/// <param name="creationScripts"></param>
public TempDBMySqlBase(
TempDbMySqlServerSettings settings,
Action<object> beforeInit,
params string[] creationScripts
) : base(
o => BeforeInit(o as TempDBMySqlBase<T>, beforeInit, settings),
creationScripts
)
{
}
protected static void BeforeInit(
TempDBMySqlBase<T> self,
Action<object> beforeInit,
TempDbMySqlServerSettings settings
)
{
self.LogAction = WrapWithDebugLogger(self, settings?.Options?.LogAction);
self._autoDeleter = new AutoDeleter();
self.Settings = settings;
beforeInit?.Invoke(self);
}
private static bool FolderExists(string path)
{
return path is not null &&
Directory.Exists(path);
}
private static void EnsureFolderDoesNotExist(
string path
)
{
var container = Path.GetDirectoryName(path);
var name = Path.GetFileName(path);
var fs = new LocalFileSystem(container);
fs.DeleteRecursive(name);
}
private static Action<string> WrapWithDebugLogger(
TempDBMySqlBase<T> tempDb,
Action<string> optionsLogAction
)
{
if (optionsLogAction is null)
{
return tempDb.DebugLog;
}
return logString =>
{
tempDb.DebugLog(logString);
optionsLogAction.Invoke(logString);
};
}
/// <summary>
/// Snapshots the database and returns the path on disk
/// - will stop the server to snapshot and then restart
/// the server afterwards
/// </summary>
/// <returns></returns>
public string Snapshot()
{
return Snapshot(null);
}
/// <summary>
/// Snapshots the database to the provided path and
/// returns the path on disk
/// - will stop the server to snapshot and then restart
/// the server afterwards
/// </summary>
/// <returns></returns>
public string Snapshot(string toNewFolder)
{
return Snapshot(toNewFolder, true);
}
public string Snapshot(
string toNewFolder,
bool restartServerAfterwards
)
{
return Snapshot(
toNewFolder,
stop: true,
restart: restartServerAfterwards
);
}
private string Snapshot(
string toNewFolder,
bool stop,
bool restart
)
{
if (stop)
{
SetDbInstanceId("");
DisposeManagedConnections();
Stop();
}
var baseDir = Path.GetDirectoryName(DatabasePath);
var result = toNewFolder ?? GenerateTemplatePath();
var fs = new LocalFileSystem(baseDir);
EnsureFolderDoesNotExist(result);
fs.Copy(DatabasePath, result);
foreach (var f in DeleteDataFilesOnSnapshot)
{
var toDelete = Path.Combine(result, "data", f);
if (File.Exists(toDelete))
{
File.Delete(toDelete);
}
}
// restarting the server after having wiped the instance
// id should cause the instance id to be automagically rewritten
if (restart)
{
StartServer(MySqld);
}
return result;
}
private string GenerateTemplatePath()
{
return Path.Combine(
Path.GetDirectoryName(DatabasePath)!,
$"template-{InstanceId}-{CurrentTimestamp()}.db"
);
}
private string CurrentTimestamp()
{
return DateTime.Now.ToString(
"yyyyMMddHHmmssfff"
);
}
// ReSharper disable once StaticMemberInGenericType
private static readonly string[] DeleteDataFilesOnSnapshot =
{
"mysql-err.log",
"start-upinfo.log",
"tempdb-debug.log"
};
private string FindInstalledMySqlD()
{
using (new AutoLocker(MysqldLock))
{
return _mysqld ??= QueryForMySqld();
}
}
private string QueryForMySqld()
{
Log("Looking for mysqld in the PATH...");
var mysqld = Find.InPath("mysqld");
var shouldFindInPath = Platform.IsUnixy || Settings.Options.ForceFindMySqlInPath;
if (shouldFindInPath && mysqld is not null)
{
Log($"Found mysqld in the PATH: {mysqld}");
return mysqld;
}
if (!Platform.IsWindows)
{
Log("mysqld discovery on non-windows platforms is limited to finding within the PATH");
throw _noMySqlFoundException;
}
var servicePath = MySqlWindowsServiceFinder.FindPathToMySqlD();
// prefer the pathed mysqld, but fall back on service path if available
var resolved = mysqld ?? servicePath;
Log(
$@"mysqld from path: {
mysqld ?? "(not found)"
}; mysqld from service finder: {
servicePath ?? "(not found)"
}"
);
return resolved ?? throw _noMySqlFoundException;
}
private string MySqld =>
_mysqld ??= StoreValidCommandlineArgumentsFor(
Settings?.Options?.PathToMySqlD ?? FindInstalledMySqlD()
);
private string StoreValidCommandlineArgumentsFor(string pathToMySqlD)
{
if (string.IsNullOrWhiteSpace(pathToMySqlD) || !File.Exists(pathToMySqlD))
{
return pathToMySqlD;
}
if (MySqlArguments.ContainsKey(pathToMySqlD))
{
return pathToMySqlD;
}
using var io = ProcessIO.Start(pathToMySqlD, "--help", "--verbose");
var collected = new List<string>();
foreach (var line in io.StandardOutput)
{
var trimmed = line.Trim();
if (trimmed.StartsWith("-"))
{
var sw = trimmed.Split(' ', '=', '[');
foreach (var sub in sw)
{
if (sub.StartsWith("-"))
{
collected.Add(sub);
}
}
}
}
MySqlArguments[pathToMySqlD] = new HashSet<string>(
collected,
StringComparer.OrdinalIgnoreCase
);
return pathToMySqlD;
}
private bool IsValidArgument(string arg)
{
if (!MySqlArguments.TryGetValue(MySqld, out var validArgs))
{
throw new InvalidOperationException(
$"mysqld argument validation attempted before gathering valid args for '{MySqld}'"
);
}
return validArgs.Contains(arg);
}
private static readonly ConcurrentDictionary<string, HashSet<string>> MySqlArguments = new(
Platform.IsUnixy
? StringComparer.Ordinal
: StringComparer.OrdinalIgnoreCase
);
private static bool TemplatingIsDisabled()
{
return Env.Flag(
EnvironmentVariables.DISABLE_TEMPLATING,
false
);
}
/// <inheritdoc />
protected override void CreateDatabase()
{
Log($"mysql is version: {MySqlVersion}");
using var _ = new AutoLocker(InstanceLock);
if (IsMySql8())
{
RemoveDeprecatedOptions();
}
BootstrappedFromTemplateFolder = Settings?.Options?.TemplateDatabasePath;
if (FolderExists(BootstrappedFromTemplateFolder))
{
BootstrapFromProvidedTemplateFolder();
}
else
{
BootstrapFromScratchOrSharedTemplate();
}
RedirectDebugLogging();
// now we need the real config file, sitting in the db dir
Log($"dumping run-time defaults file into {DatabasePath}");
_autoDeleter.Add(DatabasePath);
DumpDefaultsFileAt(DatabasePath);
ConfigFilePath = DefaultMyCnf;
Port = DeterminePortToUse();
SetRootPasswordViaCli();
DisableHostNameLookupsIfRequired();
StartServer(MySqld);
CreateInitialSchema();
SetUpAutoDisposeIfRequired();
}
private void DisableHostNameLookupsIfRequired()
{
var shouldDisable = Settings.Options.DisableHostnameLookups;
if (!shouldDisable)
{
return;
}
var lines = File.ReadAllLines(DefaultMyCnf);
foreach (var line in lines)
{
if (line.Contains("skip-name-resolve"))
{
return;
}
}
File.AppendAllText(DefaultMyCnf, "\nskip-name-resolve\n");
}
private void BootstrapFromScratchOrSharedTemplate()
{
var enableSharedTemplates = Settings?.Options?.AutoTemplate ??
// mysql8 is particularly slow at startup, default
// to using a shared template when available & not disabled
IsMySql8();
var shouldUseSharedTemplate =
SharedTemplateFolderExists &&
enableSharedTemplates &&
!TemplatingIsDisabled();
if (shouldUseSharedTemplate)
{
Log($"Quicker bootstrap via shared template at {SharedTemplateFolder}");
TemplateFolderIsShared = true;
BootstrappedFromTemplateFolder = SharedTemplateFolder;
BootstrapFromProvidedTemplateFolder();
return;
}
Log("create initial database");
_startAttempts = 0;
EnsureIsRemoved(DatabasePath);
// mysql 5.7 wants an empty data base dir, so we have to use
// a temp defaults file for init only, which 8 seems to be ok with
using var tempFolder = new AutoTempFolder(
Environment.GetEnvironmentVariable(EnvironmentVariables.BASE_PATH)
);
Log($"temp folder created at {tempFolder}");
Log($"dumping defaults in temp folder {tempFolder.Path} for initialization");
DumpDefaultsFileAt(tempFolder.Path);
InitializeWith(MySqld, Path.Combine(tempFolder.Path, "my.cnf"));
StoreSharedTemplate();
}
private void StoreSharedTemplate()
{
try
{
if (SharedTemplateFolderExists)
{
return;
}
Snapshot(SharedTemplateFolder, stop: false, restart: false);
}
catch (Exception ex)
{
Log($"WARNING: unable to snapshot clean state: {ex}");
}
}
private bool SharedTemplateFolderExists =>
Directory.Exists(SharedTemplateFolder);
private string SharedTemplateFolder =>
_sharedTemplateFolder ??= DetermineSharedTemplateFolder();
private string _sharedTemplateFolder;
public bool TemplateFolderIsShared { get; private set; }
private string DetermineSharedTemplateFolder()
{
var profileDir = Environment.GetFolderPath(
Environment.SpecialFolder.UserProfile
);
return Path.Combine(
profileDir,
".cache",
"tempdb",
$"template-mysql-{MySqlVersion.Version}"
);
}
private void BootstrapFromProvidedTemplateFolder()
{
RootPasswordSet = true; // prior snapshot should have set the root password
var container = Path.GetDirectoryName(BootstrappedFromTemplateFolder);
EnsureFolderDoesNotExist(DatabasePath);
var fs = new LocalFileSystem(
container
);
var src = Path.GetFileName(BootstrappedFromTemplateFolder);
fs.Copy(src, DatabasePath);
Log($"Re-using data from {BootstrappedFromTemplateFolder} in {DatabasePath}");
}
private void RedirectDebugLogging()
{
lock (_debugLogLock)
{
var existingFile = _debugLogFile;
var expectedFile = DataFilePath("tempdb-debug.log");
if (existingFile == expectedFile)
{
return;
}
if (!File.Exists(existingFile))
{
return;
}
_debugLogFile = expectedFile;
// if we're working from a template,
// the file will already exist; if
// not, it doesn't matter
TryDo(() => File.Delete(_debugLogFile));
var targetFolder = Path.GetDirectoryName(_debugLogFile);
if (targetFolder is not null && !Directory.Exists(targetFolder))
{
Directory.CreateDirectory(targetFolder);
}
File.Move(existingFile, _debugLogFile);
}
}
private void SetUpAutoDisposeIfRequired()
{
var timeout = Settings?.Options?.InactivityTimeout;
var absoluteLifespan = Settings?.Options?.AbsoluteLifespan;
SetupAutoDispose(absoluteLifespan, timeout);
}
private void RemoveDeprecatedOptions()
{
Log("Removing NO_AUTO_CREATE_USER option (deprecated in mysql 8+)");
Settings.SqlMode = (Settings.SqlMode ?? "").Split(',')
.Where(p => p != "NO_AUTO_CREATE_USER")
.JoinWith(",");
}
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
private void SetRootPasswordViaCli(int attempt = 0)
{
if (attempt > 10)
{
throw new UnableToInitializeMySqlException(
$"Failed to set root password via cli more than 10 times, error log follows:\n{TryReadErrorLogs().JoinWith("\n")}"
);
}
var pass = $"'{Settings.Options.RootUserPassword.Replace("'", "''")}'";
using var tmpFile = new AutoTempFile(
// update root password &
$@"
create user if not exists 'root'@'localhost' identified with mysql_native_password by {pass};
alter user 'root'@'localhost' identified with mysql_native_password by {pass};
create user if not exists 'root'@'%' identified with mysql_native_password by {pass};
alter user 'root'@'%' identified with mysql_native_password by {pass};
grant all privileges on *.* to 'root'@'%' with grant option;
grant all privileges on *.* to 'root'@'localhost' with grant option;
SHUTDOWN;".Replace("\r", "")
);
var args = new[]
{
$"\"--defaults-file={DefaultMyCnf}\"",
$"\"--basedir={BaseDirOf(MySqld)}\"",
$"\"--datadir={DataDir}\"",
$"--port={Port}",
$"\"--init-file={tmpFile.Path}\"",
};
args = DisableMonitoring(args);
args = AddSocketIfRequired(args);
using var io = ProcessIO.Start(
MySqld,
args
);
var exitCode = io.WaitForExit(StartupCommandTimeout);
if (exitCode == 0)
{
RootPasswordSet = true;
// TODO: check the error log
// -> I've seen this command return 0 when there was an error,
// and no data on stderr/stdout, but data in data/mysql-err.log
// - search for Error in log
// - look for happy exit, eg: "Received SHUTDOWN from user boot. Shutting down mysqld (Version: 8.0.34)."
return;
}
if (LooksLikePortConflict(io.StandardOutputAndErrorInterleavedSnapshot.ToArray()))
{
Port = DeterminePortToUse();
SetRootPasswordViaCli(++attempt);
return;
}
if (exitCode is null)
{
var commandline = io.Commandline;
io.Kill();
KeepTemporaryDatabaseArtifactsForDiagnostics = true;
TryStoreRootUserInitSql(tmpFile);
TryStoreInitScriptForDiagnosticPurposes(commandline);
throw new UnableToInitializeMySqlException(
@$"Timed out attempting to set up root users.
Full output from attempted server startup:
{string.Join("\n", io.StandardOutputAndErrorInterleavedSnapshot)}
Please report this, attaching a zip file of '{DatabasePath}'"
);
}
var stdout = new LogSource("stdout", io.StandardOutput.JoinWith("\n"));
var stderr = new LogSource("stderr", io.StandardError.JoinWith("\n"));
var errorLog = new LogSource("mysql-err.log", TryReadErrorLogs());
throw new UnableToInitializeMySqlException(
$"Unable to set root password via cli:\n{Collect(stdout, stderr, errorLog)}"
);
}
private void TryStoreRootUserInitSql(AutoTempFile tmpFile)
{
var script = Path.Combine(DataDir, "init-root-users.sql");
var toCopy = tmpFile.Path;
try
{
Retry.Max(5).Times(() => File.Copy(toCopy, script));
}
catch
{
// suppress
}
}
private void TryStoreInitScriptForDiagnosticPurposes(string commandline)
{
try
{
Retry.Max(5).Times(
() =>
{
if (Platform.IsUnixy)
{
File.WriteAllText(
Path.Combine(
DatabasePath,
"init.sh"
),
$@"#!/bin/bash
{commandline}
"
);
}
else
{
File.WriteAllText(
Path.Combine(
DatabasePath,
"init.bat"
),
commandline
);
}
}
);
}
catch
{
// suppress
}
}
private int StartupCommandTimeout =>
Env.Integer(
EnvironmentVariables.STARTUP_COMMAND_TIMEOUT,
fallback: Defaults.DEFAULT_STARTUP_COMMAND_TIMEOUT,
min: Defaults.MIN_STARTUP_COMMAND_TIMEOUT,
max: Defaults.MAX_STARTUP_COMMAND_TIMEOUT
);
private int InitTimeout =>
Env.Integer(
EnvironmentVariables.INIT_TIMEOUT,
fallback: Defaults.DEFAULT_STARTUP_COMMAND_TIMEOUT,
min: Defaults.MIN_STARTUP_COMMAND_TIMEOUT,
max: Defaults.MAX_STARTUP_COMMAND_TIMEOUT
);
private int PollInterval =>
Env.Integer(
EnvironmentVariables.POLL_INTERVAL,
fallback: Defaults.DEFAULT_POLL_INTERVAL,
min: Defaults.MIN_POLL_INTERVAL,
max: Defaults.MAX_POLL_INTERVAL
);
private string Collect(
params LogSource[] sources
)
{
var result = new List<string>();
foreach (var src in sources)
{
if (string.IsNullOrWhiteSpace(src.Content))
{
continue;
}
result.Add($"{src.Name}:");
result.Add($" {src.Content}");
}
return string.Join("\n", result);
}
private class LogSource
{
public string Name { get; }
public string Content { get; }
public LogSource(
string name,
string[] lines
) : this(name, string.Join("\n", lines ?? Array.Empty<string>()))
{
}
public LogSource(
string name,
string content
)
{
Name = name;
Content = content;
}
}
private string[] TryReadErrorLogs()
{
var filename = "mysql-err.log";
var logFile = FindFirstExistingFile(
// mysql 5
Path.Combine(DatabasePath, filename),
// mysql 8
Path.Combine(DataDir, filename)
);
if (logFile is null)
{
Log($"no {filename} found under {DatabasePath}");
return Array.Empty<string>();
}
try
{
return File.ReadLines(logFile)
.ToArray();
}
catch (Exception ex)
{
Log($"Can't read from {logFile}: {ex}");
return Array.Empty<string>();
}
}
public void CloseAllConnections()
{
using var conn = base.OpenConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = "show processlist";
using var reader = cmd.ExecuteReader();
var pids = new List<string>();
while (reader.NextResult())
{
var pid = reader["Id"].ToString();
pids.Add(pid);
}
foreach (var pid in pids)
{
cmd.CommandText = $"kill {pid}";
// ReSharper disable once AccessToDisposedClosure
TryDo(() => cmd.ExecuteNonQuery());
}
}
public override string DumpSchema()
{
// TODO: rather query INFORMATION_SCHEMA and do the work internally
var mysqldHome = Path.GetDirectoryName(MySqld);
// ReSharper disable once AssignNullToNotNullAttribute
var mysqldump = Path.Combine(mysqldHome, "mysqldump");
if (Platform.IsWindows)
{
mysqldump += ".exe";
}
if (!File.Exists(mysqldump))
{
mysqldump = Find.InPath("mysqldump");
if (mysqldump is null)
{
throw new InvalidOperationException(
$"Unable to find mysqldump in path"
);
}
}
using var io = ProcessIO.Start(
mysqldump,
"-u",
"root",
$"--password={Settings.Options.RootUserPassword}",
"-h",