ConnectionLogdbService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. using Dapper;
  2. using EVCB_OCPP.Domain;
  3. using EVCB_OCPP.WSServer.Helper;
  4. using log4net;
  5. using Microsoft.Data.SqlClient;
  6. using Microsoft.EntityFrameworkCore;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.Logging;
  9. using NLog.Fluent;
  10. using OCPPServer.Protocol;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Data;
  14. using System.Diagnostics;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Threading.Tasks;
  18. using static System.Runtime.InteropServices.JavaScript.JSType;
  19. namespace EVCB_OCPP.WSServer.Service;
  20. public interface IConnectionLogdbService
  21. {
  22. void WarmUpLog();
  23. void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false);
  24. }
  25. public class ConnectionLogdbService : IConnectionLogdbService
  26. {
  27. public const string LimitConfigKey = "ConnectionLogDbLimit";
  28. public ConnectionLogdbService(
  29. IDbContextFactory<ConnectionLogDBContext> connectionLogdbContextFactory,
  30. SqlConnectionFactory<ConnectionLogDBContext> sqlConnectionFactory,
  31. ILogger<ConnectionLogdbService> logger,
  32. IConfiguration configuration)
  33. {
  34. this.connectionLogdbContextFactory = connectionLogdbContextFactory;
  35. this.sqlConnectionFactory = sqlConnectionFactory;
  36. this.logger = logger;
  37. //connectionLogdbConnectionString = configuration.GetConnectionString("MeterValueDBContext");
  38. var opLimit = GetLimit(configuration);
  39. this.queueHandler = new(WriteMachineLog, opLimit);
  40. InitInsertConnectonLogHandler();
  41. }
  42. private readonly IDbContextFactory<ConnectionLogDBContext> connectionLogdbContextFactory;
  43. private readonly SqlConnectionFactory<ConnectionLogDBContext> sqlConnectionFactory;
  44. private readonly ILogger<ConnectionLogdbService> logger;
  45. private readonly QueueHandler<MachineLog> queueHandler;
  46. //private readonly string connectionLogdbConnectionString;
  47. private readonly Queue<string> _existTables = new();
  48. private GroupSingleHandler<MachineLog> insertConnectonLogHandler;
  49. public void WarmUpLog()
  50. {
  51. try
  52. {
  53. using (var log = connectionLogdbContextFactory.CreateDbContext())
  54. {
  55. log.MachineConnectionLog.ToList();
  56. }
  57. }
  58. catch (Exception ex)
  59. {
  60. Console.WriteLine(ex.ToString());
  61. }
  62. }
  63. public void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  64. {
  65. var log = new MachineLog(clientData, data, messageType, errorMsg, isSent);
  66. //queueHandler.Enqueue(log);
  67. //WriteMachineLog(log);
  68. insertConnectonLogHandler.HandleAsync(log);
  69. //InsertWithDapper(log);
  70. }
  71. private async Task InsertWithDapper(MachineLog log)
  72. {
  73. var watch = Stopwatch.StartNew();
  74. long t0, t1, t2, t3;
  75. var workTime = DateTime.UtcNow;
  76. if (!await GetTableExist(workTime))
  77. {
  78. t0 = watch.ElapsedMilliseconds;
  79. await WriteMachineLog(log);
  80. watch.Stop();
  81. t1 = watch.ElapsedMilliseconds;
  82. if (t1 > 500)
  83. {
  84. logger.LogWarning("ConnectionLog InsertWithDapper {0}/{1}", t0, t1);
  85. }
  86. return;
  87. }
  88. t0 = watch.ElapsedMilliseconds;
  89. var tableName = GetTableName(workTime);
  90. string command = $"""
  91. INSERT INTO {tableName} (CreatedOn, ChargeBoxId, MessageType, Data, Msg, IsSent, EVSEEndPoint, Session)
  92. VALUES (@CreatedOn, @ChargeBoxId, @MessageType, @Data, @Msg, @IsSent, @EVSEEndPoint, @Session);
  93. """;
  94. var parameters = new DynamicParameters();
  95. parameters.Add("CreatedOn", workTime, DbType.DateTime);
  96. parameters.Add("ChargeBoxId", log.clientData.ChargeBoxId == null ? "unknown" : log.clientData.ChargeBoxId.Replace("'", "''"), DbType.String, size:50); ;
  97. parameters.Add("MessageType", log.messageType.Replace("'", "''"), DbType.String, size: 50);
  98. parameters.Add("Data", log.data.Replace("'", "''"), DbType.String);
  99. parameters.Add("Msg", log.errorMsg.Replace("'", "''"), DbType.String, size: 200);
  100. parameters.Add("IsSent", log.isSent, DbType.Boolean);
  101. parameters.Add("EVSEEndPoint", log.clientData.RemoteEndPoint == null ? "123" : log.clientData.RemoteEndPoint.ToString(), DbType.String, size: 25);
  102. parameters.Add("Session", log.clientData.SessionID == null ? "123" : log.clientData.SessionID, DbType.String, size: 36);
  103. t1 = watch.ElapsedMilliseconds;
  104. using var sqlConnection = await sqlConnectionFactory.CreateAsync();
  105. t2 = watch.ElapsedMilliseconds;
  106. await sqlConnection.ExecuteAsync(command, parameters);
  107. watch.Stop();
  108. t3 = watch.ElapsedMilliseconds;
  109. if (t3 > 1000)
  110. {
  111. logger.LogWarning("ConnectionLog Dapper {0}/{1}/{2}/{3}", t0, t1, t2, t3);
  112. }
  113. }
  114. private void InitInsertConnectonLogHandler()
  115. {
  116. if (insertConnectonLogHandler is not null)
  117. {
  118. throw new Exception($"{nameof(InitInsertConnectonLogHandler)} should only called once");
  119. }
  120. insertConnectonLogHandler = new GroupSingleHandler<MachineLog>(
  121. //BulkInsertWithBulkCopy,
  122. BundleInsertWithDapper,
  123. //loggerFactory.CreateLogger("InsertMeterValueHandler")
  124. logger,
  125. workerCnt: 1
  126. );
  127. }
  128. private async Task WriteMachineLog(MachineLog log)
  129. {
  130. var watcher = Stopwatch.StartNew();
  131. try
  132. {
  133. if (log.clientData == null || string.IsNullOrEmpty(log.data)) return;
  134. if (log.clientData.ChargeBoxId == null)
  135. {
  136. logger.LogCritical(log.clientData.Path + "]********************session ChargeBoxId null sessionId=" + log.clientData.SessionID);
  137. }
  138. using (var db = await connectionLogdbContextFactory.CreateDbContextAsync())
  139. {
  140. string sp = "[dbo].[uspInsertMachineConnectionLog] @CreatedOn," +
  141. "@ChargeBoxId,@MessageType,@Data,@Msg,@IsSent,@EVSEEndPoint,@Session";
  142. var dd = DateTime.UtcNow;
  143. SqlParameter[] parameter =
  144. {
  145. new SqlParameter("CreatedOn", SqlDbType.DateTime){ Value = dd },
  146. new SqlParameter("ChargeBoxId", SqlDbType.NVarChar, 50){ Value= log.clientData.ChargeBoxId==null?"unknown":log.clientData.ChargeBoxId.Replace("'","''") },
  147. new SqlParameter("MessageType", SqlDbType.NVarChar , 50){ Value = log.messageType.Replace("'","''")},
  148. new SqlParameter("Data", SqlDbType.NVarChar, -1) { Value = log.data.Replace("'", "''") },
  149. new SqlParameter("Msg", SqlDbType.NVarChar, 200) { Value = log.errorMsg.Replace("'", "''") },
  150. new SqlParameter("IsSent", SqlDbType.Bit) { Value = log.isSent },
  151. new SqlParameter("EVSEEndPoint", SqlDbType.NVarChar, 25) { Value = log.clientData.RemoteEndPoint == null ? "123" : log.clientData.RemoteEndPoint.ToString() },
  152. new SqlParameter("Session", SqlDbType.NVarChar, 36) { Value = log.clientData.SessionID == null ? "123" : log.clientData.SessionID }
  153. };
  154. await db.Database.ExecuteSqlRawAsync(sp, parameter);
  155. }
  156. }
  157. catch (Exception ex)
  158. {
  159. logger.LogError(ex.ToString());
  160. }
  161. watcher.Stop();
  162. if (watcher.ElapsedMilliseconds > 1000)
  163. {
  164. logger.LogWarning("WriteMachineLog too long {0}", watcher.ElapsedMilliseconds);
  165. }
  166. }
  167. private async Task BundleInsertWithDapper(IEnumerable<MachineLog> parms)
  168. {
  169. var watch = Stopwatch.StartNew();
  170. long t0, t1, t2, t3, t4;
  171. var workTime = DateTime.UtcNow;
  172. var parmsList = parms.ToList();
  173. if (parmsList.Count == 0)
  174. {
  175. return;
  176. }
  177. var candidate = parmsList[0];
  178. if (!await GetTableExist(workTime))
  179. {
  180. t0 = watch.ElapsedMilliseconds;
  181. await WriteMachineLog(candidate);
  182. watch.Stop();
  183. t1 = watch.ElapsedMilliseconds;
  184. if (t1 > 500)
  185. {
  186. logger.LogWarning("ConnectionLog InsertWithDapper {0}/{1}", t0, t1);
  187. }
  188. parmsList.Remove(candidate);
  189. }
  190. t0 = watch.ElapsedMilliseconds;
  191. t1 = watch.ElapsedMilliseconds;
  192. using SqlConnection sqlConnection = await sqlConnectionFactory.CreateAsync();
  193. using var tans = await sqlConnection.BeginTransactionAsync();
  194. t2 = watch.ElapsedMilliseconds;
  195. var tableName = GetTableName(workTime);
  196. string command = $"""
  197. INSERT INTO {tableName} (CreatedOn, ChargeBoxId, MessageType, Data, Msg, IsSent, EVSEEndPoint, Session)
  198. VALUES (@CreatedOn, @ChargeBoxId, @MessageType, @Data, @Msg, @IsSent, @EVSEEndPoint, @Session);
  199. """;
  200. foreach (var log in parmsList)
  201. {
  202. var parameters = new DynamicParameters();
  203. parameters.Add("CreatedOn", workTime, DbType.DateTime);
  204. parameters.Add("ChargeBoxId", log.clientData.ChargeBoxId == null ? "unknown" : log.clientData.ChargeBoxId.Replace("'", "''"), DbType.String, size: 50); ;
  205. parameters.Add("MessageType", log.messageType.Replace("'", "''"), DbType.String, size: 50);
  206. parameters.Add("Data", log.data.Replace("'", "''"), DbType.String);
  207. parameters.Add("Msg", log.errorMsg.Replace("'", "''"), DbType.String, size: 200);
  208. parameters.Add("IsSent", log.isSent, DbType.Boolean);
  209. parameters.Add("EVSEEndPoint", log.clientData.RemoteEndPoint == null ? "123" : log.clientData.RemoteEndPoint.ToString(), DbType.String, size: 25);
  210. parameters.Add("Session", log.clientData.SessionID == null ? "123" : log.clientData.SessionID, DbType.String, size: 36);
  211. await sqlConnection.ExecuteAsync(command, parameters, tans);
  212. }
  213. t3 = watch.ElapsedMilliseconds;
  214. await tans.CommitAsync();
  215. watch.Stop();
  216. t4 = watch.ElapsedMilliseconds;
  217. if (t4 > 1000)
  218. {
  219. logger.LogWarning("MachineLog Bundle Dapper {0}/{1}/{2}/{3}/{4}/{5}", t0, t1, t2, t3, t4, parms.Count());
  220. }
  221. }
  222. private async Task BulkInsertWithBulkCopy(IEnumerable<MachineLog> parms)
  223. {
  224. var watcher = Stopwatch.StartNew();
  225. long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
  226. var parmsList = parms.ToList();
  227. if (parmsList.Count == 0)
  228. {
  229. return;
  230. }
  231. var workTime = DateTime.UtcNow;
  232. if (!await GetTableExist(workTime))
  233. {
  234. var candidate = parmsList.First();
  235. await WriteMachineLog(candidate);
  236. parmsList.Remove(candidate);
  237. }
  238. t0 = watcher.ElapsedMilliseconds;
  239. var table = new DataTable();
  240. table.Columns.Add("CreatedOn");
  241. table.Columns.Add("ChargeBoxId");
  242. table.Columns.Add("MessageType");
  243. table.Columns.Add("Data");
  244. table.Columns.Add("Msg");
  245. table.Columns.Add("IsSent");
  246. table.Columns.Add("EVSEEndPoint");
  247. table.Columns.Add("Session");
  248. foreach (var param in parmsList)
  249. {
  250. var row = table.NewRow();
  251. row["CreatedOn"] = workTime;
  252. row["ChargeBoxId"] = param.clientData.ChargeBoxId == null ? "unknown" : param.clientData.ChargeBoxId.Replace("'", "''");
  253. row["MessageType"] = param.messageType.Replace("'", "''");
  254. row["Data"] = param.data.Replace("'", "''");
  255. row["Msg"] = param.errorMsg.Replace("'", "''");
  256. row["IsSent"] = param.isSent;
  257. row["EVSEEndPoint"] = param.clientData.RemoteEndPoint == null ? "123" : param.clientData.RemoteEndPoint.ToString();
  258. row["Session"] = param.clientData.SessionID == null ? "123" : param.clientData.SessionID;
  259. table.Rows.Add(row);
  260. }
  261. t1 = watcher.ElapsedMilliseconds;
  262. using SqlConnection sqlConnection = await sqlConnectionFactory.CreateAsync();
  263. using SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection);
  264. t2 = watcher.ElapsedMilliseconds;
  265. sqlBulkCopy.BatchSize = parmsList.Count();
  266. sqlBulkCopy.DestinationTableName = GetTableName(workTime);
  267. sqlBulkCopy.ColumnMappings.Add("CreatedOn", "CreatedOn");
  268. sqlBulkCopy.ColumnMappings.Add("ChargeBoxId", "ChargeBoxId");
  269. sqlBulkCopy.ColumnMappings.Add("MessageType", "MessageType");
  270. sqlBulkCopy.ColumnMappings.Add("Data", "Data");
  271. sqlBulkCopy.ColumnMappings.Add("Msg", "Msg");
  272. sqlBulkCopy.ColumnMappings.Add("IsSent", "IsSent");
  273. sqlBulkCopy.ColumnMappings.Add("EVSEEndPoint", "EVSEEndPoint");
  274. sqlBulkCopy.ColumnMappings.Add("Session", "Session");
  275. t3 = watcher.ElapsedMilliseconds;
  276. await sqlBulkCopy.WriteToServerAsync(table);
  277. watcher.Stop();
  278. t4 = watcher.ElapsedMilliseconds;
  279. if (t4 > 500)
  280. {
  281. logger.LogWarning("ConnectionLog BulkInsertWithBulkCopy Slow {0}/{1}/{2}/{3}/{4}/{5}", t0, t1, t2, t3, t4, parms.Count());
  282. }
  283. }
  284. private async ValueTask<bool> GetTableExist(DateTime tableDateTime)
  285. {
  286. var tableName = GetTableName(tableDateTime);
  287. if (_existTables.Contains(tableName))
  288. {
  289. return true;
  290. }
  291. FormattableString checkTableSql = $"SELECT Count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = {tableName}";
  292. using var db = await connectionLogdbContextFactory.CreateDbContextAsync();
  293. var resultList = db.Database.SqlQuery<int>(checkTableSql)?.ToList();
  294. if (resultList is not null && resultList.Count > 0 && resultList[0] > 0)
  295. {
  296. _existTables.Enqueue(tableName);
  297. if (_existTables.Count > 30)
  298. {
  299. _existTables.TryDequeue(out _);
  300. }
  301. return true;
  302. }
  303. return false;
  304. }
  305. private static string GetTableName(DateTime dateTime)
  306. => $"MachineConnectionLog{dateTime:yyMMdd}";
  307. private int GetLimit(IConfiguration configuration)
  308. {
  309. var limitConfig = configuration[LimitConfigKey];
  310. int limit = 10;
  311. if (limitConfig != default)
  312. {
  313. int.TryParse(limitConfig, out limit);
  314. }
  315. return limit;
  316. }
  317. }
  318. internal record MachineLog(ClientData clientData, string data, string messageType, string errorMsg, bool isSent);