Added Zabbix support

This commit is contained in:
jsaey
2024-07-26 10:28:30 +02:00
parent 7e41f8108d
commit ff7a40167c
7 changed files with 307 additions and 2 deletions

View File

@@ -3,7 +3,7 @@
<TargetFrameworks>.netstandard2.1; net6.0; net7.0; net8.0; net4.8;</TargetFrameworks> <TargetFrameworks>.netstandard2.1; net6.0; net7.0; net8.0; net4.8;</TargetFrameworks>
<ApplicationIcon>icon.ico</ApplicationIcon> <ApplicationIcon>icon.ico</ApplicationIcon>
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>
<FileVersion>1.3.0</FileVersion> <FileVersion>1.3.1</FileVersion>
<Authors>EonaCat (Jeroen Saey)</Authors> <Authors>EonaCat (Jeroen Saey)</Authors>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Company>EonaCat (Jeroen Saey)</Company> <Company>EonaCat (Jeroen Saey)</Company>
@@ -24,7 +24,7 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<EVRevisionFormat>1.3.0+{chash:10}.{c:ymd}</EVRevisionFormat> <EVRevisionFormat>1.3.1+{chash:10}.{c:ymd}</EVRevisionFormat>
<EVDefault>true</EVDefault> <EVDefault>true</EVDefault>
<EVInfo>true</EVInfo> <EVInfo>true</EVInfo>
<EVTagMatch>v[0-9]*</EVTagMatch> <EVTagMatch>v[0-9]*</EVTagMatch>

View File

@@ -0,0 +1,141 @@
using EonaCat.Json;
using System;
using System.Dynamic;
using System.IO;
using System.Net;
using System.Text;
namespace EonaCat.Logger.Zabbix.API;
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class ZabbixApi
{
public ZabbixApi(string user, string password, string zabbixURL, bool basicAuth)
{
_user = user;
_password = password;
_zabbixURL = zabbixURL;
if (basicAuth)
{
_basicAuth = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(_user + ":" + _password));
}
_auth = null;
}
public ZabbixApi(string user, string password, string zabbixURL) : this(user, password, zabbixURL, false)
{
}
private readonly string _user;
private readonly string _password;
private readonly string _zabbixURL;
private string _auth;
private readonly string _basicAuth = null;
/// <summary>
/// Determines if the user is logged in
/// </summary>
public bool IsLoggedIn { get; set; }
/// <summary>
/// Logs in the user
/// </summary>
public void Login()
{
dynamic authentication = new ExpandoObject();
authentication.user = _user;
authentication.password = _password;
ZabbixApiResponse zabbixApiResponse = ResponseAsObject("user.login", authentication);
_auth = zabbixApiResponse.Result;
IsLoggedIn = !string.IsNullOrEmpty(_auth);
}
/// <summary>
/// Logs out the user
/// </summary>
/// <returns></returns>
public bool Logout()
{
ZabbixApiResponse zbxResponse = ResponseAsObject("user.logout", new string[] { });
var result = zbxResponse.Result;
return result;
}
/// <summary>
/// Generic method to send a request to the Zabbix API
/// </summary>
/// <param name="method"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public string ResponseAsJson(string method, object parameters)
{
ZabbixApiRequest zbxRequest = new ZabbixApiRequest("2.0", method, 1, _auth, parameters);
string jsonParameters = JsonHelper.ToJson(zbxRequest);
return SendRequest(jsonParameters);
}
/// <summary>
/// Generic method to send a request to the Zabbix API
/// </summary>
/// <param name="method"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public ZabbixApiResponse ResponseAsObject(string method, object parameters)
{
ZabbixApiRequest zbxRequest = new ZabbixApiRequest("2.0", method, 1, _auth, parameters);
string jsonParameters = JsonHelper.ToJson(zbxRequest);
return CreateResponse(SendRequest(jsonParameters));
}
/// <summary>
/// Creates a ZabbixApiResponse object from a JSON string
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
private ZabbixApiResponse CreateResponse(string json)
{
ZabbixApiResponse zbxResponse = JsonHelper.ToObject<ZabbixApiResponse>(json);
return zbxResponse;
}
/// <summary>
/// Sends a request to the Zabbix API
/// </summary>
/// <param name="jsonParams"></param>
/// <returns></returns>
private string SendRequest(string jsonParams)
{
WebRequest request = WebRequest.Create(_zabbixURL);
if (_basicAuth != null)
{
request.Headers.Add("Authorization", "Basic " + _basicAuth);
}
request.ContentType = "application/json-rpc";
request.Method = "POST";
string jsonResult;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(jsonParams);
streamWriter.Flush();
streamWriter.Close();
}
WebResponse response = request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
jsonResult = streamReader.ReadToEnd();
}
return jsonResult;
}
}

View File

@@ -0,0 +1,42 @@
namespace EonaCat.Logger.Zabbix.API
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class ZabbixApiRequest
{
/// <summary>
/// Jsonrpc version
/// </summary>
public string Jsonrpc { get; set; }
/// <summary>
/// Method to call
/// </summary>
public string Method { get; set; }
/// <summary>
/// Id of the request
/// </summary>
public int Id { get; set; }
/// <summary>
/// Authentification token
/// </summary>
public string Auth { get; set; }
/// <summary>
/// Parameters of the request
/// </summary>
public dynamic Parameters { get; set; }
public ZabbixApiRequest(string jsonrpc, string method, int id, string auth, dynamic parameters)
{
Jsonrpc = jsonrpc;
Method = method;
Id = id;
Auth = auth;
Parameters = parameters;
}
}
}

View File

@@ -0,0 +1,25 @@
using System.Dynamic;
namespace EonaCat.Logger.Zabbix.API
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class ZabbixApiResponse
{
/// <summary>
/// Jsonrpc version
/// </summary>
public string Jsonrpc { get; set; }
/// <summary>
/// Result of the request
/// </summary>
public dynamic Result = new ExpandoObject();
/// <summary>
/// Id of the request
/// </summary>
public int Id { get; set; }
}
}

View File

@@ -0,0 +1,17 @@

/// <summary>
/// Zabbix server.
/// </summary>
public class ZabbixData
{
public string Host { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public ZabbixData(string host, string key, string value)
{
Host = host;
Key = key;
Value = value;
}
}

View File

@@ -0,0 +1,74 @@
using EonaCat.Json;
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class ZabbixRequest
{
private const int BUFFER_SIZE = 1024;
/// <summary>
/// The request to send to the Zabbix server
/// </summary>
public string Request { get; set; }
/// <summary>
/// The data to send to the Zabbix server
/// </summary>
public ZabbixData[] Data { get; set; }
public ZabbixRequest(string host, string key, string value)
{
Request = "sender data";
Data = [new ZabbixData(host, key, value)];
}
/// <summary>
/// Sends the request to the Zabbix server
/// </summary>
/// <param name="server"></param>
/// <param name="port"></param>
/// <param name="timeout"></param>
/// <returns></returns>
/// <exception cref="TimeoutException"></exception>
public async Task<ZabbixResponse> SendAsync(string server, int port = 10051, int timeout = 500)
{
string json = JsonHelper.ToJson(new ZabbixRequest(Data[0].Host, Data[0].Key, Data[0].Value));
using (TcpClient tcpClient = new TcpClient(server, port))
using (NetworkStream stream = tcpClient.GetStream())
{
byte[] header = Encoding.ASCII.GetBytes("ZBXD\x01");
byte[] dataLength = BitConverter.GetBytes((long)json.Length);
byte[] content = Encoding.ASCII.GetBytes(json);
byte[] message = new byte[header.Length + dataLength.Length + content.Length];
Buffer.BlockCopy(header, 0, message, 0, header.Length);
Buffer.BlockCopy(dataLength, 0, message, header.Length, dataLength.Length);
Buffer.BlockCopy(content, 0, message, header.Length + dataLength.Length, content.Length);
stream.Write(message, 0, message.Length);
stream.Flush();
int counter = 0;
while (!stream.DataAvailable)
{
if (counter < timeout / 50)
{
counter++;
await Task.Delay(50).ConfigureAwait(false);
}
else
{
throw new TimeoutException();
}
}
byte[] responseBytes = new byte[BUFFER_SIZE];
stream.Read(responseBytes, 0, responseBytes.Length);
string responseAsString = Encoding.UTF8.GetString(responseBytes);
string jsonResult = responseAsString.Substring(responseAsString.IndexOf('{'));
return JsonHelper.ToObject<ZabbixResponse>(jsonResult);
}
}
}

View File

@@ -0,0 +1,6 @@
public class ZabbixResponse
{
public string Response { get; set; }
public string Info { get; set; }
}