-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathIntegrationTestUtils.cs
More file actions
241 lines (201 loc) · 7.51 KB
/
Copy pathIntegrationTestUtils.cs
File metadata and controls
241 lines (201 loc) · 7.51 KB
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
using System.Diagnostics;
using BTCPayServer.Plugins.Monero.Services;
using BTCPayServer.Tests;
using Microsoft.Extensions.Logging;
using Mono.Unix.Native;
using Npgsql;
using static Mono.Unix.Native.Syscall;
namespace BTCPayServer.Plugins.IntegrationTests.Monero;
public static class IntegrationTestUtils
{
private static readonly ILogger Logger = LoggerFactory
.Create(builder => builder.AddConsole())
.CreateLogger("IntegrationTestUtils");
private static readonly string ContainerWalletDir =
Environment.GetEnvironmentVariable("BTCPAY_XMR_WALLET_DAEMON_WALLETDIR") ?? "/wallet";
public static async Task CleanUpAsync(PlaywrightTester playwrightTester, bool deleteWalletFiles = true)
{
var moneroRpcProvider = playwrightTester.Server.PayTester.GetService<MoneroRpcProvider>();
await moneroRpcProvider.CloseWallet("XMR");
var walletService = playwrightTester.Server.PayTester.GetService<MoneroWalletService>();
walletService.GetWalletState().IsConnected = false;
if (playwrightTester.Server.PayTester.InContainer)
{
if (deleteWalletFiles)
{
moneroRpcProvider.DeleteAllWallets();
}
await DropDatabaseAsync(
"btcpayserver",
"Host=postgres;Port=5432;Username=postgres;Database=postgres");
}
else
{
if (deleteWalletFiles)
{
await RemoveWalletFromLocalDocker();
}
await DropDatabaseAsync(
"btcpayserver",
"Host=localhost;Port=39372;Username=postgres;Database=postgres");
}
}
private static async Task DropDatabaseAsync(string dbName, string connectionString)
{
try
{
await using var conn = new NpgsqlConnection(connectionString);
await conn.OpenAsync();
await new NpgsqlCommand($"""
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = '{dbName}'
AND pid <> pg_backend_pid();
""", conn).ExecuteNonQueryAsync();
var cmd = new NpgsqlCommand($"DROP DATABASE IF EXISTS {dbName};", conn);
await cmd.ExecuteNonQueryAsync();
Logger.LogInformation("Database {DbName} dropped successfully.", dbName);
}
catch (Exception ex)
{
Logger.LogError("Failed to drop database {DbName}: {ExMessage}", dbName, ex.Message);
}
}
public static async Task CopyWalletFilesToMoneroRpcDirAsync(PlaywrightTester playwrightTester, String walletDir)
{
Logger.LogInformation("Starting to copy wallet files");
if (playwrightTester.Server.PayTester.InContainer)
{
CopyWalletFilesInContainer(walletDir);
}
else
{
await CopyWalletFilesToLocalDocker(walletDir);
}
}
private static void CopyWalletFilesInContainer(String walletDir)
{
try
{
CopyWalletFile("wallet", walletDir);
CopyWalletFile("wallet.keys", walletDir);
CopyWalletFile("password", walletDir);
}
catch (Exception ex)
{
Logger.LogError(ex, "Failed to copy wallet files to the Monero directory.");
}
}
private static void CopyWalletFile(string name, string walletDir)
{
var resourceWalletDir = Path.Combine(AppContext.BaseDirectory, "Resources", walletDir);
var src = Path.Combine(resourceWalletDir, name);
var dst = Path.Combine(ContainerWalletDir, name);
if (!File.Exists(src))
{
return;
}
File.Copy(src, dst, overwrite: true);
// monero ownership
if (chown(dst, 980, 980) == 0)
{
return;
}
Logger.LogError("chown failed for {File}. errno={Errno}", dst, Stdlib.GetLastError());
}
private static async Task CopyWalletFilesToLocalDocker(String walletDir)
{
try
{
var fullWalletDir = Path.Combine(AppContext.BaseDirectory, "Resources", walletDir);
await RunProcessAsync("docker",
$"cp \"{Path.Combine(fullWalletDir, "wallet")}\" xmr_wallet:/wallet/wallet");
await RunProcessAsync("docker",
$"cp \"{Path.Combine(fullWalletDir, "wallet.keys")}\" xmr_wallet:/wallet/wallet.keys");
await RunProcessAsync("docker",
$"cp \"{Path.Combine(fullWalletDir, "password")}\" xmr_wallet:/wallet/password");
await RunProcessAsync("docker",
"exec xmr_wallet chown monero:monero /wallet/wallet /wallet/wallet.keys /wallet/password");
}
catch (Exception ex)
{
Logger.LogError(ex, "Failed to copy wallet files to the Monero directory.");
}
}
static async Task RunProcessAsync(string fileName, string args)
{
var psi = new ProcessStartInfo
{
FileName = fileName,
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
};
using var process = Process.Start(psi)!;
await process.WaitForExitAsync();
if (process.ExitCode != 0)
{
throw new Exception(await process.StandardError.ReadToEndAsync());
}
}
private static async Task RemoveWalletFromLocalDocker()
{
try
{
var removeWalletFromDocker = new ProcessStartInfo
{
FileName = "docker",
Arguments = "exec xmr_wallet sh -c \"rm -rf /wallet/*\"",
RedirectStandardOutput = true,
RedirectStandardError = true
};
using var process = Process.Start(removeWalletFromDocker);
if (process is null)
{
Logger.LogWarning("Failed to start docker process for wallet cleanup.");
return;
}
var stdout = await process.StandardOutput.ReadToEndAsync();
var stderr = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
if (!string.IsNullOrWhiteSpace(stdout))
{
Logger.LogInformation("Docker wallet cleanup output: {Output}", stdout);
}
if (!string.IsNullOrWhiteSpace(stderr))
{
Logger.LogWarning("Docker wallet cleanup error output: {Error}", stderr);
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Wallet cleanup via Docker failed.");
}
}
private static void DeleteWalletInContainer()
{
try
{
var walletFile = Path.Combine(ContainerWalletDir, "wallet");
var keysFile = walletFile + ".keys";
var passwordFile = Path.Combine(ContainerWalletDir, "password");
if (File.Exists(walletFile))
{
File.Delete(walletFile);
}
if (File.Exists(keysFile))
{
File.Delete(keysFile);
}
if (File.Exists(passwordFile))
{
File.Delete(passwordFile);
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Failed to delete wallet files in directory {Dir}", ContainerWalletDir);
}
}
}