GraphiteWriter.cs 5.3 KB

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