ulysseskao
2016-05-04 94527026b113a1ca05fdee94879fdc32c4471ab8
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
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Linq;
using System.Xml;
using Amib.Threading;
using CCSTrace.CCS.Domain;
using CCSTrace.CCS.Object;
using Iesi.Collections.Generic;
using NLog;
 
namespace CCSTrace.CCS
{
    public class CcsMain
    {
        private const string DbConfigFilename = "DBConfig.xml";
 
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        private static CcsMain _instance;
 
        private readonly List<string> _processingCases = new List<string>();
        //Record the case when the case's FDR processed by another
        private readonly SortedSet<int> _processingFdr = new SortedSet<int>();
        // private readonly object _syncDbQueue = new object();
        // private readonly Queue<OracleConnection> _dbQueue = new Queue<OracleConnection>();
        private readonly object _syncProcessingCases = new object();
        private readonly object _syncProcessingFdrs = new object();
        private readonly object _syncWaitingCases = new object();
 
        private readonly List<KeyValuePair<string, int>> _waitingCases = new List<KeyValuePair<string, int>>();
 
 
        // private readonly int _connectionCount = 1;
        private OracleConnection _mainConn;
 
        private SmartThreadPool _mainjobThreadPool;
 
        private IWorkItemsGroup _wigFinsh;
        private IWorkItemsGroup _wigNextJobs;
        private IWorkItemsGroup _wigProcess;
 
 
        public string AppDataPath { get; set; }
 
        public static CcsMain Instance => _instance ?? (_instance = new CcsMain());
 
        public void Startup()
        {
            Logger.Info("CCSMain Startup.");
 
            try
            {
                ReadConfigXml();
                Logger.Info("CCSMain ReadConfigXml Complete.");
 
                if (_mainConn == null)
                    _mainConn = CreateConnection();
                Logger.Info("CCSMain has been connected database.");
 
                GlobalVariable.CcsCodelist = new CcsCodelist(_mainConn);
                GlobalVariable.EosCodelist = new EosCodelist(_mainConn);
 
                /*
                for (var i = 0; i < _connectionCount; i++)
                {
                    lock (_syncDbQueue) _dbQueue.Enqueue(CreateConnection());
                }
                */
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
                throw;
            }
 
            AddrContrast.Instance.Initialize(_mainConn);
            AlarmData.Instance.Initialize(_mainConn);
 
            var stpStartInfo = new STPStartInfo
            {
                StartSuspended = true,
                IdleTimeout = GlobalVariable.IdleTimeout*1000,
                MaxWorkerThreads = GlobalVariable.MaxThreadSize,
                MinWorkerThreads = GlobalVariable.MinThreadSize
            };
            _mainjobThreadPool = new SmartThreadPool(stpStartInfo);
            var wigStartInfo = new WIGStartInfo
            {
                FillStateWithArgs = true
            };
            _wigProcess = _mainjobThreadPool.CreateWorkItemsGroup(1, wigStartInfo);
            _wigFinsh = _mainjobThreadPool.CreateWorkItemsGroup(1, wigStartInfo);
            _wigNextJobs = _mainjobThreadPool.CreateWorkItemsGroup(1, wigStartInfo);
 
            _mainjobThreadPool.Start();
            _wigNextJobs.Start();
            _wigProcess.Start();
            _wigFinsh.Start();
 
            Logger.Info("Create Thread Pool.");
 
            // doNextJob
            _wigNextJobs.QueueWorkItem(DoNextJobs);
            /*
            CCSEventRecord ccsEventRecord = GetWaitRecord(_mainConn);
 
            if (ccsEventRecord != null)
            {
                OracleConnection conn;
                lock (_syncDbQueue) conn = _dbQueue.Dequeue();
                ProcessCase(ccsEventRecord, conn);
            }
            */
        }
 
        public void Shutdown()
        {
            _mainjobThreadPool.Shutdown(true, 1000);
            _mainjobThreadPool.Dispose();
            _mainjobThreadPool = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
 
        private void DoNextJobs()
        {
            Logger.Debug("Enter DoNextJobs");
            var conn = CreateConnection();
 
            try
            {
                var ccsEventRecord = GetWaitRecord(conn);
 
                if (ccsEventRecord != null)
                {
                    _wigProcess.QueueWorkItem(ProcessCase, ccsEventRecord);
                }
            }
            finally
            {
                conn?.Close();
                Logger.Debug("Leave DoNextJobs");
            }
        }
 
        public void AcceptEvent(CCSEventRecord ccsEventRecord)
        {
            _mainjobThreadPool.QueueWorkItem(AcceptWebServiceEvent, ccsEventRecord);
        }
 
        private void AcceptWebServiceEvent(CCSEventRecord ccsEventRecord)
        {
            Logger.Debug("Enter AcceptWebServiceEvent");
            var conn = CreateConnection();
 
            try
            {
                if (InsertCCSEventRecord(ccsEventRecord, conn))
                {
                    _wigNextJobs.QueueWorkItem(DoNextJobs);
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
            }
            finally
            {
                conn?.Close();
                Logger.Debug("Leave AcceptWebServiceEvent");
            }
        }
 
 
        private void ReadConfigXml()
        {
            XmlReader reader = null;
 
            try
            {
                var file = Path.Combine(AppDataPath, DbConfigFilename);
                // 建立 XML 讀取器
                var settings = new XmlReaderSettings
                {
                    IgnoreComments = true, // 不處理註解
                    IgnoreWhitespace = true, // 跳過空白
                    ValidationType = ValidationType.None // 不驗證任何資料
                };
                reader = XmlReader.Create(file, settings);
 
                // 進入讀取主要部分
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element:
                            var localName = reader.LocalName; // 取得標籤名稱
 
                            // Step 3: 讀取 FileInfo 標籤的屬性
                            if (localName.Equals("DBSetting"))
                            {
                                GlobalVariable.ConnectionString =
                                    $"Data source={reader["DataSource"]};User Id={reader["UserId"]};Password={reader["Password"]};";
                                GlobalVariable.TraceConnectionString =
                                    $"{reader["UserId"]}/{reader["Password"]}@{reader["DataSource"]}";
                                var token = reader["ConnectionCount"];
                                if (token != null)
                                {
                                    GlobalVariable.MaxConnectionCount = int.Parse(token);
                                }
                                token = reader["ShowError"];
                                if (token != null)
                                {
                                    GlobalVariable.ShowError = bool.Parse(token);
                                }
                            }
                            else if (localName.Equals("ThreadSetting"))
                            {
                                var token = reader["maxThreadSize"];
                                if (token != null)
                                {
                                    GlobalVariable.MaxThreadSize = int.Parse(token);
                                }
                                token = reader["minThreadSize"];
                                if (token != null)
                                {
                                    GlobalVariable.MinThreadSize = int.Parse(token);
                                }
                            }
 
                            break;
                    }
                }
                reader.Close();
            }
            catch (XmlException xe)
            {
                Logger.Error(xe, xe.Message);
                reader?.Close();
            }
        }
 
        private OracleConnection CreateConnection()
        {
            var builder = new OracleConnectionStringBuilder(GlobalVariable.ConnectionString)
            {
                MaxPoolSize = GlobalVariable.MaxConnectionCount,
                MinPoolSize = 1,
                Pooling = true
            };
            var connectstring = builder.ToString();
 
            var dbConn = new OracleConnection(connectstring);
            dbConn.Open();
            return dbConn;
        }
 
        private bool InsertCCSEventRecord(CCSEventRecord ccsEventRecord, OracleConnection conn)
        {
            OracleTransaction transaction = null;
 
            try
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
 
                transaction = conn.BeginTransaction();
 
                if (ccsEventRecord.InsertDb(conn, transaction))
                {
                    var ccsEventQuery = new CCSEventQuery
                    {
                        CcsId = ccsEventRecord.CcsId,
                        Meter = ccsEventRecord.Meter,
                        CaseStatus = (int) CCSCaseState.EventInitial,
                        ChangeTime = ccsEventRecord.AcceptTime
                    };
 
 
                    if (ccsEventQuery.Insert(conn, transaction))
                        transaction.Commit();
                    else
                    {
                        if (transaction.Connection.State == ConnectionState.Open)
                            transaction.Rollback();
 
                        throw new Exception("案件未受理成功。");
                    }
                }
                else
                {
                    if (transaction.Connection.State == ConnectionState.Open)
                        transaction.Rollback();
 
                    throw new Exception("案件未受理成功。");
                }
            }
            catch (OracleException e)
            {
                Logger.Error(e, e.Message);
 
                if (transaction != null && (transaction.Connection.State == ConnectionState.Open))
                    transaction.Rollback();
 
                throw;
            }
            catch (Exception ex)
            {
                Logger.Error(ex, ex.Message);
 
                if (transaction != null && (transaction.Connection.State == ConnectionState.Open))
                    transaction.Rollback();
 
                throw;
            }
 
            return true;
        }
 
        private void ProcessCase(CCSEventRecord ccsEventRecord)
        {
            Logger.Debug("Enter ProcessCase");
            OracleConnection conn = CreateConnection();
            try
            {
                if (conn.State == ConnectionState.Closed)
                    conn.Open();
 
                var processEvent = new ProcessEvent();
                processEvent.Run(ccsEventRecord, conn, GlobalVariable.TraceConnectionString);
 
                _wigNextJobs.QueueWorkItem(DoNextJobs);
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message);
            }
            Logger.Debug("Leave ProcessCase");
        }
 
        // [MethodImpl(MethodImplOptions.Synchronized)]
        private CCSEventRecord GetWaitRecord(OracleConnection conn)
        {
            var processCcsid = "";
            var ccsid = "";
            CCSEventRecord ccsEventRecord = null;
 
            lock (_syncWaitingCases)
            {
                foreach (var obj in _waitingCases)
                {
                    var ccsId = obj.Key;
                    var fdrid = obj.Value;
 
                    if (ContainProcessingFdr(fdrid)) //該條饋線仍有案件在處理中
                        processCcsid = processCcsid + "'" + ccsid + "',";
                    else
                    {
                        ccsid = ccsId;
                        _waitingCases.Remove(obj);
                        break;
                    }
                }
            }
 
            if (ccsid.Length == 0) //沒有因同饋線而在等候中的案件
            {
                var sqlStmt =
                    "SELECT Q.CCSID AS CCSID FROM CCS.EVENTQUERY Q,CCS.EVENTRECORD R WHERE Q.CASESTATUS IN (" +
                    (int) CCSCaseState.EventInitial + "," +
                    (int) CCSCaseState.EventProcess + ")";
 
                lock (_processingCases)
                {
                    processCcsid = _processingCases.Aggregate(processCcsid,
                        (current, item) => current + "'" + item + "',");
                }
 
                if (processCcsid.Length != 0)
                    sqlStmt = sqlStmt + " AND Q.CCSID NOT IN (" + processCcsid.Substring(0, processCcsid.Length - 1) +
                              ")";
 
                sqlStmt = sqlStmt + " AND Q.CCSID = R.CCSID AND ROWNUM < 2 ORDER BY Q.CHANGETIME";
                var command = new OracleCommand(sqlStmt, conn);
                var reader = command.ExecuteReader();
 
                try
                {
                    if (reader.Read())
                        ccsid = reader["CCSID"].ToString();
                }
                catch (Exception e)
                {
                    Logger.Error(e, e.Message);
                }
                finally
                {
                    reader.Close();
                    command.Dispose();
                }
            }
 
            if (ccsid.Length != 0)
                ccsEventRecord = new CCSEventRecord(ccsid, conn);
 
            if (ccsEventRecord != null)
            {
                var ccsEventQuery = new CCSEventQuery
                {
                    CcsId = ccsEventRecord.CcsId,
                    CaseStatus = (int) CCSCaseState.EventProcess
                };
                //先將EVETNQUERY的案件狀態改為開始處理
 
                var transaction = conn.BeginTransaction();
 
                try
                {
                    if (ccsEventQuery.UpdateCaseStatus(conn, transaction))
                    {
                        Logger.Info("更新EVENTQUERY的案件狀態為處理中.(CCSID = " + ccsEventRecord.CcsId + ")");
                        transaction.Commit();
                        lock (_syncProcessingCases)
                        {
                            _processingCases.Add(ccsEventRecord.CcsId);
                        }
                    }
                    else
                    {
                        Logger.Error("無法更新EVENTQUERY的案件狀態.(CCSID = " + ccsEventRecord.CcsId + ")");
 
                        if (transaction.Connection.State == ConnectionState.Open)
                            transaction.Rollback();
                    }
                }
                catch (Exception e)
                {
                    if (transaction.Connection.State == ConnectionState.Open)
                        transaction.Rollback();
 
                    Logger.Error(e, e.Message);
                    ccsEventRecord = null;
                }
            }
 
            return ccsEventRecord;
        }
 
        public void AddWaitingCases(string ccsId, int fdrid)
        {
            lock (_syncWaitingCases)
            {
                _waitingCases.Add(new KeyValuePair<string, int>(ccsId, fdrid));
            }
        }
 
        public void AddProcessingFdr(int fdrid)
        {
            lock (_syncProcessingFdrs)
            {
                _processingFdr.Add(fdrid);
            }
        }
 
        public bool ContainProcessingFdr(int fdrid)
        {
            lock (_syncProcessingFdrs)
            {
                return _processingFdr.Contains(fdrid);
            }
        }
 
        public void RemoveProcessingFdr(int fdrId)
        {
            lock (_syncProcessingFdrs)
            {
                _processingFdr.Remove(fdrId);
            }
        }
 
        public void RemoveProcessingCases(string ccsId)
        {
            lock (_syncProcessingCases)
            {
                _processingCases.Remove(ccsId);
            }
        }
    }
}