-
Notifications
You must be signed in to change notification settings - Fork 1
/
ListenAgent.cs
910 lines (796 loc) · 38.3 KB
/
ListenAgent.cs
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using CoApp.Toolkit.Collections;
using CoApp.Toolkit.Extensions;
using CoApp.Toolkit.Pipes;
using CoApp.Toolkit.Tasks;
using CoApp.Toolkit.Utility;
using Newtonsoft.Json.Linq;
using System.Diagnostics;
namespace AutoBuilder
{
public class RequestHandler
{
public virtual Task Put(HttpListenerResponse response, string relativePath, byte[] data)
{
return null;
}
public virtual Task Get(HttpListenerResponse response, string relativePath, UrlEncodedMessage message)
{
return null;
}
public virtual Task Post(HttpListenerResponse response, string relativePath, UrlEncodedMessage message)
{
return null;
}
public virtual Task Head(HttpListenerResponse response, string relativePath, UrlEncodedMessage message)
{
return null;
}
}
public delegate void Logger(string message, EventLogEntryType type);
public class Listener
{
private readonly HttpListener _listener = new HttpListener();
private readonly List<string> _hosts = new List<string>();
private readonly List<int> _ports = new List<int>();
private readonly Dictionary<string, RequestHandler> _paths = new Dictionary<string, RequestHandler>();
private Task<HttpListenerContext> _current = null;
public static Logger Logger;
private static void WriteLog(string message, EventLogEntryType type = EventLogEntryType.Information)
{
if (Logger != null)
Logger(message, type);
}
public Listener()
{ }
Regex ipAddrRx = new Regex(@"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$");
Regex hostnameRx = new Regex(@"(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*");
public void AddHost(string host)
{
if (string.IsNullOrEmpty(host))
return;
host = host.ToLower();
if (_hosts.Contains(host))
return;
if (host == "+" || host == "*" || ipAddrRx.IsMatch(host) || hostnameRx.IsMatch(host))
{
_hosts.Add(host);
if (_current != null)
Restart();
return;
}
}
public void RemoveHost(string host)
{
if (string.IsNullOrEmpty(host))
return;
host = host.ToLower();
if (_hosts.Contains(host))
{
_hosts.Remove(host);
if (_current != null)
Restart();
}
}
public void AddPort(int port)
{
if (port <= 0 || port > 65535)
return;
if (_ports.Contains(port))
return;
_ports.Add(port);
if (_current != null)
Restart();
}
public void RemovePort(int port)
{
if (_ports.Contains(port))
{
_ports.Remove(port);
if (_current != null)
Restart();
}
}
public void AddHandler(string path, RequestHandler handler)
{
if (string.IsNullOrEmpty(path))
path = "/";
path = path.ToLower();
if (!path.StartsWith("/"))
path = "/" + path;
if (!path.EndsWith("/"))
path = path + "/";
if (_paths.ContainsKey(path))
return;
_paths.Add(path, handler);
if (_current != null)
Restart();
}
public void RemoveHandler(string path)
{
if (string.IsNullOrEmpty(path))
path = "/";
path = path.ToLower();
if (!path.StartsWith("/"))
path = "/" + path;
if (!path.EndsWith("/"))
path = path + "/";
if (_paths.ContainsKey(path))
{
_paths.Remove(path);
if (_current != null)
Restart();
}
}
public void Restart()
{
try
{ Stop(); }
catch
{ }
try
{ Start(); }
catch
{ }
}
public void Stop()
{
_listener.Stop();
_current = null;
}
public void Start()
{
if (_current == null)
{
_listener.Prefixes.Clear();
foreach (var host in _hosts)
{
foreach (var port in _ports)
{
foreach (var path in _paths.Keys)
{
WriteLog("Adding `http://{0}:{1}{2}`".format(host, port, path));
_listener.Prefixes.Add("http://{0}:{1}{2}".format(host, port, path));
}
}
}
}
_listener.Start();
_current = Task.Factory.FromAsync<HttpListenerContext>(_listener.BeginGetContext, _listener.EndGetContext, _listener);
_current.ContinueWith(antecedent =>
{
if (antecedent.IsCanceled || antecedent.IsFaulted)
{
_current = null;
return;
}
Start(); // start a new listener.
try
{
var request = antecedent.Result.Request;
var response = antecedent.Result.Response;
var url = request.Url;
var path = url.AbsolutePath.ToLower();
var handlerKey = _paths.Keys.OrderByDescending(each => each.Length).Where(path.StartsWith).FirstOrDefault();
if (handlerKey == null)
{
// no handler
response.StatusCode = 404;
response.Close();
return;
}
var relativePath = path.Substring(handlerKey.Length);
if (string.IsNullOrEmpty(relativePath))
relativePath = "index";
var handler = _paths[handlerKey];
Task handlerTask = null;
var length = request.ContentLength64;
switch (request.HttpMethod)
{
case "PUT":
try
{
var putData = new byte[length];
var read = 0;
var offset = 0;
do
{
read = request.InputStream.Read(putData, offset, (int)length - offset);
offset += read;
} while (read > 0 && offset < length);
handlerTask = handler.Put(response, relativePath, putData);
}
catch (Exception e)
{
HandleException(e);
response.StatusCode = 500;
response.Close();
}
break;
case "HEAD":
try
{
handlerTask = handler.Head(response, relativePath, new UrlEncodedMessage(relativePath + "?" + url.Query));
}
catch (Exception e)
{
HandleException(e);
response.StatusCode = 500;
response.Close();
}
break;
case "GET":
try
{
handlerTask = handler.Get(response, relativePath, new UrlEncodedMessage(relativePath + "?" + url.Query));
}
catch (Exception e)
{
HandleException(e);
response.StatusCode = 500;
response.Close();
}
break;
case "POST":
try
{
var postData = new byte[length];
var read = 0;
var offset = 0;
do
{
read = request.InputStream.Read(postData, offset, (int)length - offset);
offset += read;
} while (read > 0 && offset < length);
handlerTask = handler.Post(response, relativePath, new UrlEncodedMessage(relativePath + "?" + Encoding.UTF8.GetString(postData)));
}
catch (Exception e)
{
HandleException(e);
response.StatusCode = 500;
response.Close();
}
break;
}
if (handlerTask != null)
{
handlerTask.ContinueWith((antecedent2) =>
{
if (antecedent2.IsFaulted && antecedent2.Exception != null)
{
var e = antecedent2.Exception.InnerException;
HandleException(e);
response.StatusCode = 500;
}
response.Close();
}, TaskContinuationOptions.AttachedToParent);
}
else
{
// nothing retured? must be unimplemented.
response.StatusCode = 405;
response.Close();
}
}
catch (Exception e)
{
HandleException(e);
}
}, TaskContinuationOptions.AttachedToParent);
}
public static void HandleException(Exception e)
{
if (e is AggregateException)
e = (e as AggregateException).Flatten().InnerExceptions[0];
WriteLog("{0} -- {1}\r\n{2}".format(e.GetType(), e.Message, e.StackTrace), EventLogEntryType.Error);
}
}
public static class HttpListenerResponseExtensions
{
public static void WriteString(this HttpListenerResponse response, string format, params string[] args)
{
var text = string.Format(format, args);
var buffer = Encoding.UTF8.GetBytes(text);
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Flush();
}
}
public class PostHandler : RequestHandler
{
public static Logger Logger;
private static void WriteLog(string message, EventLogEntryType type = EventLogEntryType.Information)
{
if (Logger != null)
Logger(message, type);
}
public PostHandler()
{ }
public PostHandler(Logger logger)
{
Logger = logger;
}
public override Task Post(HttpListenerResponse response, string relativePath, UrlEncodedMessage message)
{
var payload = (string)message["payload"];
if (payload == null)
{
response.StatusCode = 500;
response.Close();
return "".AsResultTask();
}
var result = Task.Factory.StartNew(() =>
{
try
{
dynamic json = JObject.Parse(payload);
var jobj = JObject.Parse(payload);
WriteLog("MSG Process begin " + json.commits.Count);
string repository = (json.repository.name) ?? String.Empty;
string reference = json["ref"].ToString();
int count = json.commits.Count;
bool validTrigger = false;
for (int i = 0; i < count; i++)
{
string username = (json.commits[i].author.username ?? json.commits[i].author.name ?? new {Value = String.Empty}).Value;
if (!username.Equals((string)(AutoBuild.MasterConfig.VersionControlList["git"].Properties["username"]), StringComparison.CurrentCultureIgnoreCase))
{
validTrigger = true;
}
}
if (validTrigger)
{
AutoBuild.WriteVerbose("POST received: " + repository + " -- " + reference);
if (AutoBuild.Projects.ContainsKey(repository))
{
ProjectData project = AutoBuild.Projects[repository];
if (project.WatchRefs.IsNullOrEmpty() || project.WatchRefs.Contains(reference))
AutoBuild.StandBy(repository);
}
else
{
bool makeNew;
if (!Boolean.TryParse(AutoBuild.MasterConfig.VersionControlList["git"].Properties["NewFromHook"], out makeNew))
return;
if (makeNew)
{
/////Build new ProjectInfo info from commit message.
ProjectData project = new ProjectData();
project.SetName(repository);
project.Enabled = true;
project.KeepCleanRepo = AutoBuild.MasterConfig.DefaultCleanRepo;
// This section constructs the repo url to use...
string init_url = json.repository.url;
string proto = init_url.Substring(0, init_url.IndexOf("://") + 3);
init_url = init_url.Substring(proto.Length);
string host = init_url.Substring(0, init_url.IndexOf("/"));
string repo = init_url.Substring(init_url.IndexOf("/") + 1);
switch (((string)(AutoBuild.MasterConfig.VersionControlList["git"].Properties["url_style"])).ToLower())
{
case "git":
project.RepoURL = "git://" + host + "/" + repo;
break;
case "http":
project.RepoURL = json.url;
break;
case "ssh":
project.RepoURL = "git@" + host + ":" + repo;
break;
default:
project.RepoURL = null;
break;
}
// End repo url section
project.WatchRefs.AddRange(AutoBuild.MasterConfig.DefaultRefs);
if (!(AutoBuild.MasterConfig.DefaultCommands.IsNullOrEmpty()))
{
if (project.WatchRefs.Count > 0)
{
foreach (string watchRef in project.WatchRefs)
{
string branch = watchRef.Substring(11); //length of @"refs/heads/"
project.BuildCheckouts[branch] = new ProjectData.CheckoutInfo();
List<string> strings;
//prebuild
strings = AutoBuild.MasterConfig.DefaultCommands["prebuild"] ??
new List<string>();
foreach (string s in strings)
{
project.BuildCheckouts[branch].PreCmd.Add(s);
}
//build
project.BuildCheckouts[branch].BuildCmd.Add("Checkout"); // magic name
strings = AutoBuild.MasterConfig.DefaultCommands["build"] ?? new List<string>();
foreach (string s in strings)
{
project.BuildCheckouts[branch].BuildCmd.Add(s);
}
//postbuild
strings = AutoBuild.MasterConfig.DefaultCommands["postbuild"] ??
new List<string>();
foreach (string s in strings)
{
project.BuildCheckouts[branch].ArchiveCmd.Add(s);
}
}
}
else
{
List<string> strings;
//prebuild
strings = AutoBuild.MasterConfig.DefaultCommands["prebuild"] ??
new List<string>();
foreach (string s in strings)
{
project.PreBuild.Add(s);
}
//build
strings = AutoBuild.MasterConfig.DefaultCommands["build"] ?? new List<string>();
foreach (string s in strings)
{
project.Build.Add(s);
}
//postbuild
strings = AutoBuild.MasterConfig.DefaultCommands["postbuild"] ??
new List<string>();
foreach (string s in strings)
{
project.PostBuild.Add(s);
}
}
}
//We're obviously adding a git repo for this project, so assign that for the project's version control
project.VersionControl = "git";
//Add the new project with the new ProjectInfo
AutoBuild.Instance.AddProject(repository, project);
//Start the wait period.
AutoBuild.StandBy(repository);
}
}
}
}
catch (Exception e)
{
WriteLog("Error processing payload: {0} -- {1}\r\n{2}".format(e.GetType(), e.Message, e.StackTrace), EventLogEntryType.Error);
Listener.HandleException(e);
response.StatusCode = 500;
response.Close();
}
}, TaskCreationOptions.AttachedToParent);
result.ContinueWith(antecedent =>
{
if (result.IsFaulted)
{
var e = antecedent.Exception.InnerException;
WriteLog("Error handling commit message: {0} -- {1}\r\n{2}".format(e.GetType(), e.Message, e.StackTrace), EventLogEntryType.Error);
Listener.HandleException(e);
response.StatusCode = 500;
response.Close();
}
}, TaskContinuationOptions.OnlyOnFaulted);
return result;
}
public override Task Get(HttpListenerResponse response, string relativePath, UrlEncodedMessage message)
{
if ((message["status"] + message["build"] + message["publish"] + message["log"]
+ message["reload"] + message["reconfig"] + message["cancel"] + message["add"])
.Equals(String.Empty))
{
response.StatusCode = 500;
response.Close();
return "".AsResultTask();
}
var result = Task.Factory.StartNew(() =>
{
try
{
response.AddHeader("Content-Type", "text/plain");
if (message["reconfig"] != String.Empty)
{
//re-load global config request
if (!AutoBuild.Instance.LoadConfig())
{
response.WriteString("Failed to load new global config. ");
}
}
if (message["reload"] != String.Empty)
{
//re-load project config request
string projName = message["reload"];
if (!AutoBuild.Instance.LoadProject(projName, true))
{
response.WriteString("Failed to reload project config: '{0}'. ", projName);
}
}
if (message["add"] != String.Empty)
{
string projName = message["add"];
if (!AutoBuild.Projects.ContainsKey(projName))
{
/////Build new ProjectInfo info from commit message.
ProjectData project = new ProjectData();
project.SetName(projName);
project.Enabled = true;
project.KeepCleanRepo = AutoBuild.MasterConfig.DefaultCleanRepo;
// This section constructs the repo url to use...
project.RepoURL = @"[email protected]:coapp-packages/" + projName;
project.WatchRefs.AddRange(AutoBuild.MasterConfig.DefaultRefs);
if (!(AutoBuild.MasterConfig.DefaultCommands.IsNullOrEmpty()))
{
if (project.WatchRefs.Count > 0)
{
foreach (string watchRef in project.WatchRefs)
{
string branch = watchRef.Substring(11); //length of @"refs/heads/"
project.BuildCheckouts[branch] = new ProjectData.CheckoutInfo();
List<string> strings;
//prebuild
strings = AutoBuild.MasterConfig.DefaultCommands["prebuild"] ??
new List<string>();
foreach (string s in strings)
{
project.BuildCheckouts[branch].PreCmd.Add(s);
}
//build
project.BuildCheckouts[branch].BuildCmd.Add("Checkout"); // magic name
strings = AutoBuild.MasterConfig.DefaultCommands["build"] ?? new List<string>();
foreach (string s in strings)
{
project.BuildCheckouts[branch].BuildCmd.Add(s);
}
//postbuild
strings = AutoBuild.MasterConfig.DefaultCommands["postbuild"] ??
new List<string>();
foreach (string s in strings)
{
project.BuildCheckouts[branch].ArchiveCmd.Add(s);
}
}
}
else
{
List<string> strings;
//prebuild
strings = AutoBuild.MasterConfig.DefaultCommands["prebuild"] ??
new List<string>();
foreach (string s in strings)
{
project.PreBuild.Add(s);
}
//build
strings = AutoBuild.MasterConfig.DefaultCommands["build"] ?? new List<string>();
foreach (string s in strings)
{
project.Build.Add(s);
}
//postbuild
strings = AutoBuild.MasterConfig.DefaultCommands["postbuild"] ??
new List<string>();
foreach (string s in strings)
{
project.PostBuild.Add(s);
}
}
}
//We're obviously adding a git repo for this project, so assign that for the project's version control
project.VersionControl = "git";
//Add the new project with the new ProjectInfo
AutoBuild.Instance.AddProject(projName, project);
response.WriteString("Project added: {0}. ", projName);
}
else
{
response.WriteString("Project already exists: {0}. ", projName);
}
}
if (message["status"] != String.Empty)
{
//status request
string projName = message["status"];
var proj = AutoBuild.Projects[projName];
if (proj != null)
{
string currentStatus = AutoBuild.IsRunning(projName)
? "Running"
: AutoBuild.IsWaiting(projName)
? "Waiting in queue"
: proj.GetHistory().Builds.Count > 0
? "{0} at {1}".format(
proj.GetHistory().Builds[
proj.GetHistory().Builds.Count-1].Result,
proj.GetHistory().Builds[
proj.GetHistory().Builds.Count-1].TimeStamp
.ToString("yyyy-MM-dd HH:mm:ss"))
: "Project status unavailable. Please build the project.";
response.WriteString("Status of project '{0}': {1}", projName, currentStatus);
}
else
{
response.WriteString("Unable to return status for project '{0}': No such project. ", projName);
}
}
if (message["build"] != String.Empty)
{
//build request
string projName = message["build"];
if (AutoBuild.Projects[projName] != null)
{
if (AutoBuild.IsWaiting(projName))
response.WriteString("Project already scheduled to run: '{0}'. ", projName);
else
{
AutoBuild.StandBy(projName);
response.WriteString("Project added to build queue: '{0}'. ", projName);
}
}
else
{
response.WriteString("Unable to return status for project '{0}': No such project. ", projName);
}
}
if (message["cancel"] != String.Empty)
{
//logfile request
string projName = message["cancel"];
if (AutoBuild.Projects.ContainsKey(projName))
{
string msg = AutoBuild.CancelQueue(projName)
? "Pending builds canceled for project: '{0}'. ".format(projName)
: "Error cancelling pending builds: '{0}'. ".format(projName);
response.WriteString(msg);
}
else
{
response.WriteString("Unable to cancel, project does not exist: '{0}'. ", projName);
}
}
if (message["publish"] != String.Empty)
{
//publish finished packages
ProcessUtility _cmdexe = new ProcessUtility("cmd.exe");
int ret = AutoBuild.MasterConfig.Commands["MasterPublish"].Run(_cmdexe,
Environment.CurrentDirectory,
new XDictionary<string, string>());
if (ret == 0)
response.WriteString("Publish uploads completed successsfully. ");
else
response.WriteString("Error occurred during publish upload. ");
}
if (message["log"] != String.Empty)
{
//logfile request
string projName = message["log"];
var proj = AutoBuild.Projects[projName];
if (proj != null)
{
string msg;
if (proj.GetHistory().Builds.Count <= 0)
msg = "Project status unavailable. Please build the project.";
else
{
try
{
string logpath = Path.Combine(AutoBuild.MasterConfig.ProjectRoot, projName, "Archive",
proj.GetHistory().Builds[
proj.GetHistory().Builds.Count - 1].TimeStamp.ToString
(AutoBuild.DateTimeDirFormat));
string logfile = File.Exists(Path.Combine(logpath, "build.log")) ? Path.Combine(logpath, "build.log") : Path.Combine(logpath, "run.log");
StreamReader reader = new StreamReader(new FileStream(logfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
msg = reader.ReadToEnd();
}
catch (Exception ee)
{
msg = "Error: Unable to open log file for project '{0}'. ".format(projName);
}
}
response.WriteString(msg);
}
else
{
response.WriteString("Unable to return log for project '{0}': No such project. ", projName);
}
}
}
catch (Exception e)
{
WriteLog("Error processing request: {0} -- {1}\r\n{2}".format(e.GetType(), e.Message, e.StackTrace), EventLogEntryType.Error);
Listener.HandleException(e);
response.StatusCode = 500;
response.Close();
}
}, TaskCreationOptions.AttachedToParent);
result.ContinueWith(antecedent =>
{
if (result.IsFaulted)
{
var e = antecedent.Exception.InnerException;
WriteLog("Error handling commit message: {0} -- {1}\r\n{2}".format(e.GetType(), e.Message, e.StackTrace), EventLogEntryType.Error);
Listener.HandleException(e);
response.StatusCode = 500;
response.Close();
}
}, TaskContinuationOptions.OnlyOnFaulted);
return result;
}
}
public class ListenAgent : Daemon
{
private bool initDone = false;
private Listener listener;
public Logger Logger;
public string[] hosts { get; private set; }
public int[] ports { get; private set; }
public string postfix { get; private set; }
public ListenAgent(string handle = null, string[] Hosts = null, int[] Ports = null, Logger logger = null)
{
initDone = false;
postfix = handle ?? "trigger";
hosts = Hosts ?? new string[] { "*" };
ports = Ports ?? new int[] { 80 };
Logger = logger;
}
/// <summary>
/// Initializes the internal listener.
/// </summary>
/// <returns>True if successful. False on error.</returns>
public bool Init()
{
if (initDone)
try
{ listener.Stop(); }
catch (Exception e)
{ }
try
{
Listener.Logger = Logger;
listener = new Listener();
foreach (var host in hosts)
listener.AddHost(host);
foreach (var port in ports)
listener.AddPort(port);
listener.AddHandler(postfix, new PostHandler(Logger));
return true;
}
catch (Exception e)
{
Listener.HandleException(e);
return false;
}
}
public override bool Start()
{
if (!initDone)
initDone = Init();
try
{
listener.Start();
return true;
}
catch (Exception e)
{
Listener.HandleException(e);
return false;
}
}
public override bool Stop()
{
try
{
listener.Stop();
return true;
}
catch (Exception e)
{
Listener.HandleException(e);
return false;
}
}
} // End ListenAgent
}