-
Notifications
You must be signed in to change notification settings - Fork 0
/
Service.cs
339 lines (310 loc) · 14.4 KB
/
Service.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
/*
This file is part of MqttSql (Copyright © 2024 Guiorgy).
MqttSql is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
MqttSql is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with MqttSql. If not, see <https://www.gnu.org/licenses/>.
*/
#if !LOG && DEBUG
#define LOG
#endif
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Client.Subscribing;
using MQTTnet.Protocol;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace MqttSql
{
public class Service
{
public Service(string homeDir = null, string dirSep = "\\")
{
string macAddress = NetworkInterface
.GetAllNetworkInterfaces()
.Where(nic => nic.OperationalStatus == OperationalStatus.Up && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.Select(nic => nic.GetPhysicalAddress().ToString())
.FirstOrDefault();
this.clientId = $"{macAddress}-{Environment.MachineName}-{Environment.UserName}".Replace(' ', '.');
this.homeDir = homeDir == null ? Environment.GetEnvironmentVariable("MqttSqlHome") : homeDir;
this.dbPath = this.homeDir + (this.homeDir.EndsWith(dirSep) ? "" : dirSep) + "database.sqlite";
this.configPath = this.homeDir + (this.homeDir.EndsWith(dirSep) ? "" : dirSep) + "config.json";
DebugLog($"Home: \"{this.homeDir}\"");
DebugLog($"Database: \"{this.dbPath}\"");
DebugLog($"Configuration: \"{this.configPath}\"");
DebugLog($"ClientId: \"{this.clientId}\"");
#if LOG
this.logPath = this.homeDir + (this.homeDir.EndsWith(dirSep) ? "" : dirSep) + "logs.txt";
DebugLog($"Logs: \"{this.logPath}\"");
#endif
}
public void Start()
{
Task.Run(() =>
{
EnsureDbExists();
ReadJsonConfig();
var tables = configurations.Select(cfg => cfg.Table);
EnsureTablesExist(tables);
SubscribeToBrokers();
}, cancellationToken.Token);
}
public async Task StartAsync()
{
messageQueue = Channel.CreateUnbounded<Tuple<string, string>>();
EnsureDbExists();
ReadJsonConfig();
var tables = configurations.Select(cfg => cfg.Table);
EnsureTablesExist(tables);
SubscribeToBrokers();
await foreach ((string table, string message)
in messageQueue.Reader.ReadAllAsync(cancellationToken.Token))
{
WriteToTable(table, message);
await Task.Delay(1000);
}
}
public void Stop()
{
cancellationToken.Cancel(false);
}
private void EnsureDbExists()
{
if (!File.Exists(dbPath))
{
DebugLog($"Creating database file \"{dbPath}\"");
SQLiteConnection.CreateFile(dbPath);
}
}
private void ReadJsonConfig()
{
DebugLog($"Loading configuration \"{configPath}\":");
string json = File.ReadAllText(configPath);
DebugLog(Regex.Replace(json,
"(\"password\"\\s*:\\s*\")(.*?)(\")(,|\n|\r)",
m => m.Groups[1].Value + new string('*', m.Groups[2].Length) + '"' + m.Groups[4].Value));
configurations = JsonConvert.DeserializeObject<List<ServiceConfiguration>>(json);
DebugLog("Configuration loaded:");
foreach (var cfg in configurations)
DebugLog(cfg.ToSafeString());
}
private void EnsureTableExists(string table)
{
DebugLog($"Checking the existence of table \"{table}\"");
using (var sqlCon = new SQLiteConnection(dbPath))
{
sqlCon.Open();
string sql = "CREAT TABLE IF NOT EXISTS " + table + "("
+ "Timestamp DATETIME DEFAULT (DATETIME(CURRENT_TIMESTAMP, 'localtime')) NOT NULL PRIMARY KEY,"
+ "Message VARCHAR"
+ ")";
SQLiteCommand command = new SQLiteCommand(sql, sqlCon);
command.ExecuteNonQuery();
}
}
private void EnsureTablesExist(IEnumerable<string> tables)
{
using (var sqlCon = new SQLiteConnection("Data Source = " + dbPath + "; Version = 3;"))
{
sqlCon.Open();
using (var transaction = sqlCon.BeginTransaction())
{
using (var command = new SQLiteCommand(sqlCon))
{
command.Transaction = transaction;
var created = new HashSet<string>();
foreach (string table in tables)
{
if (created.Contains(table))
continue;
else
created.Add(table);
DebugLog($"Checking the existence of table \"{table}\"");
command.CommandText = "CREATE TABLE IF NOT EXISTS " + table + "("
+ "Timestamp DATETIME DEFAULT (DATETIME(CURRENT_TIMESTAMP, 'localtime')) NOT NULL PRIMARY KEY,"
+ "Message VARCHAR NOT NULL"
+ ");";
command.ExecuteNonQuery();
}
transaction.Commit();
}
}
}
}
private void WriteToTable(string table, string message)
{
lastSqlWrite = DateTimeOffset.Now.ToUnixTimeMilliseconds();
DebugLog($"Writing to table \"{table}\" the message: \"{message}\"");
using (var sqlCon = new SQLiteConnection("Data Source = " + dbPath + "; Version = 3;"))
{
sqlCon.Open();
string sql = "INSERT INTO " + table + "(Message) values ('" + message + "')";
SQLiteCommand command = new SQLiteCommand(sql, sqlCon);
command.ExecuteNonQuery();
}
}
private Task WriteToTableTask(string table, string message)
{
return new Task(() =>
{
lock (sqlLock)
{
while (DateTimeOffset.Now.ToUnixTimeMilliseconds() - lastSqlWrite < 1000)
Task.Delay(250);
lastSqlWrite = DateTimeOffset.Now.ToUnixTimeMilliseconds();
}
DebugLog($"Writing to table \"{table}\" the message: \"{message}\"");
using (var sqlCon = new SQLiteConnection("Data Source = " + dbPath + "; Version = 3;"))
{
sqlCon.Open();
string sql = "INSERT INTO " + table + "(Message) values ('" + message + "')";
SQLiteCommand command = new SQLiteCommand(sql, sqlCon);
command.ExecuteNonQuery();
}
});
}
private void SubscribeToBrokers()
{
var connections =
configurations
.OrderBy(cfg => $"{cfg.Host}:{cfg.Port}[{cfg.User},{cfg.Password}]")
.GroupBy(cfg => $"{cfg.Host}:{cfg.Port}[{cfg.User},{cfg.Password}]");
foreach (var congroup in connections)
{
_ = Task.Run(async () =>
{
var TopicTable = new Dictionary<string, string>(congroup.Count());
foreach (var cfg in congroup) TopicTable.Add(cfg.Topic, cfg.Table);
var connection = congroup.First();
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithClientId(clientId)
.WithTcpServer(connection.Host, connection.Port)
.WithCredentials(connection.User, connection.Password)
.Build();
bool connectionFailed = false;
mqttClient.UseDisconnectedHandler(async e =>
{
DebugLog($"Disconnected from \"{connection.Host}\"! Reason: \"{e.Reason}\"");
await Task.Delay(connectionFailed ? TimeSpan.FromMinutes(15) : TimeSpan.FromSeconds(10));
connectionFailed = true;
try
{
DebugLog($"Attempting to recconnect to \"{connection.Host}\"");
await mqttClient.ReconnectAsync(cancellationToken.Token);
connectionFailed = false;
DebugLog("Reconnected!");
}
catch
{
DebugLog("Reconnection Failed!");
cancellationToken.Cancel();
await Task.Delay(1000);
Environment.Exit(-1);
}
});
mqttClient.UseConnectedHandler(async e =>
{
DebugLog($"Connection established with \"{connection.Host}\"");
foreach ((string topic, string table) in TopicTable)
{
DebugLog($"Subscribing to \"{topic}\" topic");
await mqttClient.SubscribeAsync(
new MqttClientSubscribeOptionsBuilder()
.WithTopicFilter(topic, qualityOfServiceLevel: MqttQualityOfServiceLevel.ExactlyOnce)
.Build()
);
}
});
if (messageQueue == null)
{
mqttClient.UseApplicationMessageReceivedHandler(e =>
{
string topic = e.ApplicationMessage.Topic;
string message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
DebugLog($"Message from \"{topic}\" topic recieved: \"{message}\"");
WriteToTableTask(TopicTable[topic], message).Start();
});
}
else
{
mqttClient.UseApplicationMessageReceivedHandler(e =>
{
string topic = e.ApplicationMessage.Topic;
string message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
DebugLog($"Message from \"{topic}\" topic recieved: \"{message}\"");
messageQueue.Writer.TryWrite(Tuple.Create(TopicTable[topic], message));
});
}
DebugLog($"Connecting to \"{connection.Host}\"");
await mqttClient.ConnectAsync(options, cancellationToken.Token);
}, cancellationToken.Token);
}
}
#if !LOG
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Critical Code Smell", "S1186:Methods should not be empty")]
#endif
private void DebugLog(string message)
{
#if LOG
if ((logWrites = logWrites > 1000 ? 0 : logWrites + 1) > 1000
&& (new FileInfo(logPath) is var file) && file.Length > 100_000_000)
{
byte[] buffer;
using (BinaryReader reader = new BinaryReader(file.Open(FileMode.Open)))
{
reader.BaseStream.Position = file.Length - 1_000_000;
buffer = reader.ReadBytes(1_000_000);
}
using (BinaryWriter writer = new BinaryWriter(file.Open(FileMode.Truncate)))
{
writer.BaseStream.Position = 0;
writer.Write(buffer);
writer.Write(Encoding.UTF8.GetBytes(message + Environment.NewLine));
}
}
else
{
Console.WriteLine(message + Environment.NewLine);
File.AppendAllText(logPath, message + Environment.NewLine);
}
#endif
}
#if !LOG
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Critical Code Smell", "S1186:Methods should not be empty")]
#endif
private void DebugLog(object messageObj)
{
#if LOG
DebugLog(messageObj.ToString());
#endif
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Minor Code Smell", "S1450:Private fields only used as local variables in methods should become local variables")]
private readonly string homeDir;
private readonly string dbPath;
private readonly string configPath;
#if LOG
private readonly string logPath;
private int logWrites = 0;
#endif
private List<ServiceConfiguration> configurations;
private readonly string clientId;
private readonly CancellationTokenSource cancellationToken = new CancellationTokenSource();
private readonly static object sqlLock = new object();
private long lastSqlWrite = 0;
private Channel<Tuple<string, string>> messageQueue = null;
}
}