This repository has been archived by the owner on Jul 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
ZabbixAPI.cs
671 lines (616 loc) · 20.6 KB
/
ZabbixAPI.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web.Script.Serialization;
using System.IO;
using System.Net;
// Borrowed heavily from the Open DotNet Zabbix library https://github.com/p1nger/ODZL
namespace Zabbix
{
public delegate void AlertEvent(string msg);
public delegate void ThreadEvent(UpdateInfoMessage message);
public class ZabbixAPI
{
#region Private section
private string authHash = "";
private int id = 0;
private string _url;
private string _username;
private string _password;
private string hostgroupID;
private string minSeverity = "0";
private JavaScriptSerializer serializer = new JavaScriptSerializer();
private int sleep = 5000;
private int hideAck = 0;
#endregion
#region Public section
public AlertEvent onAlert { get; set; }
public ThreadEvent onUpdate { get; set; }
public Thread mainThread;
public Hosts hosts;
public HostGroups hostgroups;
public Triggers triggers;
public Events events;
#endregion
public ZabbixAPI(string url, string user, string pass)
{
serializer.MaxJsonLength = 16777216;
_url = url;
_username = user;
_password = pass;
triggers = new Triggers(this);
hosts = new Hosts(this);
hostgroups = new HostGroups(this);
mainThread = new Thread(getInfo);
}
public void connect()
{
try
{
mainThread.Start();
}
catch (Exception ex)
{
Alert("Exception starting mainThread: " + ex.Message);
}
}
public void stop()
{
try
{
Alert("stop()");
mainThread.Abort();
if (mainThread.IsAlive)
{
Alert("Waiting for mainThread to stop");
mainThread.Join(5000);
}
Alert("mainThread stopped");
onUpdate(new UpdateInfoMessage(this) { message = "Stopped", status = "OK" });
}
catch (Exception ex)
{
Alert("Exception stopping main thread: " + ex.Message);
}
}
public bool login()
{
bool res = false;
onUpdate(new UpdateInfoMessage(this) { message = "Trying to authenticate", status = "LOGIN" });
try
{
var userinfo = new { user = _username, password = _password };
string result = CallAPI("user.login", userinfo);
authHash = (serializer.Deserialize<simpleresult>(result)).result;
if (authHash == null)
{
res = false;
Update(new UpdateInfoMessage(this) { message = "Login failed", status = "LOGIN" });
Alert("Login failed for user: " + _username);
}
else
{
res = true;
Update(new UpdateInfoMessage(this) { message = "Login was successful", status = "OK" });
}
}
catch (Exception ex)
{
Update(new UpdateInfoMessage(this) { message = "Authorization Error:" + ex.Message, status = "LOGIN" });
res = false;
}
return res;
}
public void getInfo()
{
int err = 0;
int lasterr = err;
bool authenticated = login();
int i = 1;
while (!authenticated)
{
Update(new UpdateInfoMessage(this) { message = "Login attempt " + i.ToString(), status = "LOGIN" });
i++;
Thread.Sleep(2000);
authenticated = login();
}
// getHostgroups();
getHosts();
getTriggers();
i = 1;
while (true)
{
try
{
if (err > lasterr)
{
lasterr = err;
login();
}
refreshTriggers();
this.Update(new UpdateInfoMessage(this) { message = i.ToString(), status = "REFRESH" });
}
catch (Exception ex)
{
err++;
this.Update(new UpdateInfoMessage(this) { message = ex.Message, status = "REFRESH_ERROR" });
}
i++;
Thread.Sleep(sleep);
}
}
public string ApiVersion()
{
string result = CallAPI("apiinfo.version", null);
try
{
return (serializer.Deserialize<simpleresult>(result)).result;
}
catch(Exception ex)
{
Alert("ApiVersion() exception: " + ex.Message);
return null;
}
}
public void Update(UpdateInfoMessage msg)
{
if (onUpdate != null)
{
onUpdate(msg);
}
}
public void Alert(string message)
{
if (onAlert != null)
{
onAlert(message);
}
}
public void refreshTriggers()
{
getTriggers();
}
private void getTriggers()
{
long elapsedTicks;
var parms = new object { };
if (hideAck == 0)
{
parms = new
{
output = "extend",
//select_hosts = "extend",
selectHosts = "extend",
monitored = "1",
only_true = "1",
sortfield = "lastchange",
expandDescription = "1",
maintenance = "0",
min_severity = minSeverity,
filter = new { value = "1" }
};
}
else
{
parms = new
{
output = "extend",
//select_hosts = "extend",
selectHosts = "extend",
monitored = "1",
only_true = "1",
sortfield = "lastchange",
expandDescription = "1",
maintenance = "0",
min_severity = minSeverity,
filter = new { value = "1" },
withLastEventUnacknowledged = "1"
};
}
DateTime start = DateTime.Now;
triggers.getWithParam(parms);
elapsedTicks = DateTime.Now.Ticks - start.Ticks;
Update(new UpdateInfoMessage(this) { message = "getTriggers(" + hostgroupID + ") = " + triggers.Count().ToString(), status = "DEBUG" });
Update(new UpdateInfoMessage(this) { message = elapsedTicks.ToString(), status = "TRIGGERS" });
}
private void getHosts()
{
DateTime start = DateTime.Now;
hosts.get();
long elapsedTicks = DateTime.Now.Ticks - start.Ticks;
Update(new UpdateInfoMessage(this) { message = elapsedTicks.ToString(), status = "HOSTS" });
}
private void getHostgroups()
{
DateTime start = DateTime.Now;
hostgroups.get();
long elapsedTicks = DateTime.Now.Ticks - start.Ticks;
Update(new UpdateInfoMessage(this) { message = elapsedTicks.ToString(), status = "HOSTGROUPS" });
}
private string GetWebRequest(string body)
{
string responseFromServer = string.Empty;
try
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
WebRequest wb = WebRequest.Create(_url);
wb.ContentType = @"application/json-rpc";
wb.Credentials = CredentialCache.DefaultCredentials;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = body;
byte[] data = encoding.GetBytes(postData);
wb.Method = "POST";
wb.ContentLength = data.Length;
Stream newStream = wb.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)wb.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
}
catch (Exception ex)
{
Update(new UpdateInfoMessage(this) { message = ex.Message, status = "DEBUG" });
}
return responseFromServer;
}
private Stream GetWebFile(string url)
{
WebRequest wb = WebRequest.Create(url);
wb.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)wb.GetResponse();
Stream dataStream = response.GetResponseStream();
return dataStream;
}
public string obj2json(object obj)
{
return serializer.Serialize(obj);
}
public string CallAPI(string method, object param)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
object Query = null;
if ( method == "apiinfo.version" || method == "user.login" ){
Query = new
{
jsonrpc = "2.0",
id = id.ToString(),
method = method,
Params = param
};
}else{
Query = new
{
jsonrpc = "2.0",
auth = authHash,
id = id.ToString(),
method = method,
Params = param
};
}
String qr = obj2json(Query);
qr = qr.Replace("Params", "params");
id++;
Alert("request: \n" + qr);
string result = GetWebRequest(qr);
Alert("response: \n" + result);
return result;
}
public void setHostgroupID(string id)
{
hostgroupID = id;
}
public void setMinSeverity(string sev)
{
minSeverity = sev;
}
public void setInterval(int seconds)
{
sleep = seconds * 1000;
}
public void setHideAck(int hide)
{
hideAck = hide;
}
}
public class UpdateInfoMessage
{
public string status { get; set; }
public string message { get; set; }
public object sender { get; set; }
public UpdateInfoMessage(object Sender, string Status = "", string Message = "")
{
status = Status;
message = Message;
sender = Sender;
}
}
public class Result<T> : IEnumerable<T>
{
public T[] result;
public ZabbixAPI server;
protected string method;
protected object Params;
public string stringResult;
public object SyncRoot;
public Error error;
protected virtual void init() { }
public Result(ZabbixAPI Server)
{
init();
server = Server;
SyncRoot = new object();
}
public Result()
{
init();
}
public virtual void get()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = 16777216;
server.Update(new UpdateInfoMessage(this) { message = "Sending request to server...", status = "INFO" });
lock (SyncRoot)
{
stringResult = (server.CallAPI(method, Params));
server.Update(new UpdateInfoMessage(this) { message = "Processing query result...", status = "INFO" });
try
{
Result<T> myResult = serializer.Deserialize<Result<T>>(stringResult);
error = myResult.error;
result = myResult.result;
}
catch (ArgumentException ex)
{
server.Update(new UpdateInfoMessage(this) { message = "ArgumentException: " + ex.Message, status = "INFO" });
}
if (error == null)
{
server.Update(new UpdateInfoMessage(this) { message = "", status = "INFO" });
} else {
server.Update(new UpdateInfoMessage(this) { message = "Error: " + error.data, status = "INFO" });
}
if (result == null)
{
result = new T[1];
}
}
}
public virtual void getWithParams(object p)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = 16777216;
server.Update(new UpdateInfoMessage(this) { message = "Sending request to server...", status = "INFO" });
lock (SyncRoot)
{
stringResult = (server.CallAPI(method, p));
server.Update(new UpdateInfoMessage(this) { message = "Processing query result...", status = "INFO" });
try
{
Result<T> myResult = serializer.Deserialize<Result<T>>(stringResult);
error = myResult.error;
result = myResult.result;
}
catch (ArgumentException ex)
{
server.Update(new UpdateInfoMessage(this) { message = "ArgumentException: " + ex.Message, status = "INFO" });
}
if (error == null)
{
server.Update(new UpdateInfoMessage(this) { message = "", status = "INFO" });
}
else
{
server.Update(new UpdateInfoMessage(this) { message = "Error: " + error.data, status = "INFO" });
}
if (result == null)
{
result = new T[1];
}
}
}
public T this[int index]
{
get
{
try
{
return result[index];
}
catch (IndexOutOfRangeException)
{
return default(T);
}
}
}
public IEnumerator<T> GetEnumerator()
{
if (result != null)
{
foreach (T item in result)
{
yield return item;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class Error
{
public int code;
public string message;
public string data;
}
public class simpleresult
{
public string result;
}
public class Triggers : Result<Trigger>
{
protected override void init()
{
method = "trigger.get";
Params = new
{
output = "extend",
//select_hosts = "extend",
selectHosts = "extend",
monitored = "1",
templated = "0",
only_true = "1",
sortfield = "lastchange",
};
}
public Triggers(ZabbixAPI Server) : base(Server) { }
public override void get()
{
base.get();
foreach (Trigger tr in result)
{
if (tr != null)
{
tr.host = tr.hosts[0];
}
}
}
public void getWithParam(object p)
{
base.getWithParams(p);
foreach (Trigger tr in result)
{
if (tr != null && tr.hosts != null)
{
tr.host = tr.hosts[0];
}
}
}
public List<Trigger> getByHostid(String hostid)
{
var q = from res in result
where res.host.hostid == hostid
select res;
List<Trigger> trgs = new List<Trigger>(q);
return trgs;
}
public void refresh()
{
get();
}
}
public class Hosts : Result<Host>
{
protected override void init()
{
method = "host.get";
Params = new { output = "extend" };
}
public void getByGroupID(string GroupID)
{
Params = new { output = "extend", groupids = GroupID };
base.get();
}
public Hosts(ZabbixAPI Server) : base(Server) { }
}
public class Host
{
public string host;
public string hostid;
public string ip;
public override string ToString()
{
return host;
}
}
public class Trigger
{
public Host[] hosts { get; set; }
public string triggerid { get; set; }
public string expression { get; set; }
public string description { get; set; }
public string url { get; set; }
public string status { get; set; }
public string value { get; set; }
public string priority { get; set; }
public string lastchange { get; set; }
public DateTime lastchangeDateTime
{
get
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return origin.AddSeconds(double.Parse(lastchange));
}
}
public string dep_level { get; set; }
public string comments { get; set; }
public string error { get; set; }
public string templateid { get; set; }
public string type { get; set; }
public Host host { get; set; }
}
public class HostGroups:Result<HostGroup>
{
protected override void init()
{
method = "hostgroup.get";
Params = new { output = "extend" };
}
public override void get()
{
base.get();
foreach (HostGroup h in result)
{
if (h != null)
{
h.hosts = new Hosts(server);
h.hosts.getByGroupID(h.groupid);
}
}
}
public HostGroups(ZabbixAPI Server) : base(Server) { }
}
public class HostGroup
{
public string groupid;
public string name;
public int inter;
public override string ToString()
{
return name;
}
public string getID()
{
return groupid;
}
public Hosts hosts;
}
public class Events : Result<Event>
{
protected override void init()
{
method = "event.get";
Params = new
{
output = "extend",
sortfield = "clock",
sortorder = "ASC",
//select_hosts = "shorten",
selectHosts = "shorten",
select_triggers = "shorten",
limit = "1000"
};
}
public Events(ZabbixAPI Server) : base(Server) { }
}
public class Event
{
}
}