ConnectionLogdbService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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(WriteMachineLogEF, 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. logger.LogError(ex.Message);
  61. logger.LogError(ex.StackTrace);
  62. //Console.WriteLine(ex.ToString());
  63. }
  64. }
  65. public void WriteMachineLog(ClientData clientData, string data, string messageType, string errorMsg = "", bool isSent = false)
  66. {
  67. var log = new MachineLog(clientData, data, messageType, errorMsg, isSent);
  68. //queueHandler.Enqueue(log);
  69. //_ = WriteMachineLogEF(log);
  70. insertConnectonLogHandler.HandleAsync(log);
  71. //_ = InsertWithDapper(log);
  72. }
  73. private async Task InsertWithDapper(MachineLog log)
  74. {
  75. var watch = Stopwatch.StartNew();
  76. long t0, t1, t2, t3;
  77. var workTime = DateTime.UtcNow;
  78. if (!await GetTableExist(workTime))
  79. {
  80. t0 = watch.ElapsedMilliseconds;
  81. await WriteMachineLogEF(log);
  82. watch.Stop();
  83. t1 = watch.ElapsedMilliseconds;
  84. if (t1 > 500)
  85. {
  86. logger.LogWarning("ConnectionLog InsertWithDapper {0}/{1}", t0, t1);
  87. }
  88. return;
  89. }
  90. t0 = watch.ElapsedMilliseconds;
  91. var tableName = GetTableName(workTime);
  92. string command = $"""
  93. INSERT INTO {tableName} (CreatedOn, ChargeBoxId, MessageType, Data, Msg, IsSent, EVSEEndPoint, Session)
  94. VALUES (@CreatedOn, @ChargeBoxId, @MessageType, @Data, @Msg, @IsSent, @EVSEEndPoint, @Session);
  95. """;
  96. var parameters = new DynamicParameters();
  97. parameters.Add("CreatedOn", workTime, DbType.DateTime);
  98. parameters.Add("ChargeBoxId", log.clientData.ChargeBoxId == null ? "unknown" : log.clientData.ChargeBoxId.Replace("'", "''"), DbType.String, size:50); ;
  99. parameters.Add("MessageType", log.messageType.Replace("'", "''"), DbType.String, size: 50);
  100. parameters.Add("Data", log.data.Replace("'", "''"), DbType.String);
  101. parameters.Add("Msg", log.errorMsg.Replace("'", "''"), DbType.String, size: 200);
  102. parameters.Add("IsSent", log.isSent, DbType.Boolean);
  103. parameters.Add("EVSEEndPoint", log.clientData.RemoteEndPoint == null ? "123" : log.clientData.RemoteEndPoint.ToString(), DbType.String, size: 25);
  104. parameters.Add("Session", log.clientData.SessionID == null ? "123" : log.clientData.SessionID, DbType.String, size: 36);
  105. t1 = watch.ElapsedMilliseconds;
  106. using var sqlConnection = await sqlConnectionFactory.CreateAsync();
  107. t2 = watch.ElapsedMilliseconds;
  108. await sqlConnection.ExecuteAsync(command, parameters);
  109. watch.Stop();
  110. t3 = watch.ElapsedMilliseconds;
  111. if (t3 > 1000)
  112. {
  113. logger.LogWarning("ConnectionLog Dapper {0}/{1}/{2}/{3}", t0, t1, t2, t3);
  114. }
  115. }
  116. private void InitInsertConnectonLogHandler()
  117. {
  118. if (insertConnectonLogHandler is not null)
  119. {
  120. throw new Exception($"{nameof(InitInsertConnectonLogHandler)} should only called once");
  121. }
  122. insertConnectonLogHandler = new GroupSingleHandler<MachineLog>(
  123. //BulkInsertWithBulkCopy,
  124. BundleInsertWithDapper,
  125. //loggerFactory.CreateLogger("InsertMeterValueHandler")
  126. logger,
  127. workerCnt: 20
  128. );
  129. }
  130. private async Task WriteMachineLogEF(MachineLog log)
  131. {
  132. var watcher = Stopwatch.StartNew();
  133. try
  134. {
  135. if (log.clientData == null || string.IsNullOrEmpty(log.data)) return;
  136. if (log.clientData.ChargeBoxId == null)
  137. {
  138. logger.LogCritical(log.clientData.Path + "]********************session ChargeBoxId null sessionId=" + log.clientData.SessionID);
  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. using (var db = await connectionLogdbContextFactory.CreateDbContextAsync())
  155. {
  156. await db.Database.ExecuteSqlRawAsync(sp, parameter);
  157. }
  158. }
  159. catch (Exception ex)
  160. {
  161. logger.LogError(ex.ToString());
  162. }
  163. watcher.Stop();
  164. if (watcher.ElapsedMilliseconds > 1000)
  165. {
  166. logger.LogWarning("WriteMachineLog too long {0}", watcher.ElapsedMilliseconds);
  167. }
  168. }
  169. private async Task BundleInsertWithDapper(IEnumerable<MachineLog> parms)
  170. {
  171. var watch = Stopwatch.StartNew();
  172. long t0, t1, t2, t3, t4;
  173. var workTime = DateTime.UtcNow;
  174. var parmsList = parms.ToList();
  175. if (parmsList.Count == 0)
  176. {
  177. return;
  178. }
  179. var candidate = parmsList[0];
  180. if (!await GetTableExist(workTime))
  181. {
  182. t0 = watch.ElapsedMilliseconds;
  183. await WriteMachineLogEF(candidate);
  184. watch.Stop();
  185. t1 = watch.ElapsedMilliseconds;
  186. if (t1 > 500)
  187. {
  188. logger.LogWarning("ConnectionLog InsertWithDapper {0}/{1}", t0, t1);
  189. }
  190. parmsList.Remove(candidate);
  191. }
  192. t0 = watch.ElapsedMilliseconds;
  193. t1 = watch.ElapsedMilliseconds;
  194. using SqlConnection sqlConnection = await sqlConnectionFactory.CreateAsync();
  195. //using var trans = await sqlConnection.BeginTransactionAsync();
  196. t2 = watch.ElapsedMilliseconds;
  197. var tableName = GetTableName(workTime);
  198. string command = $"""
  199. INSERT INTO {tableName} (CreatedOn, ChargeBoxId, MessageType, Data, Msg, IsSent, EVSEEndPoint, Session)
  200. VALUES (@CreatedOn, @ChargeBoxId, @MessageType, @Data, @Msg, @IsSent, @EVSEEndPoint, @Session);
  201. """;
  202. foreach (var log in parmsList)
  203. {
  204. var parameters = new DynamicParameters();
  205. parameters.Add("CreatedOn", workTime, DbType.DateTime);
  206. parameters.Add("ChargeBoxId", log.clientData.ChargeBoxId == null ? "unknown" : log.clientData.ChargeBoxId.Replace("'", "''"), DbType.String, size: 50); ;
  207. parameters.Add("MessageType", log.messageType.Replace("'", "''"), DbType.String, size: 50);
  208. parameters.Add("Data", log.data.Replace("'", "''"), DbType.String);
  209. parameters.Add("Msg", log.errorMsg.Replace("'", "''"), DbType.String, size: 200);
  210. parameters.Add("IsSent", log.isSent, DbType.Boolean);
  211. parameters.Add("EVSEEndPoint", log.clientData.RemoteEndPoint == null ? "123" : log.clientData.RemoteEndPoint.ToString(), DbType.String, size: 25);
  212. parameters.Add("Session", log.clientData.SessionID == null ? "123" : log.clientData.SessionID, DbType.String, size: 36);
  213. await sqlConnection.ExecuteAsync(command, parameters
  214. //, trans
  215. );
  216. }
  217. t3 = watch.ElapsedMilliseconds;
  218. //await trans.CommitAsync();
  219. watch.Stop();
  220. t4 = watch.ElapsedMilliseconds;
  221. if (t4 > 1000)
  222. {
  223. logger.LogWarning("MachineLog Bundle Dapper {0}/{1}/{2}/{3}/{4}/{5}", t0, t1, t2, t3, t4, parms.Count());
  224. }
  225. }
  226. private async Task BulkInsertWithBulkCopy(IEnumerable<MachineLog> parms)
  227. {
  228. var watcher = Stopwatch.StartNew();
  229. long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
  230. var parmsList = parms.ToList();
  231. if (parmsList.Count == 0)
  232. {
  233. return;
  234. }
  235. var workTime = DateTime.UtcNow;
  236. if (!await GetTableExist(workTime))
  237. {
  238. var candidate = parmsList.First();
  239. await WriteMachineLogEF(candidate);
  240. parmsList.Remove(candidate);
  241. }
  242. t0 = watcher.ElapsedMilliseconds;
  243. var table = new DataTable();
  244. table.Columns.Add("CreatedOn");
  245. table.Columns.Add("ChargeBoxId");
  246. table.Columns.Add("MessageType");
  247. table.Columns.Add("Data");
  248. table.Columns.Add("Msg");
  249. table.Columns.Add("IsSent");
  250. table.Columns.Add("EVSEEndPoint");
  251. table.Columns.Add("Session");
  252. foreach (var param in parmsList)
  253. {
  254. var row = table.NewRow();
  255. row["CreatedOn"] = workTime;
  256. row["ChargeBoxId"] = param.clientData.ChargeBoxId == null ? "unknown" : param.clientData.ChargeBoxId.Replace("'", "''");
  257. row["MessageType"] = param.messageType.Replace("'", "''");
  258. row["Data"] = param.data.Replace("'", "''");
  259. row["Msg"] = param.errorMsg.Replace("'", "''");
  260. row["IsSent"] = param.isSent;
  261. row["EVSEEndPoint"] = param.clientData.RemoteEndPoint == null ? "123" : param.clientData.RemoteEndPoint.ToString();
  262. row["Session"] = param.clientData.SessionID == null ? "123" : param.clientData.SessionID;
  263. table.Rows.Add(row);
  264. }
  265. t1 = watcher.ElapsedMilliseconds;
  266. using SqlConnection sqlConnection = await sqlConnectionFactory.CreateAsync();
  267. using SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection);
  268. t2 = watcher.ElapsedMilliseconds;
  269. sqlBulkCopy.BatchSize = parmsList.Count();
  270. sqlBulkCopy.DestinationTableName = GetTableName(workTime);
  271. sqlBulkCopy.ColumnMappings.Add("CreatedOn", "CreatedOn");
  272. sqlBulkCopy.ColumnMappings.Add("ChargeBoxId", "ChargeBoxId");
  273. sqlBulkCopy.ColumnMappings.Add("MessageType", "MessageType");
  274. sqlBulkCopy.ColumnMappings.Add("Data", "Data");
  275. sqlBulkCopy.ColumnMappings.Add("Msg", "Msg");
  276. sqlBulkCopy.ColumnMappings.Add("IsSent", "IsSent");
  277. sqlBulkCopy.ColumnMappings.Add("EVSEEndPoint", "EVSEEndPoint");
  278. sqlBulkCopy.ColumnMappings.Add("Session", "Session");
  279. t3 = watcher.ElapsedMilliseconds;
  280. await sqlBulkCopy.WriteToServerAsync(table);
  281. watcher.Stop();
  282. t4 = watcher.ElapsedMilliseconds;
  283. if (t4 > 500)
  284. {
  285. logger.LogWarning("ConnectionLog BulkInsertWithBulkCopy Slow {0}/{1}/{2}/{3}/{4}/{5}", t0, t1, t2, t3, t4, parms.Count());
  286. }
  287. }
  288. private async ValueTask<bool> GetTableExist(DateTime tableDateTime)
  289. {
  290. var tableName = GetTableName(tableDateTime);
  291. if (_existTables.Contains(tableName))
  292. {
  293. return true;
  294. }
  295. FormattableString checkTableSql = $"SELECT Count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = {tableName}";
  296. using var db = await connectionLogdbContextFactory.CreateDbContextAsync();
  297. var resultList = await db.Database.SqlQuery<int>(checkTableSql)?.ToListAsync();
  298. if (resultList is not null && resultList.Count > 0 && resultList[0] > 0)
  299. {
  300. _existTables.Enqueue(tableName);
  301. if (_existTables.Count > 30)
  302. {
  303. _existTables.TryDequeue(out _);
  304. }
  305. return true;
  306. }
  307. return false;
  308. }
  309. private static string GetTableName(DateTime dateTime)
  310. => $"MachineConnectionLog{dateTime:yyMMdd}";
  311. private int GetLimit(IConfiguration configuration)
  312. {
  313. var limitConfig = configuration[LimitConfigKey];
  314. int limit = 10;
  315. if (limitConfig != default)
  316. {
  317. int.TryParse(limitConfig, out limit);
  318. }
  319. return limit;
  320. }
  321. }
  322. internal record MachineLog(ClientData clientData, string data, string messageType, string errorMsg, bool isSent);