InfluxTest.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. using System;
  2. using System.Configuration;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Threading;
  7. using DotNet.Testcontainers.Builders;
  8. using InfluxDB.Client;
  9. using Xunit;
  10. namespace OhmGraphite.Test
  11. {
  12. public class InfluxTest
  13. {
  14. [Fact, Trait("Category", "integration")]
  15. public async void CanInsertIntoInflux()
  16. {
  17. var testContainersBuilder = new ContainerBuilder()
  18. .WithDockerEndpoint(DockerUtils.DockerEndpoint())
  19. .WithImage("influxdb:1.8-alpine")
  20. .WithEnvironment("INFLUXDB_DB", "mydb")
  21. .WithEnvironment("INFLUXDB_USER", "my_user")
  22. .WithEnvironment("INFLUXDB_USER_PASSWORD", "my_pass")
  23. .WithPortBinding(8086, assignRandomHostPort: true)
  24. .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8086));
  25. await using var container = testContainersBuilder.Build();
  26. await container.StartAsync();
  27. var baseUrl = $"http://{container.Hostname}:{container.GetMappedPublicPort(8086)}";
  28. var config = new InfluxConfig(new Uri(baseUrl), "mydb", "my_user", "my_pass");
  29. using var writer = new InfluxWriter(config, "my-pc");
  30. using var client = new HttpClient();
  31. for (int attempts = 0; ; attempts++)
  32. {
  33. try
  34. {
  35. await writer.ReportMetrics(DateTime.Now, TestSensorCreator.Values());
  36. var resp = await client.GetAsync(
  37. $"{baseUrl}/query?pretty=true&db=mydb&q=SELECT%20*%20FROM%20Temperature");
  38. Assert.True(resp.IsSuccessStatusCode);
  39. var content = await resp.Content.ReadAsStringAsync();
  40. Assert.Contains("/intelcpu/0/temperature/0", content);
  41. break;
  42. }
  43. catch (Exception)
  44. {
  45. if (attempts >= 10)
  46. {
  47. throw;
  48. }
  49. Thread.Sleep(TimeSpan.FromSeconds(1));
  50. }
  51. }
  52. }
  53. [Fact, Trait("Category", "integration")]
  54. public async void CanInsertIntoPasswordLessInfluxdb()
  55. {
  56. var testContainersBuilder = new ContainerBuilder()
  57. .WithDockerEndpoint(DockerUtils.DockerEndpoint())
  58. .WithImage("influxdb:1.8-alpine")
  59. .WithEnvironment("INFLUXDB_DB", "mydb")
  60. .WithEnvironment("INFLUXDB_USER", "my_user")
  61. .WithEnvironment("INFLUXDB_HTTP_AUTH_ENABLED", "false")
  62. .WithPortBinding(8086, assignRandomHostPort: true)
  63. .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8086));
  64. await using var container = testContainersBuilder.Build();
  65. await container.StartAsync();
  66. var baseUrl = $"http://{container.Hostname}:{container.GetMappedPublicPort(8086)}";
  67. var config = new InfluxConfig(new Uri(baseUrl), "mydb", "my_user", null);
  68. using var writer = new InfluxWriter(config, "my-pc");
  69. using var client = new HttpClient();
  70. for (int attempts = 0; ; attempts++)
  71. {
  72. try
  73. {
  74. await writer.ReportMetrics(DateTime.Now, TestSensorCreator.Values());
  75. var resp = await client.GetAsync(
  76. $"{baseUrl}/query?pretty=true&db=mydb&q=SELECT%20*%20FROM%20Temperature");
  77. Assert.True(resp.IsSuccessStatusCode);
  78. var content = await resp.Content.ReadAsStringAsync();
  79. Assert.Contains("/intelcpu/0/temperature/0", content);
  80. break;
  81. }
  82. catch (Exception)
  83. {
  84. if (attempts >= 10)
  85. {
  86. throw;
  87. }
  88. Thread.Sleep(TimeSpan.FromSeconds(1));
  89. }
  90. }
  91. }
  92. [Fact, Trait("Category", "integration")]
  93. public async void CanInsertIntoInflux2()
  94. {
  95. var testContainersBuilder = new ContainerBuilder()
  96. .WithDockerEndpoint(DockerUtils.DockerEndpoint())
  97. .WithImage("influxdb:2.0-alpine")
  98. .WithEnvironment("DOCKER_INFLUXDB_INIT_MODE", "setup")
  99. .WithEnvironment("DOCKER_INFLUXDB_INIT_USERNAME", "my-user")
  100. .WithEnvironment("DOCKER_INFLUXDB_INIT_PASSWORD", "my-password")
  101. .WithEnvironment("DOCKER_INFLUXDB_INIT_BUCKET", "mydb")
  102. .WithEnvironment("DOCKER_INFLUXDB_INIT_ORG", "myorg")
  103. .WithPortBinding(8086, assignRandomHostPort: true)
  104. .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8086));
  105. await using var container = testContainersBuilder.Build();
  106. await container.StartAsync();
  107. var baseUrl = $"http://{container.Hostname}:{container.GetMappedPublicPort(8086)}";
  108. var options = new InfluxDBClientOptions.Builder()
  109. .Url(baseUrl)
  110. .Authenticate("my-user", "my-password".ToCharArray())
  111. .Bucket("mydb")
  112. .Org("myorg")
  113. .Build();
  114. var config = new Influx2Config(options);
  115. using var writer = new Influx2Writer(config, "my-pc");
  116. for (int attempts = 0; ; attempts++)
  117. {
  118. try
  119. {
  120. await writer.ReportMetrics(DateTime.Now, TestSensorCreator.Values());
  121. var influxDBClient = new InfluxDBClient(options);
  122. var flux = "from(bucket:\"mydb\") |> range(start: -1h)";
  123. var queryApi = influxDBClient.GetQueryApi();
  124. var tables = await queryApi.QueryAsync(flux, "myorg");
  125. var fields = tables.SelectMany(x => x.Records).Select(x => x.GetValueByKey("identifier"));
  126. Assert.Contains("/intelcpu/0/temperature/0", fields);
  127. break;
  128. }
  129. catch (Exception)
  130. {
  131. if (attempts >= 10)
  132. {
  133. throw;
  134. }
  135. Thread.Sleep(TimeSpan.FromSeconds(1));
  136. }
  137. }
  138. }
  139. [Fact, Trait("Category", "integration")]
  140. public async void CanInsertIntoInflux2Token()
  141. {
  142. var testContainersBuilder = new ContainerBuilder()
  143. .WithDockerEndpoint(DockerUtils.DockerEndpoint())
  144. .WithImage("influxdb:2.0-alpine")
  145. .WithEnvironment("DOCKER_INFLUXDB_INIT_MODE", "setup")
  146. .WithEnvironment("DOCKER_INFLUXDB_INIT_USERNAME", "my-user")
  147. .WithEnvironment("DOCKER_INFLUXDB_INIT_PASSWORD", "my-password")
  148. .WithEnvironment("DOCKER_INFLUXDB_INIT_BUCKET", "mydb")
  149. .WithEnvironment("DOCKER_INFLUXDB_INIT_ORG", "myorg")
  150. .WithEnvironment("DOCKER_INFLUXDB_INIT_ADMIN_TOKEN", "thisistheinfluxdbtoken")
  151. .WithPortBinding(8086, assignRandomHostPort: true)
  152. .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8086));
  153. await using var container = testContainersBuilder.Build();
  154. await container.StartAsync();
  155. var baseUrl = $"http://{container.Hostname}:{container.GetMappedPublicPort(8086)}";
  156. var configMap = new ExeConfigurationFileMap { ExeConfigFilename = "assets/influx2.config" };
  157. var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
  158. config.AppSettings.Settings["influx2_address"].Value = baseUrl;
  159. var customConfig = new CustomConfig(config);
  160. var results = MetricConfig.ParseAppSettings(customConfig);
  161. using var writer = new Influx2Writer(results.Influx2, "my-pc");
  162. for (int attempts = 0; ; attempts++)
  163. {
  164. try
  165. {
  166. await writer.ReportMetrics(DateTime.Now, TestSensorCreator.Values());
  167. var influxDBClient = new InfluxDBClient(results.Influx2.Options);
  168. var flux = "from(bucket:\"mydb\") |> range(start: -1h)";
  169. var queryApi = influxDBClient.GetQueryApi();
  170. var tables = await queryApi.QueryAsync(flux, "myorg");
  171. var fields = tables.SelectMany(x => x.Records).Select(x => x.GetValueByKey("identifier"));
  172. Assert.Contains("/intelcpu/0/temperature/0", fields);
  173. break;
  174. }
  175. catch (Exception)
  176. {
  177. if (attempts >= 10)
  178. {
  179. throw;
  180. }
  181. Thread.Sleep(TimeSpan.FromSeconds(1));
  182. }
  183. }
  184. }
  185. [Fact, Trait("Category", "integration")]
  186. public async void CanInsertIntoInflux2TokenTls()
  187. {
  188. // We do some fancy docker footwork where we informally connect
  189. // these two containers. In the future I believe test containers will
  190. // be able to natively handle adding these to a docker network
  191. var testContainersBuilder = new ContainerBuilder()
  192. .WithDockerEndpoint(DockerUtils.DockerEndpoint())
  193. .WithImage("influxdb:2.0-alpine")
  194. .WithEnvironment("DOCKER_INFLUXDB_INIT_MODE", "setup")
  195. .WithEnvironment("DOCKER_INFLUXDB_INIT_USERNAME", "my-user")
  196. .WithEnvironment("DOCKER_INFLUXDB_INIT_PASSWORD", "my-password")
  197. .WithEnvironment("DOCKER_INFLUXDB_INIT_BUCKET", "mydb")
  198. .WithEnvironment("DOCKER_INFLUXDB_INIT_ORG", "myorg")
  199. .WithEnvironment("DOCKER_INFLUXDB_INIT_ADMIN_TOKEN", "thisistheinfluxdbtoken")
  200. .WithPortBinding(8086, assignRandomHostPort: true)
  201. .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8086));
  202. await using var container = testContainersBuilder.Build();
  203. await container.StartAsync();
  204. var cmd = $"apk add openssl && openssl req -x509 -nodes -newkey rsa:4096 -keyout /tmp/key.pem -out /tmp/cert.pem -days 365 -subj '/C=US/ST=Oregon/L=Portland/O=Company Name/OU=Org/CN=www.example.com' && /usr/bin/ghostunnel server --listen=0.0.0.0:8087 --target={container.IpAddress}:8086 --unsafe-target --disable-authentication --key /tmp/key.pem --cert=/tmp/cert.pem";
  205. var tlsContainerBuilder = new ContainerBuilder()
  206. .WithDockerEndpoint(DockerUtils.DockerEndpoint())
  207. .WithImage("squareup/ghostunnel")
  208. .WithExposedPort(8087)
  209. .WithPortBinding(8087, assignRandomHostPort: true)
  210. .WithWaitStrategy(Wait.ForUnixContainer().UntilPortIsAvailable(8087))
  211. .WithEntrypoint("/bin/sh")
  212. .WithCommand("-c", cmd);
  213. await using var tlsContainer = tlsContainerBuilder.Build();
  214. await tlsContainer.StartAsync();
  215. var baseUrl = $"https://{tlsContainer.Hostname}:{tlsContainer.GetMappedPublicPort(8087)}";
  216. var configMap = new ExeConfigurationFileMap { ExeConfigFilename = "assets/influx2-ssl.config" };
  217. var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
  218. config.AppSettings.Settings["influx2_address"].Value = baseUrl;
  219. var customConfig = new CustomConfig(config);
  220. var results = MetricConfig.ParseAppSettings(customConfig);
  221. try
  222. {
  223. using var writer = new Influx2Writer(results.Influx2, "my-pc");
  224. for (int attempts = 0; ; attempts++)
  225. {
  226. try
  227. {
  228. await writer.ReportMetrics(DateTime.Now, TestSensorCreator.Values());
  229. var influxDbClient = new InfluxDBClient(results.Influx2.Options);
  230. var flux = "from(bucket:\"mydb\") |> range(start: -1h)";
  231. var queryApi = influxDbClient.GetQueryApi();
  232. var tables = await queryApi.QueryAsync(flux, "myorg");
  233. var fields = tables.SelectMany(x => x.Records).Select(x => x.GetValueByKey("identifier"));
  234. Assert.Contains("/intelcpu/0/temperature/0", fields);
  235. break;
  236. }
  237. catch (Exception)
  238. {
  239. if (attempts >= 10)
  240. {
  241. throw;
  242. }
  243. Thread.Sleep(TimeSpan.FromSeconds(1));
  244. }
  245. }
  246. }
  247. finally
  248. {
  249. ServicePointManager.ServerCertificateValidationCallback = null;
  250. }
  251. }
  252. }
  253. }