markus / ConvertService / ServiceBase / Markus.Service.Station / ServiceStation.cs @ 1d79913e
이력 | 보기 | 이력해설 | 다운로드 (19.7 KB)
1 |
using log4net; |
---|---|
2 |
using Markus.EntityModel; |
3 |
using Markus.Service.Extensions; |
4 |
using Markus.Service.Helper; |
5 |
using Markus.Service.IWcfService; |
6 |
using Markus.Service.WcfService; |
7 |
using Salaros.Configuration; |
8 |
using System; |
9 |
using System.Collections.Generic; |
10 |
using System.ComponentModel; |
11 |
using System.Data; |
12 |
using System.Diagnostics; |
13 |
using System.Globalization; |
14 |
using System.IO; |
15 |
using System.Linq; |
16 |
using System.Runtime.InteropServices; |
17 |
using System.ServiceModel; |
18 |
using System.ServiceModel.Channels; |
19 |
using System.ServiceModel.Dispatcher; |
20 |
using System.ServiceProcess; |
21 |
using System.Text; |
22 |
using System.Threading; |
23 |
using System.Threading.Tasks; |
24 |
using System.Timers; |
25 |
using static Markus.Service.Extensions.Encrypt; |
26 |
|
27 |
namespace Markus.Service |
28 |
{ |
29 |
public partial class ServiceStation : ServiceBase |
30 |
{ |
31 |
protected ILog logger = LogManager.GetLogger(typeof(ServiceStation)); |
32 |
protected ServiceHost gWcfServiceHost; |
33 |
private SERVICE_PROPERTIES ServiceProperty; |
34 |
|
35 |
private string ServiceID; |
36 |
private List<SubStationServiceItem> StationServiceList; |
37 |
private List<string> StationServiceIDList; |
38 |
private Service.WcfClient.StationServiceTask.StationServiceClient StationClient; |
39 |
private bool IsStation; |
40 |
|
41 |
private Uri gServiceHostAddress; |
42 |
|
43 |
private string MarkusDBConnectionString; |
44 |
private string DownloadTempFolder; |
45 |
private string FontsFolder; |
46 |
private int MultiThreadMaxPages; |
47 |
private int MinFontSize; |
48 |
private int UseResolution; |
49 |
private bool CreateProcessWindow; |
50 |
private long ReleaseWorkMemory; |
51 |
|
52 |
private int SaveStatusInterval; |
53 |
|
54 |
private bool IsReleaseItems; |
55 |
private readonly System.Timers.Timer timer= null; |
56 |
|
57 |
private readonly object locker = new object(); |
58 |
|
59 |
private List<string> RunProjectList = new List<string>(); |
60 |
|
61 |
/// <summary> |
62 |
/// 프로세스 카운터 자주 람다식을 사용해서 list<int>로 함. |
63 |
/// </summary> |
64 |
private List<Int64> ProcessorAffinityList; |
65 |
|
66 |
private string configFileName; |
67 |
|
68 |
public ServiceStation() |
69 |
{ |
70 |
InitializeComponent(); |
71 |
|
72 |
timer = new System.Timers.Timer(new TimeSpan(0, 0, 0,1).TotalMilliseconds); |
73 |
timer.Elapsed += timerWorkMethod; |
74 |
} |
75 |
|
76 |
/// <summary> |
77 |
/// Config 파일 |
78 |
/// </summary> |
79 |
public void GetApplicationConfig() |
80 |
{ |
81 |
try |
82 |
{ |
83 |
ConfigParser config = null; |
84 |
|
85 |
try |
86 |
{ |
87 |
configFileName = $"{typeof(ServiceStation).Name}.ini"; |
88 |
config = ConfigHelper.AppConfig(this.configFileName); |
89 |
} |
90 |
catch (Exception ex) |
91 |
{ |
92 |
throw new Exception("Config Read Error.", ex); |
93 |
} |
94 |
|
95 |
if (config != null) |
96 |
{ |
97 |
// CONVERT DATABASE 연결 문자열 |
98 |
MarkusDBConnectionString = AESEncrypter.Decrypt(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.MARKUS_CONNECTION_STRING)); |
99 |
|
100 |
IsStation = System.Convert.ToBoolean(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.IS_STATAION, "false")); |
101 |
|
102 |
ServiceID = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.SERVICE_ID, Guid.Empty.ToString()); |
103 |
|
104 |
if (IsStation) |
105 |
{ |
106 |
var servicetList = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.SERVICE_LIST, ""); |
107 |
|
108 |
if (!servicetList.IsNullOrEmpty()) |
109 |
{ |
110 |
StationServiceIDList = servicetList.Split(',').ToList(); |
111 |
} |
112 |
} |
113 |
else |
114 |
{ |
115 |
var address = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.STATAION_ADDRESS,""); |
116 |
|
117 |
if (!address.IsNullOrEmpty()) |
118 |
{ |
119 |
BasicHttpBinding myBinding = new BasicHttpBinding(); |
120 |
EndpointAddress myEndpoint = new EndpointAddress(UriHelper.UriCreate(address)); |
121 |
StationClient = new WcfClient.StationServiceTask.StationServiceClient(myBinding, myEndpoint); |
122 |
} |
123 |
} |
124 |
|
125 |
CreateProcessWindow = System.Convert.ToBoolean(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.CREATE_WINDOW, "false")); |
126 |
|
127 |
// PDF 임시 다운로드 폴더 |
128 |
DownloadTempFolder = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.DOWNLOAD_TEMP_FOLDER,"C:\\temp"); |
129 |
FontsFolder = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.FONTS_FOLDER, "C:\\MarkusFonts"); |
130 |
// pThraed를 이용한 컨버팅 설정. |
131 |
//최대 페이지가 MultiThreadMaxPages설정까지 pThread를 적용하여 컨버팅함. |
132 |
MultiThreadMaxPages = System.Convert.ToInt16(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.MULTI_TRHEAD_MAX_PAGE, "500")); |
133 |
|
134 |
// 서비스 상태 Log 저장간격 |
135 |
SaveStatusInterval = System.Convert.ToInt16(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.SAVE_STATUS_INTERVAL, "5")); |
136 |
|
137 |
//PDF에 폰트가 최소 폰트 사이즈보다 작은 사이증의 폰트가 있으면 해상도를 높여서 컨버팅함. |
138 |
MinFontSize = System.Convert.ToInt16(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.MIN_FONT_SIZE, "10")); |
139 |
|
140 |
// 사용자 설정의 해상도 |
141 |
// MinFontSize를 -1로 하고 UseResolution를 설정하면 해당 해상도로 컨버팅됨 |
142 |
UseResolution = System.Convert.ToInt16(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.USE_RESOLUTION, "0")); |
143 |
|
144 |
// 각 프로세스의 최대 메모리 사용량 |
145 |
var workingMemory = System.Convert.ToDouble(config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.RELEASE_WORK_MEMORY, "1.5")); |
146 |
|
147 |
ReleaseWorkMemory = MathBytes.Bytes(workingMemory, DataSizeType.GB); |
148 |
|
149 |
// 서비스 사용 프로젝트 |
150 |
var projectList = config.GetValue(CONFIG_DEFINE.SERVICE, CONFIG_DEFINE.FITER_PROCECT,""); |
151 |
|
152 |
if(!projectList.IsNullOrEmpty()) |
153 |
{ |
154 |
RunProjectList = projectList.Split(',').ToList(); |
155 |
} |
156 |
|
157 |
// 서비스 ENDPOINT |
158 |
// http://localhost/ |
159 |
var endpointName = config.GetValue(CONFIG_DEFINE.WCF_ENDPOINT, CONFIG_DEFINE.STATION_SERVICE_NAME); |
160 |
var port = config.GetValue(CONFIG_DEFINE.WCF_ENDPOINT, CONFIG_DEFINE.STATION_PORT); |
161 |
|
162 |
if (!string.IsNullOrWhiteSpace(endpointName) && port.IsNumber()) |
163 |
{ |
164 |
gServiceHostAddress = UriHelper.UriCreate($"http://localhost:{port}/{endpointName}"); |
165 |
} |
166 |
|
167 |
// 각 ConvertService의 원격 관리를 위한 서비스 설정 로드 |
168 |
using (Markus.Service.DataBase.ConvertDatabase db = new Markus.Service.DataBase.ConvertDatabase(MarkusDBConnectionString)) |
169 |
{ |
170 |
ServiceProperty = db.GetServiceProperties(ServiceID); |
171 |
} |
172 |
} |
173 |
} |
174 |
catch (Exception ex) |
175 |
{ |
176 |
throw new Exception("ApplicationConfig ", ex); |
177 |
} |
178 |
} |
179 |
|
180 |
protected override void OnStart(string[] args) |
181 |
{ |
182 |
try |
183 |
{ |
184 |
StartService(); |
185 |
} |
186 |
catch (Exception ex) |
187 |
{ |
188 |
logger.Error("ServiceStation Start Error - ", ex); |
189 |
} |
190 |
} |
191 |
|
192 |
/// <summary> |
193 |
/// alivequeue와 process를 비교하여 정리하고 |
194 |
/// 대기중인 아이템을 분배한다. |
195 |
/// </summary> |
196 |
private void ReleaseItems() |
197 |
{ |
198 |
try |
199 |
{ |
200 |
IsReleaseItems = true; |
201 |
|
202 |
System.Diagnostics.Debug.WriteLine("CleanUpAliveQueueItems start"); |
203 |
CleanUpAliveQueueItems(); |
204 |
System.Diagnostics.Debug.WriteLine("CleanUpAliveQueueItems end"); |
205 |
|
206 |
if (IsStation) |
207 |
{ |
208 |
//if (IsDataBaseWaitingList(1)) |
209 |
//{ |
210 |
System.Diagnostics.Debug.WriteLine("ReleaseItems start"); |
211 |
var task = ReflashSubServiceAsync(); |
212 |
|
213 |
if(task.Wait(40000)) |
214 |
{ |
215 |
if (task.Result) |
216 |
{ |
217 |
if (StationServiceList.All(x => x.IsOnline)) |
218 |
{ |
219 |
CleanUpDataBaseItems(); |
220 |
setDataBaseWaitingList(); |
221 |
} |
222 |
else |
223 |
{ |
224 |
logger.Error("Service Any Offline"); |
225 |
} |
226 |
} |
227 |
else |
228 |
{ |
229 |
logger.Error("ReleaseItems - ReflashSubServiceAsync result false"); |
230 |
} |
231 |
|
232 |
} |
233 |
|
234 |
|
235 |
System.Diagnostics.Debug.WriteLine("ReleaseItems end"); |
236 |
//} |
237 |
} |
238 |
} |
239 |
catch (Exception ex) |
240 |
{ |
241 |
logger.Error("get Wating Item error", ex); |
242 |
} |
243 |
|
244 |
IsReleaseItems = false; |
245 |
} |
246 |
|
247 |
/// <summary> |
248 |
/// System.Diagnostics.Process의 ProcessorAffinity Core 선호도를 위한 초기화 |
249 |
/// 설정된 MultiProcessCount에 대해서 프로세스의 코어의 선호도를 지정 한다. |
250 |
/// 코어의 선택은 비트로 이루어 진다. |
251 |
/// 8코어에서 1번 코어 00000001 |
252 |
/// 8코어에서 1번 3번 코어 00000101 |
253 |
/// 8코어에서 1번 3번 코어 00000101 |
254 |
/// 8코어에서 1,2,3 선택 00000111 |
255 |
/// https://dotnetgalactics.wordpress.com/2009/10/20/how-to-set-the-processor-affinity-programatically/ |
256 |
/// </summary> |
257 |
private void ProcessorAffinityInit() |
258 |
{ |
259 |
ProcessorAffinityList = new List<long>(); |
260 |
|
261 |
int processCount = Environment.ProcessorCount; |
262 |
int AffinityScope = processCount; |
263 |
|
264 |
if (processCount > ServiceProperty.PROCESS_COUNT) |
265 |
{ |
266 |
AffinityScope = processCount / ServiceProperty.PROCESS_COUNT; |
267 |
} |
268 |
|
269 |
long affinityMask = 0; |
270 |
|
271 |
while (ProcessorAffinityList.Count() < ServiceProperty.PROCESS_COUNT) |
272 |
{ |
273 |
if(affinityMask <= 1) |
274 |
{ |
275 |
affinityMask = 1 << (processCount - 1); |
276 |
} |
277 |
else |
278 |
{ |
279 |
affinityMask = affinityMask >>1; |
280 |
} |
281 |
|
282 |
ProcessorAffinityList.Add(affinityMask); |
283 |
} |
284 |
|
285 |
// for (int i = 0; i < AffinityScope; i += AffinityScope) |
286 |
// { |
287 |
// var bits = new int[processCount]; |
288 |
|
289 |
// for (int j = i; j < i + AffinityScope; j++) |
290 |
// { |
291 |
// bits[j] = 1; |
292 |
// } |
293 |
|
294 |
// var affinity = System.Convert.ToInt64(string.Join("", bits), 2); |
295 |
|
296 |
//#if DEBUG |
297 |
// List<int> test = bits.ToList(); |
298 |
// test.Reverse(); |
299 |
// System.Diagnostics.Debug.WriteLine($"index{string.Format("0#",i)} - {string.Join("", test)}"); |
300 |
//#endif |
301 |
// ProcessorAffinityList.Add(affinity); |
302 |
// } |
303 |
} |
304 |
|
305 |
public void StartService() |
306 |
{ |
307 |
/// 서비스 설정 로드 |
308 |
try |
309 |
{ |
310 |
this.GetApplicationConfig(); |
311 |
logger.Info("Read Config"); |
312 |
|
313 |
if (ServiceProperty != null) |
314 |
{ |
315 |
ProcessorAffinityInit(); |
316 |
} |
317 |
else |
318 |
{ |
319 |
throw new Exception("StartService Error. ServiceProperty is Null"); |
320 |
} |
321 |
|
322 |
} |
323 |
catch (Exception e) |
324 |
{ |
325 |
throw new Exception("StartService Error. ", e); |
326 |
} |
327 |
|
328 |
/// pThread.dll을 리소스에서 Service 실행 디렉토리로 복사. |
329 |
//try |
330 |
//{ |
331 |
// // MarkusPDF.dll에서 pThread lib 사용을 위해 Insatll |
332 |
// var libPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "\\convert\\libpthread.dll"); |
333 |
// if (!File.Exists(libPath)) |
334 |
// { |
335 |
// Markus.Library.Installer.Install(); |
336 |
// logger.Info("Markus.Library.Installer Install"); |
337 |
// } |
338 |
// else |
339 |
// { |
340 |
// logger.Info("Markus.Library.Installer Exists."); |
341 |
// } |
342 |
|
343 |
//} |
344 |
//catch (Exception e) |
345 |
//{ |
346 |
// throw new Exception("Stop Installer Error. ", e); |
347 |
//} |
348 |
|
349 |
/// 컨버터 프로세스가 실행중인 경우 모두 중지 시킨다. |
350 |
try |
351 |
{ |
352 |
// 기존에 실행 중이던 프로세스 종료 |
353 |
Stopprocess(); |
354 |
logger.Info("Stopprocess"); |
355 |
} |
356 |
catch (Exception e) |
357 |
{ |
358 |
throw new Exception("Stop Process Error. ", e); |
359 |
} |
360 |
|
361 |
/// wcf 서비스 실행 |
362 |
try |
363 |
{ |
364 |
// WCF 실행 |
365 |
StartWcfService(); |
366 |
|
367 |
if (gWcfServiceHost.BaseAddresses?.Count() > 0) |
368 |
{ |
369 |
gServiceHostAddress = gWcfServiceHost.BaseAddresses.First(); |
370 |
} |
371 |
|
372 |
// 각 sub서비스에 컨버터 아이템을 보내기 위한 서비스 초기화 |
373 |
if (IsStation) |
374 |
{ |
375 |
SetServiceList(this.StationServiceIDList); |
376 |
} |
377 |
|
378 |
logger.Info($"StartWcfService {gServiceHostAddress}"); |
379 |
} |
380 |
catch (Exception e) |
381 |
{ |
382 |
throw new Exception("start Wcf Service Error. ", e); |
383 |
} |
384 |
|
385 |
//try |
386 |
//{ |
387 |
// // Status가 4이하인 Convert Item을 다시 Convert 함. |
388 |
// setDataBaseWaitingList(); |
389 |
// logger.Info("setDataBaseWaitingList"); |
390 |
//} |
391 |
//catch (Exception e) |
392 |
//{ |
393 |
// throw new Exception("Database Waiting List Error . ", e); |
394 |
//} |
395 |
|
396 |
logger.Info("Start ServiceStation"); |
397 |
timer.Start(); |
398 |
} |
399 |
|
400 |
private void timerWorkMethod(object sender, ElapsedEventArgs e) |
401 |
{ |
402 |
if (timer.Enabled) |
403 |
{ |
404 |
var _timer = (System.Timers.Timer)sender; |
405 |
_timer.Stop(); |
406 |
|
407 |
if (!IsStop) |
408 |
{ |
409 |
StartConvert(); |
410 |
|
411 |
_timer.Start(); |
412 |
} |
413 |
else |
414 |
{ |
415 |
StopService(); |
416 |
} |
417 |
} |
418 |
else |
419 |
{ |
420 |
logger.Error("timer disable"); |
421 |
} |
422 |
} |
423 |
|
424 |
private bool IsStop = false; |
425 |
|
426 |
DateTime logTime; |
427 |
DateTime ReleaseTime; |
428 |
|
429 |
|
430 |
private bool StartConvert() |
431 |
{ |
432 |
//stateTimer.Change(new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0, 0, -1)); |
433 |
try |
434 |
{ |
435 |
|
436 |
if ((DateTime.Now - ReleaseTime) >= new TimeSpan(0, 0,1)) |
437 |
{ |
438 |
if (!IsReleaseItems) |
439 |
{ |
440 |
if (System.Environment.UserInteractive) |
441 |
{ |
442 |
Console.WriteLine("Release Items"); |
443 |
} |
444 |
logger.Info("Release Items"); |
445 |
ReleaseItems(); |
446 |
} |
447 |
else |
448 |
{ |
449 |
if (System.Environment.UserInteractive) |
450 |
{ |
451 |
Console.WriteLine("pass Release Items"); |
452 |
} |
453 |
} |
454 |
|
455 |
ReleaseTime = DateTime.Now; |
456 |
} |
457 |
|
458 |
if ((DateTime.Now - logTime) >= new TimeSpan(0, 5,0)) |
459 |
{ |
460 |
logTime = DateTime.Now; |
461 |
logger.Info("StationService Alive Check"); |
462 |
} |
463 |
} |
464 |
catch (Exception ex) |
465 |
{ |
466 |
logger.Error("Timer Error ", ex); |
467 |
} |
468 |
|
469 |
return true; |
470 |
} |
471 |
|
472 |
public void SetServiceList(List<string> serviceList) |
473 |
{ |
474 |
StationServiceList = new List<SubStationServiceItem>(); |
475 |
|
476 |
using (DataBase.ConvertDatabase database = new DataBase.ConvertDatabase(MarkusDBConnectionString)) |
477 |
{ |
478 |
foreach (var item in serviceList) |
479 |
{ |
480 |
try |
481 |
{ |
482 |
var prop = database.GetServiceProperties(item); |
483 |
|
484 |
if (prop != null) |
485 |
{ |
486 |
BasicHttpBinding httpbinding = new BasicHttpBinding(); |
487 |
httpbinding.CloseTimeout = new TimeSpan(0, 10, 0); |
488 |
httpbinding.ReceiveTimeout = new TimeSpan(0, 10, 0); |
489 |
httpbinding.SendTimeout = new TimeSpan(0, 10, 0); |
490 |
httpbinding.OpenTimeout = new TimeSpan(0, 10, 0); |
491 |
|
492 |
EndpointAddress myEndpoint = new EndpointAddress(UriHelper.UriCreate(prop.SERVICE_ADDRESS)); |
493 |
var StationServiceClient = new WcfClient.StationServiceTask.StationServiceClient(httpbinding, myEndpoint); |
494 |
|
495 |
|
496 |
//var items = StationServiceClient.AliveConvertList(); |
497 |
|
498 |
StationServiceList.Add(new SubStationServiceItem |
499 |
{ |
500 |
Properties = prop, |
501 |
Service = StationServiceClient |
502 |
}); |
503 |
} |
504 |
|
505 |
} |
506 |
catch (Exception ex) |
507 |
{ |
508 |
logger.Error($"Service Properties Error ID : { item }",ex); |
509 |
} |
510 |
} |
511 |
} |
512 |
} |
513 |
|
514 |
protected override void OnStop() |
515 |
{ |
516 |
try |
517 |
{ |
518 |
IsStop = true; |
519 |
} |
520 |
catch (Exception e) |
521 |
{ |
522 |
logger.Error("OnStop Error . ", e); |
523 |
} |
524 |
} |
525 |
|
526 |
public void StopService() |
527 |
{ |
528 |
StopWcfService(); |
529 |
Stopprocess(); |
530 |
|
531 |
logger.Info("ServiceStation Stop"); |
532 |
} |
533 |
|
534 |
#region Sleep 방지 |
535 |
//[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] |
536 |
//static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags); |
537 |
//[FlagsAttribute] |
538 |
//public enum EXECUTION_STATE : uint |
539 |
//{ |
540 |
// ES_AWAYMODE_REQUIRED = 0x00000040, |
541 |
// ES_CONTINUOUS = 0x80000000, |
542 |
// ES_DISPLAY_REQUIRED = 0x00000002, |
543 |
// ES_SYSTEM_REQUIRED = 0x00000001 |
544 |
// // Legacy flag, should not be used. |
545 |
// // ES_USER_PRESENT = 0x00000004 |
546 |
//} |
547 |
//public static void PreventScreenAndSleep() |
548 |
//{ |
549 |
// SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | |
550 |
// EXECUTION_STATE.ES_SYSTEM_REQUIRED | |
551 |
// EXECUTION_STATE.ES_AWAYMODE_REQUIRED | |
552 |
// EXECUTION_STATE.ES_DISPLAY_REQUIRED); |
553 |
//} |
554 |
#endregion |
555 |
} |
556 |
} |