1
0

GraphiteWriter.cs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using NLog;
  8. using OpenHardwareMonitor.Hardware;
  9. using static System.FormattableString;
  10. namespace OhmGraphite
  11. {
  12. public class GraphiteWriter : IWriteMetrics
  13. {
  14. private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
  15. private readonly string _localHost;
  16. private readonly string _remoteHost;
  17. private readonly int _remotePort;
  18. private readonly bool _tags;
  19. private readonly TcpClient _client = new TcpClient();
  20. private static readonly Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
  21. public GraphiteWriter(string remoteHost, int remotePort, string localHost, bool tags)
  22. {
  23. _remoteHost = remoteHost;
  24. _remotePort = remotePort;
  25. _tags = tags;
  26. _localHost = localHost;
  27. }
  28. public async Task ReportMetrics(DateTime reportTime, IEnumerable<ReportedValue> sensors)
  29. {
  30. // Reconnect whenever the previous network attempt failed or first
  31. // time connections
  32. if (!_client.Connected)
  33. {
  34. Logger.Debug($"New connection to {_remoteHost}:{_remotePort}");
  35. await _client.ConnectAsync(_remoteHost, _remotePort);
  36. }
  37. // We don't want to transmit metrics across multiple seconds as they
  38. // are being retrieved so calculate the timestamp of the signaled event
  39. // only once.
  40. long epoch = new DateTimeOffset(reportTime).ToUnixTimeSeconds();
  41. // Create a stream writer that leaves the underlying stream open
  42. // when the writer is closed, as we don't want our TCP connection
  43. // closed too. Since this requires the four param constructor for
  44. // the stream writer, the encoding and buffer sized are copied from
  45. // the C# reference source.
  46. using (var writer = new StreamWriter(_client.GetStream(), Utf8NoBom, bufferSize: 1024, leaveOpen: true))
  47. {
  48. foreach (var sensor in sensors)
  49. {
  50. await writer.WriteLineAsync(FormatGraphiteData(epoch, sensor));
  51. }
  52. }
  53. await _client.GetStream().FlushAsync();
  54. }
  55. private static string NormalizedIdentifier(string host, ReportedValue sensor)
  56. {
  57. // Take the sensor's identifier (eg. /nvidiagpu/0/load/0)
  58. // and tranform into nvidiagpu.0.load.<name> where <name>
  59. // is the name of the sensor lowercased with spaces removed.
  60. // A name like "GPU Core" is turned into "gpucore". Also
  61. // since some names are like "cpucore#2", turn them into
  62. // separate metrics by replacing "#" with "."
  63. string identifier = sensor.Identifier.Replace('/', '.').Substring(1);
  64. identifier = identifier.Remove(identifier.LastIndexOf('.'));
  65. string name = sensor.Sensor.ToLower().Replace(" ", null).Replace('#', '.');
  66. return $"ohm.{host}.{identifier}.{name}";
  67. }
  68. public static string GraphiteEscape(string src)
  69. {
  70. // Formula for escaping graphite data is taken from
  71. // collectd's utils_format_graphite.c
  72. var builder = new StringBuilder(src.Length);
  73. foreach (char c in src)
  74. {
  75. if (c == '.' || char.IsWhiteSpace(c) || char.IsControl(c))
  76. {
  77. builder.Append('-');
  78. }
  79. else
  80. {
  81. builder.Append(c);
  82. }
  83. }
  84. return builder.ToString();
  85. }
  86. public string FormatGraphiteData(long epoch, ReportedValue data)
  87. {
  88. // Graphite API wants <metric> <value> <timestamp>. We prefix the metric
  89. // with `ohm` as to not overwrite potentially existing metrics
  90. string id = NormalizedIdentifier(_localHost, data);
  91. if (!_tags)
  92. {
  93. return Invariant($"{id} {data.Value} {epoch:d}");
  94. }
  95. return $"{id};" +
  96. $"host={_localHost};" +
  97. "app=ohm;" +
  98. $"hardware={GraphiteEscape(data.Hardware)};" +
  99. $"hardware_type={Enum.GetName(typeof(HardwareType), data.HardwareType)};" +
  100. $"sensor_type={Enum.GetName(typeof(SensorType), data.SensorType)};" +
  101. $"sensor_index={data.SensorIndex};" +
  102. $"raw_name={GraphiteEscape(data.Sensor)} " +
  103. $"{data.Value} {epoch:d}";
  104. }
  105. }
  106. }