瀏覽代碼

Add influx compatibility

Nick Babcock 7 年之前
父節點
當前提交
2718e3ef77

+ 39 - 0
OhmGraphite/GraphiteConfig.cs

@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace OhmGraphite
+{
+    class GraphiteConfig
+    {
+        public GraphiteConfig(string host, int port, bool tags)
+        {
+            Host = host;
+            Port = port;
+            Tags = tags;
+        }
+
+        public string Host { get; }
+        public int Port { get; }
+        public bool Tags { get; }
+
+        public static GraphiteConfig ParseAppSettings()
+        {
+            string host = ConfigurationManager.AppSettings["host"] ?? "localhost";
+            if (!int.TryParse(ConfigurationManager.AppSettings["port"], out int port))
+            {
+                port = 2003;
+            }
+
+            if (!bool.TryParse(ConfigurationManager.AppSettings["tags"], out bool tags))
+            {
+                tags = false;
+            }
+
+            return new GraphiteConfig(host, port, tags);
+        }
+    }
+}

+ 1 - 1
OhmGraphite/GraphiteWriter.cs

@@ -8,7 +8,7 @@ using static System.FormattableString;
 
 
 namespace OhmGraphite
 namespace OhmGraphite
 {
 {
-    public class GraphiteWriter
+    public class GraphiteWriter : IWriteMetrics
     {
     {
         private readonly string _localHost;
         private readonly string _localHost;
         private readonly string _remoteHost;
         private readonly string _remoteHost;

+ 10 - 0
OhmGraphite/IWriteMetrics.cs

@@ -0,0 +1,10 @@
+using System;
+using System.Collections.Generic;
+
+namespace OhmGraphite
+{
+    interface IWriteMetrics
+    {
+        void ReportMetrics(DateTime reportTime, IEnumerable<ReportedValue> sensors);
+    }
+}

+ 45 - 0
OhmGraphite/InfluxConfig.cs

@@ -0,0 +1,45 @@
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace OhmGraphite
+{
+    class InfluxConfig
+    {
+        public InfluxConfig(Uri address, string db, string user, string password)
+        {
+            this.Address = address;
+            this.Db = db;
+            this.User = user;
+            this.Password = password;
+        }
+
+        public Uri Address { get; }
+        public string Db { get; }
+        public string User { get; }
+        public string Password { get; }
+
+        public static InfluxConfig ParseAppSettings()
+        {
+            string influxAddress = ConfigurationManager.AppSettings["influx_address"];
+            if (!Uri.TryCreate(influxAddress, UriKind.Absolute, out var addr))
+            {
+                throw new ApplicationException($"Unable to parse {influxAddress} into a Uri");
+            }
+
+            var db = ConfigurationManager.AppSettings["influx_db"];
+            if (string.IsNullOrEmpty(db))
+            {
+                throw new ApplicationException("influx_db must be specified in the config");
+            }
+
+            var user = ConfigurationManager.AppSettings["influx_user"];
+            var password = ConfigurationManager.AppSettings["influx_password"];
+
+            return new InfluxConfig(addr, db, user, password);
+        }
+    }
+}

+ 65 - 0
OhmGraphite/InfluxWriter.cs

@@ -0,0 +1,65 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using InfluxDB.LineProtocol;
+using InfluxDB.LineProtocol.Client;
+using InfluxDB.LineProtocol.Payload;
+using NLog;
+using OpenHardwareMonitor.Hardware;
+
+namespace OhmGraphite
+{
+    class InfluxWriter : IWriteMetrics
+    {
+        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
+
+        private readonly InfluxConfig _config;
+        private readonly string _localHost;
+
+        public InfluxWriter(InfluxConfig config, string localHost)
+        {
+            _config = config;
+            _localHost = localHost;
+        }
+
+        public void ReportMetrics(DateTime reportTime, IEnumerable<ReportedValue> sensors)
+        {
+            var payload = new LineProtocolPayload();
+            var client = new LineProtocolClient(_uri, _db, _user, _password);
+            var writer = new LineProtocolWriter(Precision.Seconds);
+            foreach (var point in sensors.Select(x => NewMethod(reportTime, x)))
+            {
+                payload.Add(point);
+            }
+
+            var task = client.SendAsync(writer);
+            task.RunSynchronously();
+            var result = task.Result;
+            if (!result.Success)
+            {
+                Logger.Error("Influxdb encountered an error: {0}", result.ErrorMessage);
+            }
+        }
+
+        private LineProtocolPoint NewMethod(DateTime reportTime, ReportedValue sensor)
+        {
+            var tags = new Dictionary<string, string>()
+            {
+                {"host", _localHost},
+                {"app", "ohm"},
+                {"hardware", sensor.Hardware},
+                {"hardware_type", Enum.GetName(typeof(HardwareType), sensor.HardwareType)},
+                {"sensor", sensor.Sensor},
+                {"sensor_type", Enum.GetName(typeof(SensorType), sensor.SensorType)}
+            };
+
+            var fields = new Dictionary<string, object>()
+            {
+                {"value", sensor.Value},
+                {"sensor_index", sensor.SensorIndex}
+            };
+
+            return new LineProtocolPoint(sensor.Identifier, fields, tags, reportTime.ToUniversalTime());
+        }
+    }
+}

+ 21 - 18
OhmGraphite/MetricConfig.cs

@@ -5,39 +5,42 @@ namespace OhmGraphite
 {
 {
     public class MetricConfig
     public class MetricConfig
     {
     {
-        public MetricConfig(string host, int port, TimeSpan interval, bool tags)
+        public MetricConfig(TimeSpan interval, GraphiteConfig graphite, InfluxConfig influx)
         {
         {
-            Host = host;
-            Port = port;
             Interval = interval;
             Interval = interval;
-            Tags = tags;
+            Graphite = graphite;
+            Influx = influx;
         }
         }
 
 
-        public string Host { get; }
-        public int Port { get; }
         public TimeSpan Interval { get; }
         public TimeSpan Interval { get; }
-        public bool Tags { get; }
+        public GraphiteConfig Graphite { get; }
+        public InfluxConfig Influx { get; }
 
 
         public static MetricConfig ParseAppSettings()
         public static MetricConfig ParseAppSettings()
         {
         {
-            string host = ConfigurationManager.AppSettings["host"] ?? "localhost";
-            if (!int.TryParse(ConfigurationManager.AppSettings["port"], out int port))
+            if (!int.TryParse(ConfigurationManager.AppSettings["interval"], out int seconds))
             {
             {
-                port = 2003;
+                seconds = 5;
             }
             }
 
 
-            if (!bool.TryParse(ConfigurationManager.AppSettings["tags"], out bool tags))
-            {
-                tags = false;
-            }
+            var interval = TimeSpan.FromSeconds(seconds);
 
 
-            if (!int.TryParse(ConfigurationManager.AppSettings["interval"], out int seconds))
+            var type = ConfigurationManager.AppSettings["type"] ?? "graphite";
+            var gconfig = null;
+            var iconfig = null;
+
+            switch (type.ToLowerInvariant())
             {
             {
-                seconds = 5;
+                case "graphite":
+                    gconfig = GraphiteConfig.ParseAppSettings();
+                    break;
+                case "influxdb":
+                case "influx":
+                    iconfig = InfluxConfig.ParseAppSettings();
+                    break;
             }
             }
 
 
-            var interval = TimeSpan.FromSeconds(seconds);
-            return new MetricConfig(host, port, interval, tags);
+            return new MetricConfig(interval, gconfig, iconfig);
         }
         }
     }
     }
 }
 }

+ 2 - 2
OhmGraphite/MetricTimer.cs

@@ -12,9 +12,9 @@ namespace OhmGraphite
         private readonly SensorCollector _collector;
         private readonly SensorCollector _collector;
 
 
         private readonly Timer _timer;
         private readonly Timer _timer;
-        private readonly GraphiteWriter _writer;
+        private readonly IWriteMetrics _writer;
 
 
-        public MetricTimer(TimeSpan interval, SensorCollector collector, GraphiteWriter writer)
+        public MetricTimer(TimeSpan interval, SensorCollector collector, IWriteMetrics writer)
         {
         {
             _timer = new Timer(interval.TotalMilliseconds) {AutoReset = true};
             _timer = new Timer(interval.TotalMilliseconds) {AutoReset = true};
             _timer.Elapsed += ReportMetrics;
             _timer.Elapsed += ReportMetrics;

+ 2 - 1
OhmGraphite/OhmGraphite.csproj

@@ -34,6 +34,7 @@
     <PackageReference Include="NLog.Config" Version="4.4.12" />
     <PackageReference Include="NLog.Config" Version="4.4.12" />
     <PackageReference Include="TopShelf" Version="4.0.3" />
     <PackageReference Include="TopShelf" Version="4.0.3" />
     <PackageReference Include="Topshelf.NLog" Version="4.0.3" />
     <PackageReference Include="Topshelf.NLog" Version="4.0.3" />
+    <PackageReference Include="InfluxDB.LineProtocol" Version="1.1.0" />
   </ItemGroup>
   </ItemGroup>
   <ItemGroup>
   <ItemGroup>
     <ProjectReference Include="..\LibreHardwareMonitor\OpenHardwareMonitorLib.csproj" />
     <ProjectReference Include="..\LibreHardwareMonitor\OpenHardwareMonitorLib.csproj" />
@@ -43,6 +44,6 @@
   </ItemGroup>
   </ItemGroup>
 
 
   <Target Name="ILPack" AfterTargets="Build" Condition="'$(Configuration)' == 'Release'">
   <Target Name="ILPack" AfterTargets="Build" Condition="'$(Configuration)' == 'Release'">
-    <Exec Command="&quot;$(NuGetPackageRoot)ilrepack\2.0.15\tools\ILRepack.exe&quot; /out:$(OutputPath)OhmGraphite.exe $(OutputPath)OhmGraphite.exe $(OutputPath)Topshelf.dll $(OutputPath)Topshelf.NLog.dll $(OutputPath)NLog.dll $(OutputPath)OpenHardwareMonitorLib.dll" />
+    <Exec Command="&quot;$(NuGetPackageRoot)ilrepack\2.0.15\tools\ILRepack.exe&quot; /out:$(OutputPath)OhmGraphite.exe $(OutputPath)OhmGraphite.exe $(OutputPath)Topshelf.dll $(OutputPath)Topshelf.NLog.dll $(OutputPath)NLog.dll $(OutputPath)OpenHardwareMonitorLib.dll $(OutputPath)InfluxDB.LineProtocol.dll" />
   </Target>
   </Target>
 </Project>
 </Project>

+ 14 - 2
OhmGraphite/Program.cs

@@ -19,7 +19,20 @@ namespace OhmGraphite
                     // to poll the hardware
                     // to poll the hardware
                     var config = Logger.LogFunction("parse config", MetricConfig.ParseAppSettings);
                     var config = Logger.LogFunction("parse config", MetricConfig.ParseAppSettings);
                     double seconds = config.Interval.TotalSeconds;
                     double seconds = config.Interval.TotalSeconds;
-                    Logger.Info($"Host: {config.Host} port: {config.Port} interval: {seconds} tags: {config.Tags}");
+                    IWriteMetrics writer = null;
+                    if (config.Graphite != null)
+                    {
+                        Logger.Info($"Graphite host: {config.Graphite.Host} port: {config.Graphite.Port} interval: {seconds} tags: {config.Graphite.Tags}");
+                        writer = new GraphiteWriter(config.Graphite.Host,
+                            config.Graphite.Port,
+                            Environment.MachineName,
+                            config.Graphite.Tags);
+                    }
+                    else
+                    {
+                        Logger.Info($"Influxdb address: {config.Influx.Address} db: {config.Influx.Db}");
+                        writer = new InfluxWriter(config.Influx, Environment.MachineName);
+                    }
 
 
                     // We'll want to capture all available hardware metrics
                     // We'll want to capture all available hardware metrics
                     // to send to graphite
                     // to send to graphite
@@ -34,7 +47,6 @@ namespace OhmGraphite
                     };
                     };
 
 
                     var collector = new SensorCollector(computer);
                     var collector = new SensorCollector(computer);
-                    var writer = new GraphiteWriter(config.Host, config.Port, Environment.MachineName, config.Tags);
 
 
                     s.ConstructUsing(name =>
                     s.ConstructUsing(name =>
                         Logger.LogFunction("creating timer",
                         Logger.LogFunction("creating timer",