프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

markus / ConvertService / ServiceBase / Markus.Service.Station / ServiceStation.cs @ ab7fe8c0

이력 | 보기 | 이력해설 | 다운로드 (21 KB)

1
using log4net;
2
using Markus.Service.DataBase;
3
using Markus.Service.DataBase.Entities;
4
using Markus.Service.DataBase.Repositories;
5
using Markus.Service.Extensions;
6
using Markus.Service.Helper;
7
using Markus.Service.IWcfService;
8
using Markus.Service.WcfService;
9
using Salaros.Configuration;
10
using System;
11
using System.Collections;
12
using System.Collections.Generic;
13
using System.ComponentModel;
14
using System.Data;
15
using System.Diagnostics;
16
using System.Globalization;
17
using System.IO;
18
using System.Linq;
19
using System.Runtime.InteropServices;
20
using System.ServiceModel;
21
using System.ServiceModel.Channels;
22
using System.ServiceModel.Dispatcher;
23
using System.ServiceProcess;
24
using System.Text;
25
using System.Threading;
26
using System.Threading.Tasks;
27
using System.Timers;
28
using static Markus.Service.Extensions.Encrypt;
29

    
30
namespace Markus.Service
31
{
32
    public partial class ServiceStation : ServiceBase
33
    {
34
        protected ILog logger = LogManager.GetLogger(typeof(ServiceStation));
35
        protected ServiceHost gWcfServiceHost;
36
        private SERVICEPROPERTIES ServiceProperty;
37

    
38
        private string ServiceID;
39
        private List<SubStationServiceItem> StationServiceList;
40
        private List<string> StationServiceIDList = new List<string>();
41
        private Service.WcfClient.StationServiceTask.StationServiceClient StationClient;
42
        private bool IsStation;
43

    
44
        private Uri gServiceHostAddress;
45

    
46
        private string MarkusDBConnectionString;
47
        private DBMSType DBMSType;
48
        private string DownloadTempFolder;
49
        private string FontsFolder;
50
        private int MultiThreadMaxPages;
51
        private int MinFontSize;
52
        private int UseResolution;
53
        private bool CreateProcessWindow;
54
        private long ReleaseWorkMemory;
55

    
56
        private int SaveStatusInterval;
57

    
58
        private bool IsReleaseItems;
59
        private readonly System.Timers.Timer timer= null;
60
        
61
        private readonly object locker = new object();
62

    
63
        private List<string> RunProjectList = new List<string>();
64

    
65
        /// <summary>
66
        /// 프로세스 카운터 자주 람다식을 사용해서 list<int>로 함.
67
        /// </summary>
68
        private List<Int64> ProcessorAffinityList;
69
        private Int64 DefaultAffinity;
70

    
71
        private string configFileName;
72

    
73
        public ServiceStation()
74
        {
75
            InitializeComponent();
76

    
77
            timer = new System.Timers.Timer(new TimeSpan(0, 0, 0,5).TotalMilliseconds);
78
            timer.Elapsed += timerWorkMethod;
79
        }
80

    
81
        /// <summary>
82
        /// Config 파일 
83
        /// </summary>
84
        public void GetApplicationConfig()
85
        {
86
            try
87
            {
88
                ConfigParser config = null;
89

    
90
                try
91
                {
92
                    configFileName = $"{typeof(ServiceStation).Name}.ini";
93
                    config = ConfigHelper.AppConfig(this.configFileName);
94
                }
95
                catch (Exception ex)
96
                {
97
                    throw new Exception("Config Read Error.", ex);
98
                }
99

    
100
                if (config != null)
101
                {
102
                    // CONVERT DATABASE 연결 문자열
103
                    MarkusDBConnectionString = AESEncrypter.Decrypt(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.MARKUS_CONNECTION_STRING));
104

    
105
                    var dbtype = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.DBTYPE);
106
                    if (string.IsNullOrWhiteSpace(dbtype))
107
                    {
108
                        throw new Exception("DBTYPE not defined in SERVICE section");
109
                    }
110
                    else
111
                    {
112
                        if (!Enum.TryParse<DBMSType>(dbtype, out DBMSType))
113
                        {
114
                            throw new Exception("DBTYPE of SERVICE is MSSQL,POSTGRESQL.");
115
                        }
116
                    }
117

    
118
                    IsStation = System.Convert.ToBoolean(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.IS_STATAION, "false"));
119

    
120
                    ServiceID = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.SERVICE_ID, Guid.Empty.ToString());
121

    
122
                    if (IsStation)
123
                    {
124
                        var servicetList = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.SERVICE_LIST, "");
125

    
126
                        if (!servicetList.IsNullOrEmpty())
127
                        {
128
                            StationServiceIDList = servicetList.Split(',').ToList();
129
                        }
130
                    }
131
                    else
132
                    {
133
                        var address = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.STATAION_ADDRESS,"");
134

    
135
                        if (!address.IsNullOrEmpty())
136
                        {
137
                            BasicHttpBinding myBinding = new BasicHttpBinding();
138
                            EndpointAddress myEndpoint = new EndpointAddress(UriHelper.UriCreate(address));
139
                            StationClient = new WcfClient.StationServiceTask.StationServiceClient(myBinding, myEndpoint);
140
                        }
141
                    }
142

    
143
                    CreateProcessWindow = System.Convert.ToBoolean(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.CREATE_WINDOW, "false"));
144

    
145
                    // PDF 임시 다운로드 폴더
146
                    DownloadTempFolder = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.DOWNLOAD_TEMP_FOLDER,"C:\\temp");
147
                    FontsFolder = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.FONTS_FOLDER, "C:\\MarkusFonts"); 
148
                    // pThraed를 이용한 컨버팅 설정.
149
                    //최대 페이지가 MultiThreadMaxPages설정까지 pThread를 적용하여 컨버팅함.
150
                    MultiThreadMaxPages = System.Convert.ToInt16(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.MULTI_TRHEAD_MAX_PAGE, "500"));
151

    
152
                    // 서비스 상태 Log 저장간격
153
                    SaveStatusInterval = System.Convert.ToInt16(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.SAVE_STATUS_INTERVAL, "5"));
154

    
155
                    //PDF에 폰트가 최소 폰트 사이즈보다 작은 사이증의 폰트가 있으면 해상도를 높여서 컨버팅함.
156
                    MinFontSize = System.Convert.ToInt16(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.MIN_FONT_SIZE, "10"));
157

    
158
                    // 사용자 설정의 해상도
159
                    // MinFontSize를 -1로 하고 UseResolution를 설정하면 해당 해상도로 컨버팅됨
160
                    UseResolution = System.Convert.ToInt16(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.USE_RESOLUTION, "0"));
161

    
162
                    // 각 프로세스의 최대 메모리 사용량
163
                    var workingMemory = System.Convert.ToDouble(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.RELEASE_WORK_MEMORY, "1.5"));
164

    
165
                    ReleaseWorkMemory = MathBytes.Bytes(workingMemory, DataSizeType.GB);
166

    
167
                    // 서비스 사용 프로젝트
168
                    var projectList = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.FITER_PROCECT,"");
169

    
170
                    if(!projectList.IsNullOrEmpty())
171
                    {
172
                        RunProjectList = projectList.Split(',').ToList();
173
                    }
174

    
175
                    // 서비스 ENDPOINT
176
                    // http://localhost/
177
                    var endpointName = config.GetValue(CONFIG_DEFINE.WCF_ENDPOINT, CONFIG_DEFINE.STATION_SERVICE_NAME);
178
                    var port = config.GetValue(CONFIG_DEFINE.WCF_ENDPOINT, CONFIG_DEFINE.STATION_PORT);
179

    
180
                    if (!string.IsNullOrWhiteSpace(endpointName) && port.IsNumber())
181
                    {
182
                        gServiceHostAddress = UriHelper.UriCreate($"http://localhost:{port}/{endpointName}");
183
                    }
184

    
185
                    // 각  ConvertService의 원격 관리를 위한 서비스 설정 로드
186
                    using (Markus.Service.DataBase.Repositories.SERVICEPROPERTIESRepository db = new DataBase.Repositories.SERVICEPROPERTIESRepository(MarkusDBConnectionString,DBMSType))
187
                    {
188
                        ServiceProperty = db.GetSingleAsync(ServiceID).GetAwaiter().GetResult();
189
                    }
190
                }
191
            }
192
            catch (Exception ex)
193
            {
194
                throw new Exception("ApplicationConfig ", ex);
195
            }
196
        }
197

    
198
        protected override void OnStart(string[] args)
199
        {
200
            try
201
            {
202
                StartService();
203
            }
204
            catch (Exception ex)
205
            {
206
                logger.Error("ServiceStation Start Error - ", ex);
207
            }
208
        }
209

    
210
        /// <summary>
211
        /// alivequeue와 process를 비교하여 정리하고
212
        /// 대기중인 아이템을 분배한다.
213
        /// </summary>
214
        private void ReleaseItems()
215
        {
216
            try
217
            {
218
                IsReleaseItems = true;
219

    
220
                System.Diagnostics.Debug.WriteLine("CleanUpAliveQueueItems start");
221
                CleanUpAliveQueueItems();
222
                System.Diagnostics.Debug.WriteLine("CleanUpAliveQueueItems end");
223

    
224
                if (IsStation)
225
                {
226
                    //if (IsDataBaseWaitingList(1))
227
                    //{
228
                    System.Diagnostics.Debug.WriteLine("ReleaseItems start");
229

    
230
                    bool reflashResult = false;
231

    
232
                    if (this.StationServiceList.Count() > 0)
233
                    {
234
                        reflashResult = ReflashSubServiceAsync().GetAwaiter().GetResult();
235
                    }
236
                    else
237
                    {
238
                        reflashResult = true;
239
                    }
240
            
241
                    if (reflashResult)
242
                    {
243
                        //if (StationServiceList.All(x => x.IsOnline))
244
                        //{
245
                            CleanUpDataBaseItems();
246
                            setDataBaseWaitingList();
247
                        //}
248
                        //else
249
                        //{
250
                        //    logger.Error("Service Any Offline");
251
                        //}
252
                    }
253
                    else
254
                    {
255
                        logger.Error("ReleaseItems - ReflashSubServiceAsync result false");
256
                    }
257

    
258

    
259
                    System.Diagnostics.Debug.WriteLine("ReleaseItems end");
260
                    //}
261
                }
262
            }
263
            catch (Exception ex)
264
            {
265
                logger.Error("get Wating Item error", ex);
266
            }
267

    
268
            IsReleaseItems = false;
269
        }
270

    
271
        /// <summary>
272
        /// System.Diagnostics.Process의 ProcessorAffinity Core 선호도를 위한 초기화
273
        /// 설정된 MultiProcessCount에 대해서 프로세스의 코어의 선호도를 지정 한다.
274
        /// 코어의 선택은 비트로 이루어 진다.
275
        /// 8코어에서 1번 코어 00000001
276
        /// 8코어에서 1번 3번 코어 00000101
277
        /// 8코어에서 1번 3번 코어 00000101
278
        /// 8코어에서 1,2,3 선택   00000111
279
        /// https://dotnetgalactics.wordpress.com/2009/10/20/how-to-set-the-processor-affinity-programatically/
280
        /// </summary>
281
        private void ProcessorAffinityInit()
282
        {
283
            ProcessorAffinityList = new List<long>();
284

    
285
            int processCount = Environment.ProcessorCount;
286
            int AffinityScope = processCount;
287

    
288
            //Process 자동 배분 
289
            DefaultAffinity = GetAffinityMask(processCount, processCount);
290

    
291
            long affinityMask = 0;
292

    
293
            while (ProcessorAffinityList.Count() < ServiceProperty.PROCESS_COUNT)
294

    
295
            for (int i = ServiceProperty.PROCESS_COUNT; i > 0; i--)
296
            {
297
                affinityMask = GetAffinityMask(processCount, i);
298

    
299
                if (Environment.UserInteractive)
300
                {
301
                    Console.WriteLine($"index{string.Format("{0:D2}", ProcessorAffinityList.Count())} - {longToBinaryString(affinityMask)}");
302
                }
303

    
304
                ProcessorAffinityList.Add(affinityMask);
305
            }
306
        }
307

    
308
        private static long GetAffinityMask(int processCount, int index)
309
        {
310
            BitArray bitArray = new BitArray(processCount);
311

    
312
            if (processCount - 1 < index)
313
            {
314
                bitArray = new BitArray(processCount, true);
315
            }
316
            else
317
            {
318
                bitArray.Set(index, true);
319
            }
320

    
321
            var bits = bitArray.Cast<bool>().Select(bit => bit ? 1 : 0);
322

    
323
            return System.Convert.ToInt64(string.Join("", bits), 2);
324
        }
325
        private static string longToBinaryString(long value)
326
        {
327
            string binary = Convert.ToString(value, 2);
328
            return binary.PadLeft(64, '0');
329
        }
330

    
331
        public void StartService()
332
        {
333
            /// 서비스 설정 로드
334
            try
335
            {
336
                this.GetApplicationConfig();
337
                logger.Info("Read Config");
338

    
339
                if (ServiceProperty != null)
340
                {
341
                    ProcessorAffinityInit();
342
                }
343
                else
344
                {
345
                    throw new Exception("StartService Error. ServiceProperty is Null");
346
                }
347

    
348
            }
349
            catch (Exception e)
350
            {
351
                throw new Exception("StartService Error. ", e);
352
            }
353

    
354
            /// pThread.dll을 리소스에서 Service 실행 디렉토리로 복사.
355
            //try
356
            //{
357
            //    // MarkusPDF.dll에서 pThread lib 사용을 위해 Insatll
358
            //    var libPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "\\convert\\libpthread.dll");
359
            //    if (!File.Exists(libPath))
360
            //    {
361
            //        Markus.Library.Installer.Install();
362
            //        logger.Info("Markus.Library.Installer Install");
363
            //    }
364
            //    else
365
            //    {
366
            //        logger.Info("Markus.Library.Installer Exists.");
367
            //    }
368

    
369
            //}
370
            //catch (Exception e)
371
            //{
372
            //    throw new Exception("Stop Installer Error. ", e);
373
            //}
374

    
375
            /// 컨버터 프로세스가 실행중인 경우 모두 중지 시킨다.
376
            try
377
            {
378
                // 기존에 실행 중이던 프로세스 종료
379
                Stopprocess();
380
                logger.Info("Stopprocess");
381
            }
382
            catch (Exception e)
383
            {
384
                throw new Exception("Stop Process Error. ", e);
385
            }
386

    
387
            /// wcf 서비스 실행
388
            try
389
            {
390
                // WCF 실행
391
                StartWcfService();
392

    
393
                if (gWcfServiceHost.BaseAddresses?.Count() > 0)
394
                {
395
                    gServiceHostAddress = gWcfServiceHost.BaseAddresses.First();
396
                }
397

    
398
                //  각 sub서비스에 컨버터 아이템을 보내기 위한 서비스 초기화
399
                if (IsStation)
400
                {
401
                    SetServiceList(this.StationServiceIDList);
402
                }
403

    
404
                logger.Info($"StartWcfService {gServiceHostAddress}");
405
            }
406
            catch (Exception e)
407
            {
408
                throw new Exception("start Wcf Service Error. ", e);
409
            }
410

    
411
            //try
412
            //{
413
            //    // Status가 4이하인 Convert Item을 다시 Convert 함. 
414
            //    setDataBaseWaitingList();
415
            //    logger.Info("setDataBaseWaitingList");
416
            //}
417
            //catch (Exception e)
418
            //{
419
            //    throw new Exception("Database Waiting List Error . ", e);
420
            //}
421

    
422
            logger.Info("Start ServiceStation");
423
            timer.Start();
424
        }
425

    
426
        private void timerWorkMethod(object sender, ElapsedEventArgs e)
427
        {
428
            if (timer.Enabled)
429
            {
430
                var _timer = (System.Timers.Timer)sender;
431
                _timer.Stop();
432

    
433
                if (!IsStop)
434
                {
435
                    StartConvert();
436
                    
437
                    _timer.Start();
438
                }
439
                else
440
                {
441
                    StopService();
442
                }
443
            }
444
            else
445
            {
446
                logger.Error("timer disable");
447
            }
448
        }
449

    
450
        private bool IsStop = false;
451
    
452
        DateTime logTime;
453
        DateTime ReleaseTime;
454

    
455

    
456
        private bool StartConvert()
457
        {
458
            //stateTimer.Change(new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0, 0, -1));
459
            try
460
            {
461
               
462
                if ((DateTime.Now - ReleaseTime) >= new TimeSpan(0, 0,1))
463
                {
464
                    if (!IsReleaseItems)
465
                    {
466
                        if (System.Environment.UserInteractive)
467
                        {
468
                            Console.WriteLine("Release Items");
469
                        }
470

    
471
                        ReleaseItems();
472
                    }
473
                    else
474
                    {
475
                        if (System.Environment.UserInteractive)
476
                        {
477
                            Console.WriteLine("pass Release Items");
478
                        }
479
                    }
480

    
481
                    ReleaseTime = DateTime.Now;
482
                }
483
              
484
                if ((DateTime.Now - logTime) >= new TimeSpan(0, 5,0))
485
                {
486
                    logTime = DateTime.Now;
487
                    logger.Info("StationService Alive Check");
488
                }
489
            }
490
            catch (Exception ex)
491
            {
492
                logger.Error("Timer Error ", ex);
493
            }
494

    
495
            return true;
496
        }
497

    
498
        public void SetServiceList(List<string> serviceList)
499
        {
500
            StationServiceList = new List<SubStationServiceItem>();
501

    
502
            using (SERVICEPROPERTIESRepository database = new SERVICEPROPERTIESRepository(MarkusDBConnectionString,DBMSType))
503
            {
504
                foreach (var item in serviceList)
505
                {
506
                    try
507
                    {
508
                        var prop = database.GetSingleAsync(item).GetAwaiter().GetResult();
509

    
510
                        if (prop != null)
511
                        {
512
                            BasicHttpBinding httpbinding = new BasicHttpBinding();
513
                            httpbinding.CloseTimeout = new TimeSpan(0, 10, 0);
514
                            httpbinding.ReceiveTimeout = new TimeSpan(0, 10, 0);
515
                            httpbinding.SendTimeout = new TimeSpan(0, 10, 0);
516
                            httpbinding.OpenTimeout = new TimeSpan(0, 10, 0);
517

    
518
                            EndpointAddress myEndpoint = new EndpointAddress(UriHelper.UriCreate(prop.SERVICE_ADDRESS));
519
                            var StationServiceClient = new WcfClient.StationServiceTask.StationServiceClient(httpbinding, myEndpoint);
520
                        
521
                       
522
                                //var items = StationServiceClient.AliveConvertList();
523
                            
524
                                StationServiceList.Add(new SubStationServiceItem
525
                                {
526
                                    Properties = prop,
527
                                    Service = StationServiceClient
528
                                });
529
                        }
530

    
531
                    }
532
                    catch (Exception ex)
533
                    {
534
                        logger.Error($"Service Properties Error  ID : { item }",ex);
535
                    }
536
                }
537
            }
538
        }
539

    
540
        protected override void OnStop()
541
        {
542
            try
543
            {
544
                IsStop = true;
545
            }
546
            catch (Exception e)
547
            {
548
                logger.Error("OnStop Error . ", e);
549
            }
550
        }
551

    
552
        public void StopService()
553
        {
554
            StopWcfService();
555
            try
556
            {
557
                Stopprocess();
558
            }
559
            catch (Exception ex)
560
            {
561
                System.Diagnostics.Debug.WriteLine(ex);
562
            }
563

    
564
            logger.Info("ServiceStation Stop");
565
        }
566

    
567
        #region Sleep 방지
568
        //[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
569
        //static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
570
        //[FlagsAttribute]
571
        //public enum EXECUTION_STATE : uint
572
        //{
573
        //    ES_AWAYMODE_REQUIRED = 0x00000040,
574
        //    ES_CONTINUOUS = 0x80000000,
575
        //    ES_DISPLAY_REQUIRED = 0x00000002,
576
        //    ES_SYSTEM_REQUIRED = 0x00000001
577
        //    // Legacy flag, should not be used.
578
        //    // ES_USER_PRESENT = 0x00000004
579
        //}
580
        //public static void PreventScreenAndSleep()
581
        //{
582
        //    SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS |
583
        //                            EXECUTION_STATE.ES_SYSTEM_REQUIRED |
584
        //                            EXECUTION_STATE.ES_AWAYMODE_REQUIRED |
585
        //                            EXECUTION_STATE.ES_DISPLAY_REQUIRED);
586
        //} 
587
        #endregion
588
    }
589
}
클립보드 이미지 추가 (최대 크기: 500 MB)