├── .nuget ├── NuGet.exe ├── packages.config ├── NuGet.Config └── NuGet.targets ├── InfluxDB.Net ├── Infrastructure │ ├── Formatters │ │ ├── FormatterV096.cs │ │ ├── FormatterV0x.cs │ │ ├── FormatterV010x.cs │ │ ├── FormatterV011x.cs │ │ ├── FormatterV012x.cs │ │ ├── FormatterV013x.cs │ │ ├── FormatterV095.cs │ │ ├── FormatterV1_1_x.cs │ │ ├── FormatterV092.cs │ │ └── FormatterBase.cs │ ├── Influx │ │ ├── InfluxDbException.cs │ │ └── InfluxDbResponse.cs │ ├── Configuration │ │ ├── DatabaseConfiguration.cs │ │ └── InfluxDbClientConfiguration.cs │ └── Validation │ │ └── Validate.cs ├── Contracts │ ├── IRequestContent.cs │ ├── IFormatter.cs │ ├── IInfluxDb.cs │ └── IInfluxDbClient.cs ├── Models │ ├── ContinuousQuery.cs │ ├── Server.cs │ ├── Database.cs │ ├── Shards.cs │ ├── Pong.cs │ ├── QueryResult.cs │ ├── ShardSpace.cs │ ├── Shard.cs │ ├── Serie.cs │ ├── WriteRequest.cs │ ├── User.cs │ └── Point.cs ├── Enums │ ├── TimeUnit.cs │ ├── InfluxVersion.cs │ └── LogLevel.cs ├── Helpers │ ├── HttpUtility.cs │ ├── ObjectExtensions.cs │ └── Stopwatch.cs ├── Constants │ ├── QueryParams.cs │ └── QueryStatements.cs ├── packages.config ├── app.config ├── Client │ ├── InfluxDbClientV0x.cs │ ├── InfluxDbClientV092.cs │ ├── InfluxDbClientV095.cs │ ├── InfluxDbClientV096.cs │ ├── InfluxDbClientV010x.cs │ ├── InfluxDbClientV011x.cs │ ├── InfluxDbClientV012x.cs │ ├── InfluxDbClientV013x.cs │ ├── InfluxDbClientV1_1_x.cs │ ├── InfluxDbClientAutoVersion.cs │ └── InfluxDbClientBase.cs ├── Properties │ └── AssemblyInfo.cs ├── InfluxDB.Net.nuspec ├── InfluxDB.Net.csproj └── InfluxDb.cs ├── InfluxDB.Net.Posh ├── packages.config ├── AddInfluxDb.cs ├── OpenInfluxDb.cs ├── WriteInfluxDb.cs ├── PingInfluxDb.cs ├── Properties │ └── AssemblyInfo.cs ├── TestModule │ └── TestInfluxDb.ps1 └── InfluxDB.Net.Posh.csproj ├── .gitattributes ├── InfluxDB.Net.Tests ├── packages.config ├── Properties │ └── AssemblyInfo.cs ├── app.config ├── TestBase.cs ├── InfluxDB.Net.Tests.csproj └── InfluxDBTests.cs ├── circle.yml ├── LICENSE ├── .gitignore ├── InfluxDB.Net.sln ├── InfluxDB.Net.Posh.sln └── README.md /.nuget/NuGet.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/josephwoodward/InfluxDB.Net/master/.nuget/NuGet.exe -------------------------------------------------------------------------------- /.nuget/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Formatters/FormatterV096.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Infrastructure.Formatters 2 | { 3 | internal class FormatterV096 : FormatterBase 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Formatters/FormatterV0x.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Infrastructure.Formatters 2 | { 3 | internal class FormatterV0x : FormatterBase 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Formatters/FormatterV010x.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Infrastructure.Formatters 2 | { 3 | internal class FormatterV010x : FormatterBase 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Formatters/FormatterV011x.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Infrastructure.Formatters 2 | { 3 | internal class FormatterV011x : FormatterBase 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Formatters/FormatterV012x.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Infrastructure.Formatters 2 | { 3 | internal class FormatterV012x : FormatterBase 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Formatters/FormatterV013x.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Infrastructure.Formatters 2 | { 3 | internal class FormatterV013x : FormatterBase 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Formatters/FormatterV095.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Infrastructure.Formatters 2 | { 3 | internal class FormatterV095 : FormatterBase 4 | { 5 | 6 | } 7 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Formatters/FormatterV1_1_x.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Infrastructure.Formatters 2 | { 3 | internal class FormatterV1_1_x : FormatterBase 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /.nuget/NuGet.Config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /InfluxDB.Net.Posh/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /InfluxDB.Net/Contracts/IRequestContent.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | 3 | namespace InfluxDB.Net.Contracts 4 | { 5 | internal interface IRequestContent 6 | { 7 | HttpContent GetContent(); 8 | } 9 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Models/ContinuousQuery.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Models 2 | { 3 | public class ContinuousQuery 4 | { 5 | public int Id { get; set; } 6 | public string Query { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Models/Server.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Models 2 | { 3 | public class Server 4 | { 5 | public string Id { get; set; } 6 | public string ProtobufConnectString { get; set; } 7 | } 8 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Models/Database.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace InfluxDB.Net.Models 4 | { 5 | public class Database 6 | { 7 | [JsonProperty("name")] 8 | public string Name { get; set; } 9 | } 10 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Enums/TimeUnit.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Enums 2 | { 3 | public enum TimeUnit 4 | { 5 | Seconds, 6 | Milliseconds, 7 | Microseconds, 8 | Minutes, 9 | Hours, 10 | Days 11 | } 12 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Models/Shards.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace InfluxDB.Net.Models 4 | { 5 | public class Shards 6 | { 7 | public List LongTerm { get; set; } 8 | public List ShortTerm { get; set; } 9 | } 10 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Models/Pong.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace InfluxDB.Net.Models 4 | { 5 | public class Pong 6 | { 7 | public bool Success{ get; set; } 8 | public string Version { get; set; } 9 | public TimeSpan ResponseTime { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Helpers/HttpUtility.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace InfluxDB.Net.Helpers 4 | { 5 | internal static class HttpUtility 6 | { 7 | public static string UrlEncode(string parameter) 8 | { 9 | return Uri.EscapeUriString(parameter); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Formatters/FormatterV092.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Infrastructure.Formatters 2 | { 3 | internal class FormatterV092 : FormatterBase 4 | { 5 | protected override string ToInt(string result) 6 | { 7 | return result; 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Contracts/IFormatter.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Models; 2 | 3 | namespace InfluxDB.Net.Contracts 4 | { 5 | public interface IFormatter 6 | { 7 | string GetLineTemplate(); 8 | 9 | string PointToString(Point point); 10 | 11 | Serie PointToSerie(Point point); 12 | } 13 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Enums/InfluxVersion.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Enums 2 | { 3 | public enum InfluxVersion 4 | { 5 | Auto, 6 | v1_1_x, 7 | v013x, 8 | v012x, 9 | v011x, 10 | v010x, 11 | v09x, 12 | v096, 13 | v095, 14 | v092, 15 | v08x, 16 | v0x 17 | } 18 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Models/QueryResult.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Models 2 | { 3 | public class QueryResult 4 | { 5 | public string Error { get; set; } 6 | public Result[] Results { get; set; } 7 | } 8 | 9 | public class Result 10 | { 11 | public string Error { get; set; } 12 | public Serie[] Series { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Models/ShardSpace.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Models 2 | { 3 | public class ShardSpace 4 | { 5 | public string Name { get; set; } 6 | public string Database { get; set; } 7 | public string RetentionPolicy { get; set; } 8 | public string ShardDuration { get; set; } 9 | public string Regex { get; set; } 10 | public int ReplicationFactor { get; set; } 11 | public int Split { get; set; } 12 | } 13 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Constants/QueryParams.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Constants 2 | { 3 | internal static class QueryParams 4 | { 5 | internal const string Username = "u"; 6 | internal const string Password = "p"; 7 | internal const string Db = "db"; 8 | internal const string Query = "q"; 9 | internal const string Id = "id"; 10 | internal const string Name = "name"; 11 | internal const string Precision = "precision"; 12 | } 13 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Models/Shard.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace InfluxDB.Net.Models 4 | { 5 | public class Shard 6 | { 7 | public int Id { get; set; } 8 | public long StartTime { get; set; } 9 | public long EndTime { get; set; } 10 | public bool LongTerm { get; set; } 11 | public List Shards { get; set; } 12 | 13 | public class Member 14 | { 15 | public List ServerIds { get; set; } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /InfluxDB.Net/Enums/LogLevel.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Enums 2 | { 3 | public enum LogLevel 4 | { 5 | /* No logging. */ 6 | None, 7 | /* Log only the request method and URL and the response status code and execution time. */ 8 | Basic, 9 | /* Log the basic information along with request and response headers. */ 10 | Headers, 11 | /* 12 | * Log the headers, body, and metadata for both requests and responses. 13 | * Note: This requires that the entire request and response body be buffered in memory! 14 | */ 15 | Full 16 | } 17 | } -------------------------------------------------------------------------------- /InfluxDB.Net/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /InfluxDB.Net/Models/Serie.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace InfluxDB.Net.Models 4 | { 5 | public class Serie 6 | { 7 | public Serie() 8 | { 9 | Tags = new Dictionary(); 10 | Columns = new string[] { }; 11 | Values = new object[][] { }; 12 | } 13 | 14 | private Serie(string name) 15 | { 16 | Name = name; 17 | } 18 | 19 | public string Name { get; set; } 20 | public Dictionary Tags { get; set; } 21 | public string[] Columns { get; set; } 22 | public object[][] Values { get; set; } 23 | } 24 | } -------------------------------------------------------------------------------- /InfluxDB.Net.Posh/AddInfluxDb.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation; 2 | using InfluxDB.Net.Contracts; 3 | using InfluxDB.Net.Helpers; 4 | 5 | namespace InfluxDB.Net.Posh 6 | { 7 | [Cmdlet(VerbsCommon.Add, "InfluxDb")] 8 | public class AddInfluxDb : Cmdlet 9 | { 10 | [Parameter(Mandatory = true)] 11 | public IInfluxDb Connection { get; set; } 12 | 13 | [Parameter(Mandatory = true)] 14 | public string Name { get; set; } 15 | 16 | protected override void ProcessRecord() 17 | { 18 | var response = Connection.CreateDatabaseAsync(Name).Result; 19 | WriteObject(response.ToJson()); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /InfluxDB.Net.Posh/OpenInfluxDb.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation; 2 | 3 | namespace InfluxDB.Net.Posh 4 | { 5 | [Cmdlet(VerbsCommon.Open, "InfluxDb")] 6 | public class OpenInfluxDb : Cmdlet 7 | { 8 | [Parameter(Mandatory = true)] 9 | public string Uri { get; set; } 10 | 11 | [Parameter(Mandatory = false)] 12 | public string User { get; set; } 13 | 14 | [Parameter(Mandatory = false)] 15 | public string Password { get; set; } 16 | 17 | protected override void ProcessRecord() 18 | { 19 | var response = new InfluxDb(Uri, User ?? "root", Password ?? "root"); 20 | WriteObject(response); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /InfluxDB.Net.Tests/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /InfluxDB.Net/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientV0x.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Contracts; 2 | using InfluxDB.Net.Enums; 3 | using InfluxDB.Net.Infrastructure.Configuration; 4 | using InfluxDB.Net.Infrastructure.Formatters; 5 | 6 | namespace InfluxDB.Net.Client 7 | { 8 | internal class InfluxDbClientV0x : InfluxDbClientBase 9 | { 10 | public InfluxDbClientV0x(InfluxDbClientConfiguration configuration) 11 | : base(configuration) 12 | { 13 | } 14 | 15 | public override IFormatter GetFormatter() 16 | { 17 | return new FormatterV0x(); 18 | } 19 | 20 | public override InfluxVersion GetVersion() 21 | { 22 | return InfluxVersion.v0x; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientV092.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Contracts; 2 | using InfluxDB.Net.Enums; 3 | using InfluxDB.Net.Infrastructure.Configuration; 4 | using InfluxDB.Net.Infrastructure.Formatters; 5 | 6 | namespace InfluxDB.Net.Client 7 | { 8 | internal class InfluxDbClientV092 : InfluxDbClientBase 9 | { 10 | public InfluxDbClientV092(InfluxDbClientConfiguration configuration) 11 | : base(configuration) 12 | { 13 | } 14 | 15 | public override IFormatter GetFormatter() 16 | { 17 | return new FormatterV092(); 18 | } 19 | 20 | public override InfluxVersion GetVersion() 21 | { 22 | return InfluxVersion.v092; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientV095.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Contracts; 2 | using InfluxDB.Net.Enums; 3 | using InfluxDB.Net.Infrastructure.Configuration; 4 | using InfluxDB.Net.Infrastructure.Formatters; 5 | 6 | namespace InfluxDB.Net.Client 7 | { 8 | internal class InfluxDbClientV095 : InfluxDbClientBase 9 | { 10 | public InfluxDbClientV095(InfluxDbClientConfiguration configuration) 11 | : base(configuration) 12 | { 13 | } 14 | 15 | public override IFormatter GetFormatter() 16 | { 17 | return new FormatterV095(); 18 | } 19 | 20 | public override InfluxVersion GetVersion() 21 | { 22 | return InfluxVersion.v095; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientV096.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Contracts; 2 | using InfluxDB.Net.Enums; 3 | using InfluxDB.Net.Infrastructure.Configuration; 4 | using InfluxDB.Net.Infrastructure.Formatters; 5 | 6 | namespace InfluxDB.Net.Client 7 | { 8 | internal class InfluxDbClientV096 : InfluxDbClientBase 9 | { 10 | public InfluxDbClientV096(InfluxDbClientConfiguration configuration) 11 | : base(configuration) 12 | { 13 | } 14 | 15 | public override IFormatter GetFormatter() 16 | { 17 | return new FormatterV096(); 18 | } 19 | 20 | public override InfluxVersion GetVersion() 21 | { 22 | return InfluxVersion.v096; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientV010x.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Contracts; 2 | using InfluxDB.Net.Enums; 3 | using InfluxDB.Net.Infrastructure.Configuration; 4 | using InfluxDB.Net.Infrastructure.Formatters; 5 | 6 | namespace InfluxDB.Net.Client 7 | { 8 | internal class InfluxDbClientV010x : InfluxDbClientBase 9 | { 10 | public InfluxDbClientV010x(InfluxDbClientConfiguration configuration) 11 | : base(configuration) 12 | { 13 | } 14 | 15 | public override IFormatter GetFormatter() 16 | { 17 | return new FormatterV010x(); 18 | } 19 | 20 | public override InfluxVersion GetVersion() 21 | { 22 | return InfluxVersion.v010x; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientV011x.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Contracts; 2 | using InfluxDB.Net.Enums; 3 | using InfluxDB.Net.Infrastructure.Configuration; 4 | using InfluxDB.Net.Infrastructure.Formatters; 5 | 6 | namespace InfluxDB.Net.Client 7 | { 8 | internal class InfluxDbClientV011x : InfluxDbClientBase 9 | { 10 | public InfluxDbClientV011x(InfluxDbClientConfiguration configuration) 11 | : base(configuration) 12 | { 13 | } 14 | 15 | public override IFormatter GetFormatter() 16 | { 17 | return new FormatterV011x(); 18 | } 19 | 20 | public override InfluxVersion GetVersion() 21 | { 22 | return InfluxVersion.v011x; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientV012x.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Contracts; 2 | using InfluxDB.Net.Enums; 3 | using InfluxDB.Net.Infrastructure.Configuration; 4 | using InfluxDB.Net.Infrastructure.Formatters; 5 | 6 | namespace InfluxDB.Net.Client 7 | { 8 | internal class InfluxDbClientV012x : InfluxDbClientBase 9 | { 10 | public InfluxDbClientV012x(InfluxDbClientConfiguration configuration) 11 | : base(configuration) 12 | { 13 | } 14 | 15 | public override IFormatter GetFormatter() 16 | { 17 | return new FormatterV012x(); 18 | } 19 | 20 | public override InfluxVersion GetVersion() 21 | { 22 | return InfluxVersion.v012x; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientV013x.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Contracts; 2 | using InfluxDB.Net.Enums; 3 | using InfluxDB.Net.Infrastructure.Configuration; 4 | using InfluxDB.Net.Infrastructure.Formatters; 5 | 6 | namespace InfluxDB.Net.Client 7 | { 8 | internal class InfluxDbClientV013x : InfluxDbClientBase 9 | { 10 | public InfluxDbClientV013x(InfluxDbClientConfiguration configuration) 11 | : base(configuration) 12 | { 13 | } 14 | 15 | public override IFormatter GetFormatter() 16 | { 17 | return new FormatterV013x(); 18 | } 19 | 20 | public override InfluxVersion GetVersion() 21 | { 22 | return InfluxVersion.v013x; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientV1_1_x.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Contracts; 2 | using InfluxDB.Net.Enums; 3 | using InfluxDB.Net.Infrastructure.Configuration; 4 | using InfluxDB.Net.Infrastructure.Formatters; 5 | 6 | namespace InfluxDB.Net.Client 7 | { 8 | internal class InfluxDbClientV1_1_x : InfluxDbClientBase 9 | { 10 | public InfluxDbClientV1_1_x(InfluxDbClientConfiguration configuration) 11 | : base(configuration) 12 | { 13 | } 14 | 15 | public override IFormatter GetFormatter() 16 | { 17 | return new FormatterV1_1_x(); 18 | } 19 | 20 | public override InfluxVersion GetVersion() 21 | { 22 | return InfluxVersion.v1_1_x; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /InfluxDB.Net.Posh/WriteInfluxDb.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation; 2 | using InfluxDB.Net.Contracts; 3 | using InfluxDB.Net.Helpers; 4 | using InfluxDB.Net.Models; 5 | 6 | namespace InfluxDB.Net.Posh 7 | { 8 | [Cmdlet(VerbsCommunications.Write, "InfluxDb")] 9 | public class WriteInfluxDb : Cmdlet 10 | { 11 | [Parameter(Mandatory = true)] 12 | public IInfluxDb Connection { get; set; } 13 | 14 | [Parameter(Mandatory = true)] 15 | public string Name { get; set; } 16 | 17 | [Parameter(Mandatory = true)] 18 | public string Data { get; set; } 19 | 20 | protected override void ProcessRecord() 21 | { 22 | var point = Data.FromJson(); 23 | var response = Connection.WriteAsync(Name, point).Result; 24 | WriteObject(response.ToJson()); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | machine: 2 | environment: 3 | USE_SYSTEM_NUNIT_CONSOLE: 0 4 | 5 | dependencies: 6 | pre: 7 | - sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF 8 | - echo "deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/sources.list.d/mono-xamarin.list 9 | - sudo apt-get update 10 | - sudo aptitude install -yq mono-devel 11 | - sudo aptitude install -yq mono-complete 12 | - sudo aptitude install -yq referenceassemblies-pcl 13 | - mozroots --import --sync 14 | - mono .nuget/NuGet.exe restore InfluxDB.Net.sln 15 | - sudo chmod +x build.sh 16 | - wget https://s3.amazonaws.com/influxdb/influxdb_0.9.2_amd64.deb 17 | - sudo dpkg -i influxdb_0.9.2_amd64.deb 18 | - sudo service influxdb start 19 | 20 | test: 21 | override: 22 | - ./build.sh 23 | -------------------------------------------------------------------------------- /InfluxDB.Net/Models/WriteRequest.cs: -------------------------------------------------------------------------------- 1 | using InfluxDB.Net.Contracts; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.Linq; 6 | 7 | namespace InfluxDB.Net.Models 8 | { 9 | /// 10 | /// Represents an API write request 11 | /// 12 | public class WriteRequest 13 | { 14 | private readonly IFormatter _formatter; 15 | 16 | public WriteRequest(IFormatter formatter) 17 | { 18 | _formatter = formatter; 19 | } 20 | 21 | public string Database { get; set; } 22 | public string RetentionPolicy { get; set; } 23 | public Point[] Points { get; set; } 24 | 25 | /// Gets the set of points in line protocol format. 26 | /// 27 | public string GetLines() 28 | { 29 | return String.Join("\n", Points.Select(p => _formatter.PointToString(p))); 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /InfluxDB.Net/Models/User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace InfluxDB.Net.Models 4 | { 5 | public class User 6 | { 7 | public string Name { get; set; } 8 | public string Password { get; set; } 9 | public bool IsAdmin { get; set; } 10 | public string ReadFrom { get; set; } 11 | public string WriteTo { get; set; } 12 | 13 | public void SetPermissions(params string[] permissions) 14 | { 15 | if (null != permissions) 16 | { 17 | switch (permissions.Length) 18 | { 19 | case 0: 20 | break; 21 | case 2: 22 | ReadFrom = permissions[0]; 23 | WriteTo = permissions[1]; 24 | break; 25 | default: 26 | throw new ArgumentException("You have to specify readFrom and writeTo permissions."); 27 | } 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Influx/InfluxDbException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | 4 | namespace InfluxDB.Net.Infrastructure.Influx 5 | { 6 | public class InfluxDbException : Exception 7 | { 8 | public InfluxDbException(string message, Exception innerException) 9 | : base(message, innerException) 10 | { 11 | } 12 | 13 | public InfluxDbException(string message) 14 | : base(message) 15 | { 16 | } 17 | } 18 | 19 | public class InfluxDbApiException : InfluxDbException 20 | { 21 | public InfluxDbApiException(HttpStatusCode statusCode, string responseBody) 22 | : base(String.Format("InfluxDb API responded with status code={0}, response={1}", statusCode, responseBody)) 23 | { 24 | StatusCode = statusCode; 25 | ResponseBody = responseBody; 26 | } 27 | 28 | public HttpStatusCode StatusCode { get; private set; } 29 | 30 | public string ResponseBody { get; private set; } 31 | } 32 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Resources; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | 8 | [assembly: AssemblyTitle("InfluxDB.Net")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("InfluxDB.Net")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | [assembly: NeutralResourcesLanguage("en")] 17 | 18 | // Version information for an assembly consists of the following four values: 19 | // 20 | // Major Version 21 | // Minor Version 22 | // Build Number 23 | // Revision 24 | // 25 | // You can specify all the values or you can default the Build and Revision Numbers 26 | // by using the '*' as shown below: 27 | // [assembly: AssemblyVersion("1.0.*")] 28 | 29 | [assembly: AssemblyVersion("1.0.0.0")] 30 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Ziya SARIKAYA 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /InfluxDB.Net/Models/Point.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using InfluxDB.Net.Enums; 4 | 5 | namespace InfluxDB.Net.Models 6 | { 7 | /// 8 | /// A class representing a time series point for db writes 9 | /// 10 | /// 11 | public class Point 12 | { 13 | /// 14 | /// Serie name. Measurement is Influxes convention for Serie name. 15 | /// 16 | /// 17 | public string Measurement { get; set; } 18 | public Dictionary Tags { get; set; } // string, string? 19 | public Dictionary Fields { get; set; } 20 | public TimeUnit Precision { get; set; } 21 | public DateTime? Timestamp { get; set; } 22 | 23 | public Point() 24 | { 25 | Tags = new Dictionary(); 26 | Fields = new Dictionary(); 27 | Precision = TimeUnit.Milliseconds; 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /InfluxDB.Net/InfluxDB.Net.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | InfluxDB.Net-Main 5 | 1.0.0 6 | InfluxDB.Net Main 7 | Ziya SARIKAYA, Daniel Bohlin 8 | ziyasal, poxet 9 | https://github.com/ziyasal/InfluxDB.Net/blob/master/LICENSE 10 | https://github.com/ziyasal/InfluxDB.Net 11 | false 12 | 13 | Portable .NET client for InfluxDB. 14 | It is fully asynchronous and non-blocking way to interact with InfluxDB programmatically. 15 | 16 | Portable .NET client for InfluxDB. 17 | 18 | Added explicit support for version 1.1.x. 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /InfluxDB.Net.Posh/PingInfluxDb.cs: -------------------------------------------------------------------------------- 1 | using System.Management.Automation; 2 | using InfluxDB.Net.Contracts; 3 | using InfluxDB.Net.Helpers; 4 | using InfluxDB.Net.Models; 5 | 6 | namespace InfluxDB.Net.Posh 7 | { 8 | [Cmdlet(VerbsDiagnostic.Ping, "InfluxDb")] 9 | public class PingInfluxDb : Cmdlet 10 | { 11 | [Parameter(Mandatory = false)] 12 | public IInfluxDb Connection { get; set; } 13 | 14 | [Parameter(Mandatory = false)] 15 | public string Uri { get; set; } 16 | 17 | [Parameter(Mandatory = false)] 18 | public string User { get; set; } 19 | 20 | [Parameter(Mandatory = false)] 21 | public string Password { get; set; } 22 | 23 | protected override void ProcessRecord() 24 | { 25 | Pong response; 26 | 27 | if (Connection != null) 28 | { 29 | response = Connection.PingAsync().Result; 30 | } 31 | else if (Uri != null) 32 | { 33 | var db = new InfluxDb(Uri, User ?? "root", Password ?? "root"); 34 | response = db.PingAsync().Result; 35 | } 36 | else 37 | { 38 | throw new InvalidJobStateException("Parameter Connection or Uri has to be provided."); 39 | } 40 | 41 | WriteObject(response.ToJson()); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Configuration/DatabaseConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using InfluxDB.Net.Models; 4 | 5 | namespace InfluxDB.Net.Infrastructure.Configuration 6 | { 7 | public class DatabaseConfiguration 8 | { 9 | private readonly List _continuousQueries; 10 | 11 | private readonly List _spaces; 12 | 13 | public DatabaseConfiguration() 14 | { 15 | _spaces = new List(); 16 | _continuousQueries = new List(); 17 | } 18 | 19 | public string Name { get; set; } 20 | 21 | public List ContinuousQueries 22 | { 23 | get { return _continuousQueries; } 24 | } 25 | 26 | public List ShardSpaces 27 | { 28 | get { return _spaces; } 29 | } 30 | 31 | public List GetSpaces() 32 | { 33 | return _spaces; 34 | } 35 | 36 | public void AddSpace(ShardSpace space) 37 | { 38 | _spaces.Add(space); 39 | } 40 | 41 | public List GetContinuousQueries() 42 | { 43 | return _continuousQueries; 44 | } 45 | 46 | public void AddContinuousQueries(String continuousQuery) 47 | { 48 | _continuousQueries.Add(continuousQuery); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Influx/InfluxDbResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | 3 | namespace InfluxDB.Net.Infrastructure.Influx 4 | { 5 | public class InfluxDbApiResponse 6 | { 7 | public InfluxDbApiResponse(HttpStatusCode statusCode, string body) 8 | { 9 | StatusCode = statusCode; 10 | Body = body; 11 | } 12 | 13 | public HttpStatusCode StatusCode { get; private set; } 14 | 15 | public string Body { get; private set; } 16 | 17 | public virtual bool Success 18 | { 19 | get { return StatusCode == HttpStatusCode.OK; } 20 | } 21 | } 22 | 23 | public class InfluxDbApiWriteResponse : InfluxDbApiResponse 24 | { 25 | public InfluxDbApiWriteResponse(HttpStatusCode statusCode, string body) 26 | : base(statusCode, body) 27 | { 28 | } 29 | 30 | public override bool Success 31 | { 32 | get { return StatusCode == HttpStatusCode.NoContent; } 33 | } 34 | } 35 | 36 | public class InfluxDbApiDeleteResponse : InfluxDbApiResponse 37 | { 38 | public InfluxDbApiDeleteResponse(HttpStatusCode statusCode, string body) 39 | : base(statusCode, body) 40 | { 41 | } 42 | 43 | public override bool Success 44 | { 45 | //TODO: Ask to influx db creators 46 | get { return StatusCode == HttpStatusCode.NoContent; } 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /InfluxDB.Net.Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | 8 | [assembly: AssemblyTitle("InfluxDB.Net.Tests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("InfluxDB.Net.Tests")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | 21 | [assembly: ComVisible(false)] 22 | 23 | // The following GUID is for the ID of the typelib if this project is exposed to COM 24 | 25 | [assembly: Guid("1bfea085-dd35-4897-9872-c398a51d54be")] 26 | 27 | // Version information for an assembly consists of the following four values: 28 | // 29 | // Major Version 30 | // Minor Version 31 | // Build Number 32 | // Revision 33 | // 34 | // You can specify all the values or you can default the Build and Revision Numbers 35 | // by using the '*' as shown below: 36 | // [assembly: AssemblyVersion("1.0.*")] 37 | 38 | [assembly: AssemblyVersion("1.0.0.0")] 39 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /InfluxDB.Net.Posh/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("InfluxDB.Net.Posh")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("InfluxDB.Net.Posh")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("26a19974-ea03-4dbc-9b5a-ae76ad365a40")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /InfluxDB.Net.Tests/app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Validation/Validate.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace InfluxDB.Net.Infrastructure.Validation 5 | { 6 | internal static class Validate 7 | { 8 | public static void NotNull(T value, string paramName) where T : class 9 | { 10 | if (value == null) 11 | throw new ArgumentNullException(paramName); 12 | } 13 | 14 | public static void NotNull(T value, string paramName, string message) where T : class 15 | { 16 | if (value == null) 17 | throw new ArgumentNullException(paramName, message); 18 | } 19 | 20 | public static void IfTrue(bool value, string message) 21 | { 22 | if (value) 23 | throw new ArgumentException(message); 24 | } 25 | 26 | public static void NotNullOrEmpty(string value, string paramName) 27 | { 28 | if (String.IsNullOrEmpty(value)) 29 | throw new ArgumentException(paramName); 30 | } 31 | 32 | public static void NotZeroLength(T[] array, string paramName) 33 | { 34 | if (array.Length == 0) 35 | throw new ArgumentOutOfRangeException(paramName); 36 | } 37 | 38 | public static void NotZeroLength(T[] array, string paramName, string message) 39 | { 40 | if (array.Length == 0) 41 | throw new ArgumentOutOfRangeException(paramName, message); 42 | } 43 | 44 | public static void NotZeroLength(List list, string paramName) 45 | { 46 | if (list.Count == 0) 47 | throw new ArgumentOutOfRangeException(paramName); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /InfluxDB.Net.Posh/TestModule/TestInfluxDb.ps1: -------------------------------------------------------------------------------- 1 | #*************************************************************************************************************** 2 | #** TestInfluxDb.ps1 3 | #*************************************************************************************************************** 4 | #** 5 | #*************************************************************************************************************** 6 | 7 | param ( 8 | [switch]$copyFiles = $true 9 | ) 10 | 11 | $host.ui.rawui.WindowTitle = "Test InfluxDb" 12 | 13 | if($copyFiles) 14 | { 15 | $srcPath = "..\bin\Debug\*" 16 | $dstPath = ".\Modules\InfluxDb" 17 | new-Item -Path ".\Modules" -ItemType:Directory -Force 18 | new-Item -Path ".\Modules\InfluxDb" -ItemType:Directory -Force 19 | write-host "Copy '$srcPath' to '$dstPath'" -f Yellow 20 | #Try 21 | #{ 22 | copy-item $srcPath $dstPath -container -recurse -force -erroraction:Stop 23 | #} 24 | #Catch 25 | #{ 26 | # write-host "Oups!" -f Red 27 | # write.host $_.Exception 28 | #} 29 | } 30 | 31 | import-module .\modules\InfluxDb -force 32 | get-command -module:InfluxDb | select Name | ft 33 | 34 | #Create a database connection 35 | $db = Open-InfluxDb -Uri:"http://...:8086" -User:"root" -Password:"root" 36 | 37 | #Ping the connection 38 | $pong = Ping-InfluxDb -Connection:$db 39 | $pong 40 | 41 | #Create a new database 42 | Add-InfluxDb -Connection:$db -Name:"TheTest" 43 | 44 | #Write measurement data to the database 45 | Write-InfluxDb -Connection:$db -Name:"TheTest" -Data:"{'Measurement':'SomeData','Tags':{'Tag1':'A','Tag2':'B'},'Fields':{'Val1':12,'Val2':1.2},'Precision':1,'Timestamp':null}" 46 | 47 | remove-module InfluxDb 48 | 49 | #*************************************************************************************************************** 50 | 51 | pause -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Configuration/InfluxDbClientConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | using InfluxDB.Net.Infrastructure.Validation; 4 | using InfluxDB.Net.Enums; 5 | 6 | namespace InfluxDB.Net.Infrastructure.Configuration 7 | { 8 | public class InfluxDbClientConfiguration 9 | { 10 | public Uri EndpointBaseUri { get; internal set; } 11 | 12 | public string Username { get; private set; } 13 | 14 | public string Password { get; private set; } 15 | 16 | public InfluxVersion InfluxVersion { get; private set; } 17 | 18 | public TimeSpan? RequestTimeout { get; private set; } 19 | 20 | public InfluxDbClientConfiguration(Uri endpoint, string username, string password, InfluxVersion influxVersion, TimeSpan? requestTimeout) 21 | { 22 | Validate.NotNull(endpoint, "Endpoint may not be null or empty."); 23 | Validate.NotNullOrEmpty(password, "Password may not be null or empty."); 24 | Validate.NotNullOrEmpty(username, "Username may not be null or empty."); 25 | Username = username; 26 | Password = password; 27 | InfluxVersion = influxVersion; 28 | EndpointBaseUri = SanitizeEndpoint(endpoint, false); 29 | RequestTimeout = requestTimeout; 30 | } 31 | 32 | private static Uri SanitizeEndpoint(Uri endpoint, bool isTls) 33 | { 34 | var builder = new UriBuilder(endpoint); 35 | 36 | if (isTls) 37 | { 38 | builder.Scheme = "https"; 39 | } 40 | else if (builder.Scheme.Equals("tcp", StringComparison.CurrentCultureIgnoreCase)) 41 | //InvariantCultureIgnoreCase, not supported in PCL 42 | { 43 | builder.Scheme = "http"; 44 | } 45 | 46 | return builder.Uri; 47 | } 48 | 49 | public HttpClient BuildHttpClient() 50 | { 51 | return new HttpClient(); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Constants/QueryStatements.cs: -------------------------------------------------------------------------------- 1 | namespace InfluxDB.Net.Constants 2 | { 3 | internal static class QueryStatements 4 | { 5 | internal const string AlterRetentionPolicy = "alter retention policy {0} on {1} {2} {3} {4} {5}"; 6 | internal const string CreateContinuousQuery = "create continuous query {0} on {1} begin {2} end;"; 7 | internal const string CreateDatabase = "create database \"{0}\""; 8 | internal const string CreateRetentionPolicy = "create retention policy \"{0}\" on {1} {2} {3} {4} {5}"; 9 | internal const string CreateUser = "create user {0} with password {1} {2}"; 10 | internal const string DropContinuousQuery = "drop continuous query {0}"; 11 | internal const string DropDatabase = "drop database \"{0}\""; 12 | internal const string DropMeasurement = "drop measurement \"{0}\""; 13 | internal const string DropRetentionPolicy = "drop retention policy \"{0}\" on {1}"; 14 | internal const string DropSeries = "drop series from \"{0}\""; 15 | internal const string DropUser = "drop user {0}"; 16 | internal const string Grant = "grant {0} on {1} to {2}"; 17 | internal const string GrantAll = "grant all to {0}"; 18 | internal const string Revoke = "revoke {0} on {1} from {2}"; 19 | internal const string RevokeAll = "revoke all privleges from {0}"; 20 | internal const string ShowContinuousQueries = "show continuous queries"; 21 | internal const string ShowDatabases = "show databases"; 22 | internal const string ShowFieldKeys = "show field keys {0} {1}"; 23 | internal const string ShowMeasurements = "show measurements"; 24 | internal const string ShowRetentionPolicies = "show retention policies {0}"; 25 | internal const string ShowSeries = "show series"; 26 | internal const string ShowTagKeys = "show tag keys"; 27 | internal const string ShowTagValues = "show tag values"; 28 | internal const string ShowUsers = "show users"; 29 | } 30 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Build Folders (you can keep bin if you'd like, to store dlls and pdbs) 2 | [Bb]in/ 3 | [Oo]bj/ 4 | [Aa]pp_Data/ 5 | # Nuget Packages folder 6 | [Pp]ackages/ 7 | # BuildArtifacts folder 8 | [Bb]uildArtifacts/ 9 | *.nupkg 10 | 11 | # mstest test results 12 | TestResults 13 | 14 | ## Ignore Visual Studio temporary files, build results, and 15 | ## files generated by popular Visual Studio add-ons. 16 | 17 | # User-specific files 18 | *.suo 19 | *.user 20 | *.sln.docstates 21 | *.vs 22 | 23 | # Build results 24 | [Dd]ebug/ 25 | [Rr]elease/ 26 | [Bb]uild/ 27 | x64/ 28 | *_i.c 29 | *_p.c 30 | *.ilk 31 | *.meta 32 | *.obj 33 | *.pch 34 | *.pdb 35 | *.pgc 36 | *.pgd 37 | *.rsp 38 | *.sbr 39 | *.tlb 40 | *.tli 41 | *.tlh 42 | *.tmp 43 | *.vspscc 44 | *.vssscc 45 | .builds 46 | 47 | # Visual C++ cache files 48 | ipch/ 49 | *.aps 50 | *.ncb 51 | *.opensdf 52 | *.sdf 53 | 54 | # Visual Studio profiler 55 | *.psess 56 | *.vsp 57 | 58 | # Guidance Automation Toolkit 59 | *.gpState 60 | 61 | # ReSharper is a .NET coding add-in 62 | _ReSharper* 63 | 64 | # NCrunch 65 | *.ncrunch* 66 | .*crunch*.local.xml 67 | 68 | # Installshield output folder 69 | [Ee]xpress 70 | 71 | # DocProject is a documentation generator add-in 72 | DocProject/buildhelp/ 73 | DocProject/Help/*.HxT 74 | DocProject/Help/*.HxC 75 | DocProject/Help/*.hhc 76 | DocProject/Help/*.hhk 77 | DocProject/Help/*.hhp 78 | DocProject/Help/Html2 79 | DocProject/Help/html 80 | 81 | # Click-Once directory 82 | publish 83 | 84 | # Publish Web Output 85 | *.Publish.xml 86 | 87 | # Others 88 | [Bb]in 89 | [Oo]bj 90 | sql 91 | TestResults 92 | [Tt]est[Rr]esult* 93 | *.Cache 94 | ClientBin 95 | [Ss]tyle[Cc]op.* 96 | ~$* 97 | *.dbmdl 98 | Generated_Code #added for RIA/Silverlight projects 99 | 100 | # Backup & report files from converting an old project file to a newer 101 | # Visual Studio version. Backup files are not needed, because we have git ;-) 102 | _UpgradeReport_Files/ 103 | Backup*/ 104 | UpgradeLog*.XML 105 | _NCrunch*/ 106 | 107 | */TestModule/Modules/* 108 | 109 | *.orig -------------------------------------------------------------------------------- /InfluxDB.Net/Helpers/ObjectExtensions.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Text; 4 | using InfluxDB.Net.Infrastructure.Influx; 5 | 6 | namespace InfluxDB.Net.Helpers 7 | { 8 | public static class ObjectExtensions 9 | { 10 | private static DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); 11 | 12 | public static string ToJson(this object @object) 13 | { 14 | return JsonConvert.SerializeObject(@object); 15 | } 16 | 17 | public static T FromJson(this string item) 18 | { 19 | var response = JsonConvert.DeserializeObject(item); 20 | return response; 21 | } 22 | 23 | public static T ReadAs(this InfluxDbApiResponse response) 24 | { 25 | var @object = JsonConvert.DeserializeObject(response.Body); 26 | 27 | return @object; 28 | } 29 | 30 | /// Converts to unix time in milliseconds. 31 | /// The date. 32 | /// The number of elapsed milliseconds 33 | public static long ToUnixTime(this DateTime date) 34 | { 35 | return Convert.ToInt64((date - _epoch).TotalMilliseconds); 36 | } 37 | 38 | /// Converts from unix time in milliseconds. 39 | /// The unix time in millis. 40 | /// 41 | public static DateTime FromUnixTime(this long unixTimeInMillis) 42 | { 43 | return _epoch.AddMilliseconds(unixTimeInMillis); 44 | } 45 | 46 | public static string NextPrintableString(this Random random, int length) 47 | { 48 | var data = new byte[length]; 49 | 50 | for (int i = 0; i < data.Length; i++) 51 | { 52 | // Only printable UTF-8 53 | // and no backslashes for now 54 | // https://github.com/influxdb/influxdb/issues/3070 55 | do 56 | { 57 | data[i] = (byte)random.Next(32, 127); 58 | } 59 | while (data[i] == 92); 60 | } 61 | 62 | var encoding = new UTF8Encoding(); 63 | return encoding.GetString(data, 0, length); 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /InfluxDB.Net.Tests/TestBase.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Moq; 3 | using NUnit.Framework; 4 | using Ploeh.AutoFixture; 5 | 6 | namespace InfluxDB.Net.Tests 7 | { 8 | // NOTE: http://stackoverflow.com/questions/106907/making-code-internal-but-available-for-unit-testing-from-other-projects 9 | 10 | [TestFixture] 11 | public class TestBase 12 | { 13 | [SetUp] 14 | public async Task Setup() 15 | { 16 | _mockRepository = new MockRepository(MockBehavior.Strict); 17 | FixtureRepository = new Fixture(); 18 | VerifyAll = true; 19 | 20 | await FinalizeSetUp(); 21 | } 22 | 23 | [TearDown] 24 | public async Task TearDown() 25 | { 26 | if (VerifyAll) 27 | { 28 | _mockRepository.VerifyAll(); 29 | } 30 | else 31 | { 32 | _mockRepository.Verify(); 33 | } 34 | 35 | await FinalizeTearDown(); 36 | } 37 | 38 | [TestFixtureSetUp] 39 | public async Task TestFixtureSetUp() 40 | { 41 | await FinalizeTestFixtureSetUp(); 42 | } 43 | 44 | [TestFixtureTearDown] 45 | public async Task TestFixtureTearDown() 46 | { 47 | await FinalizeTestFixtureTearDown(); 48 | } 49 | 50 | private MockRepository _mockRepository; 51 | protected IFixture FixtureRepository { get; set; } 52 | protected bool VerifyAll { get; set; } 53 | 54 | protected Mock MockFor() where T : class 55 | { 56 | return _mockRepository.Create(); 57 | } 58 | 59 | protected Mock MockFor(params object[] @params) where T : class 60 | { 61 | return _mockRepository.Create(@params); 62 | } 63 | 64 | protected void EnableCustomization(ICustomization customization) 65 | { 66 | customization.Customize(FixtureRepository); 67 | } 68 | 69 | protected virtual async Task FinalizeTearDown() 70 | { 71 | } 72 | 73 | protected virtual async Task FinalizeTestFixtureTearDown() 74 | { 75 | } 76 | 77 | protected virtual async Task FinalizeSetUp() 78 | { 79 | } 80 | 81 | protected virtual async Task FinalizeTestFixtureSetUp() 82 | { 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /InfluxDB.Net.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{91B2CB56-7AB0-4AF1-A081-95525F8A754C}" 7 | ProjectSection(SolutionItems) = preProject 8 | .nuget\NuGet.Config = .nuget\NuGet.Config 9 | .nuget\NuGet.exe = .nuget\NuGet.exe 10 | .nuget\NuGet.targets = .nuget\NuGet.targets 11 | EndProjectSection 12 | EndProject 13 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InfluxDB.Net", "InfluxDB.Net\InfluxDB.Net.csproj", "{9092CDD0-1585-48DE-B619-98F6FF01F8CC}" 14 | EndProject 15 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9B34D123-58D5-4291-8651-9231C8875A86}" 16 | ProjectSection(SolutionItems) = preProject 17 | build.sh = build.sh 18 | circle.yml = circle.yml 19 | InfluxDB.Net\InfluxDB.Net.nuspec = InfluxDB.Net\InfluxDB.Net.nuspec 20 | LICENSE = LICENSE 21 | README.md = README.md 22 | EndProjectSection 23 | EndProject 24 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InfluxDB.Net.Tests", "InfluxDB.Net.Tests\InfluxDB.Net.Tests.csproj", "{56B4EF11-8B2A-4862-8723-FC4368274768}" 25 | EndProject 26 | Global 27 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 28 | Debug|Any CPU = Debug|Any CPU 29 | Release|Any CPU = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 32 | {9092CDD0-1585-48DE-B619-98F6FF01F8CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {9092CDD0-1585-48DE-B619-98F6FF01F8CC}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {9092CDD0-1585-48DE-B619-98F6FF01F8CC}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {9092CDD0-1585-48DE-B619-98F6FF01F8CC}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {56B4EF11-8B2A-4862-8723-FC4368274768}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {56B4EF11-8B2A-4862-8723-FC4368274768}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {56B4EF11-8B2A-4862-8723-FC4368274768}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {56B4EF11-8B2A-4862-8723-FC4368274768}.Release|Any CPU.Build.0 = Release|Any CPU 40 | EndGlobalSection 41 | GlobalSection(SolutionProperties) = preSolution 42 | HideSolutionNode = FALSE 43 | EndGlobalSection 44 | GlobalSection(CodealikeProperties) = postSolution 45 | SolutionGuid = 8c17e567-62f8-4eb6-bc82-a3715bfa171d 46 | EndGlobalSection 47 | EndGlobal 48 | -------------------------------------------------------------------------------- /InfluxDB.Net.Posh.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25123.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InfluxDB.Net.Tests", "InfluxDB.Net.Tests\InfluxDB.Net.Tests.csproj", "{56B4EF11-8B2A-4862-8723-FC4368274768}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{91B2CB56-7AB0-4AF1-A081-95525F8A754C}" 9 | ProjectSection(SolutionItems) = preProject 10 | .nuget\NuGet.Config = .nuget\NuGet.Config 11 | .nuget\NuGet.exe = .nuget\NuGet.exe 12 | .nuget\NuGet.targets = .nuget\NuGet.targets 13 | EndProjectSection 14 | EndProject 15 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InfluxDB.Net", "InfluxDB.Net\InfluxDB.Net.csproj", "{9092CDD0-1585-48DE-B619-98F6FF01F8CC}" 16 | EndProject 17 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InfluxDB.Net.Posh", "InfluxDB.Net.Posh\InfluxDB.Net.Posh.csproj", "{69792FFC-154A-4C91-99E6-CFCFAAFDBBA4}" 18 | EndProject 19 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{32A0B9CC-0620-4686-A9D4-2793948FC4F5}" 20 | ProjectSection(SolutionItems) = preProject 21 | README.md = README.md 22 | EndProjectSection 23 | EndProject 24 | Global 25 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 26 | Debug|Any CPU = Debug|Any CPU 27 | Release|Any CPU = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 30 | {56B4EF11-8B2A-4862-8723-FC4368274768}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {56B4EF11-8B2A-4862-8723-FC4368274768}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {56B4EF11-8B2A-4862-8723-FC4368274768}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {56B4EF11-8B2A-4862-8723-FC4368274768}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {9092CDD0-1585-48DE-B619-98F6FF01F8CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {9092CDD0-1585-48DE-B619-98F6FF01F8CC}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {9092CDD0-1585-48DE-B619-98F6FF01F8CC}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {9092CDD0-1585-48DE-B619-98F6FF01F8CC}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {69792FFC-154A-4C91-99E6-CFCFAAFDBBA4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {69792FFC-154A-4C91-99E6-CFCFAAFDBBA4}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {69792FFC-154A-4C91-99E6-CFCFAAFDBBA4}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {69792FFC-154A-4C91-99E6-CFCFAAFDBBA4}.Release|Any CPU.Build.0 = Release|Any CPU 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | EndGlobal 47 | -------------------------------------------------------------------------------- /InfluxDB.Net/Helpers/Stopwatch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace InfluxDB.Net.Helpers 4 | { 5 | public sealed class Stopwatch 6 | { 7 | private long _elapsed; 8 | private bool _isRunning; 9 | private long _startTick; 10 | 11 | /// 12 | /// Gets a value indicating whether the instance is currently recording. 13 | /// 14 | public bool IsRunning 15 | { 16 | get { return _isRunning; } 17 | } 18 | 19 | /// 20 | /// Gets the Elapsed time as a Timespan. 21 | /// 22 | public TimeSpan Elapsed 23 | { 24 | get { return TimeSpan.FromMilliseconds(ElapsedMilliseconds); } 25 | } 26 | 27 | /// 28 | /// Gets the Elapsed time as the total number of milliseconds. 29 | /// 30 | public long ElapsedMilliseconds 31 | { 32 | get { return GetCurrentElapsedTicks() / TimeSpan.TicksPerMillisecond; } 33 | } 34 | 35 | /// 36 | /// Gets the Elapsed time as the total number of ticks (which is faked 37 | /// as Silverlight doesn't have a way to get at the actual "Ticks") 38 | /// 39 | public long ElapsedTicks 40 | { 41 | get { return GetCurrentElapsedTicks(); } 42 | } 43 | 44 | /// 45 | /// Creates a new instance of the class and starts the watch immediately. 46 | /// 47 | /// An instance of Stopwatch, running. 48 | public static Stopwatch StartNew() 49 | { 50 | var sw = new Stopwatch(); 51 | sw.Start(); 52 | return sw; 53 | } 54 | 55 | /// 56 | /// Completely resets and deactivates the timer. 57 | /// 58 | public void Reset() 59 | { 60 | _elapsed = 0; 61 | _isRunning = false; 62 | _startTick = 0; 63 | } 64 | 65 | /// 66 | /// Begins the timer. 67 | /// 68 | public void Start() 69 | { 70 | if (!_isRunning) 71 | { 72 | _startTick = GetCurrentTicks(); 73 | _isRunning = true; 74 | } 75 | } 76 | 77 | /// 78 | /// Stops the current timer. 79 | /// 80 | public void Stop() 81 | { 82 | if (_isRunning) 83 | { 84 | _elapsed += GetCurrentTicks() - _startTick; 85 | _isRunning = false; 86 | } 87 | } 88 | 89 | private long GetCurrentElapsedTicks() 90 | { 91 | return _elapsed + (IsRunning ? (GetCurrentTicks() - _startTick) : 0); 92 | } 93 | 94 | private long GetCurrentTicks() 95 | { 96 | // TickCount: Gets the number of milliseconds elapsed since the system started. 97 | return Environment.TickCount * TimeSpan.TicksPerMillisecond; 98 | } 99 | } 100 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Contracts/IInfluxDb.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using InfluxDB.Net.Infrastructure.Influx; 5 | using InfluxDB.Net.Models; 6 | using InfluxDB.Net.Enums; 7 | 8 | namespace InfluxDB.Net.Contracts 9 | { 10 | public interface IInfluxDb 11 | { 12 | #region Database 13 | 14 | Task CreateDatabaseAsync(string name); 15 | 16 | Task DropDatabaseAsync(string name); 17 | 18 | Task> ShowDatabasesAsync(); 19 | 20 | #endregion Database 21 | 22 | #region Basic Querying 23 | 24 | Task WriteAsync(string database, Point point, string retenionPolicy = "default"); 25 | 26 | Task WriteAsync(string database, Point[] points, string retenionPolicy = "default"); 27 | 28 | Task> QueryAsync(string database, string query); 29 | 30 | Task> QueryAsync(string database, List queries); 31 | 32 | #endregion Basic Querying 33 | 34 | #region Continuous Queries 35 | 36 | Task> DescribeContinuousQueriesAsync(string database); 37 | 38 | Task DeleteContinuousQueryAsync(string database, int id); 39 | 40 | #endregion Continuous Queries 41 | 42 | #region Series 43 | 44 | Task DropSeriesAsync(string database, string serieName); 45 | 46 | #endregion Series 47 | 48 | #region Clustering 49 | 50 | Task CreateClusterAdminAsync(string username, string adminPassword); 51 | 52 | Task DeleteClusterAdminAsync(string username); 53 | 54 | Task> DescribeClusterAdminsAsync(); 55 | 56 | Task UpdateClusterAdminAsync(string username, string password); 57 | 58 | #endregion Clustering 59 | 60 | #region Sharding 61 | 62 | Task> GetShardSpacesAsync(); 63 | 64 | Task DropShardSpaceAsync(string database, string name); 65 | 66 | Task CreateShardSpaceAsync(string database, ShardSpace shardSpace); 67 | 68 | #endregion Sharding 69 | 70 | #region Users 71 | 72 | Task CreateDatabaseUserAsync(string database, string name, string password, params string[] permissions); 73 | 74 | Task DeleteDatabaseUserAsync(string database, string name); 75 | 76 | Task> DescribeDatabaseUsersAsync(string database); 77 | 78 | Task UpdateDatabaseUserAsync(string database, string name, string password, params string[] permissions); 79 | 80 | Task AlterDatabasePrivilegeAsync(string database, string name, bool isAdmin, params string[] permissions); 81 | 82 | Task AuthenticateDatabaseUserAsync(string database, string user, string password); 83 | 84 | #endregion Users 85 | 86 | #region Other 87 | 88 | Task PingAsync(); 89 | 90 | Task ForceRaftCompactionAsync(); 91 | 92 | Task> InterfacesAsync(); 93 | 94 | Task SyncAsync(); 95 | 96 | Task> ListServersAsync(); 97 | 98 | Task RemoveServersAsync(int id); 99 | 100 | IFormatter GetFormatter(); 101 | 102 | InfluxVersion GetClientVersion(); 103 | 104 | #endregion Other 105 | } 106 | } -------------------------------------------------------------------------------- /InfluxDB.Net.Posh/InfluxDB.Net.Posh.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {69792FFC-154A-4C91-99E6-CFCFAAFDBBA4} 8 | Library 9 | Properties 10 | InfluxDB.Net.Posh 11 | InfluxDb 12 | v4.5 13 | 512 14 | ..\ 15 | true 16 | 17 | 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | 26 | 27 | 28 | 29 | pdbonly 30 | true 31 | bin\Release\ 32 | TRACE 33 | prompt 34 | 4 35 | 36 | 37 | 38 | 39 | 40 | True 41 | ..\packages\System.Management.Automation_PowerShell_3.0.6.3.9600.17400\lib\net40\System.Management.Automation.dll 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | {9092cdd0-1585-48de-b619-98f6ff01f8cc} 63 | InfluxDB.Net 64 | 65 | 66 | 67 | 68 | 69 | 70 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 71 | 72 | 73 | 74 | 81 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | InfluxDB.Net 2 | ============ 3 | 4 | >[InfluxDB](http://influxdb.com/) An open-source distributed time series database 5 | with no external dependencies. It is the new home for all of your metrics, events, and analytics. 6 | 7 | A Portable .NET library to access the REST API of a [InfluxDB](http://influxdb.com/) database. 8 | 9 | **Installation** 10 | ```sh 11 | Install-Package InfluxDB.Net-Main 12 | ``` 13 | 14 | **Versions of InfluxDB** 15 | The currently supported versions of InfluxDB is 0.9 - 1.1. When creating a connection to the database you can specify the version to use, or the *auto* configuration that starts by determening the version. 16 | 17 | #### List of supported methods 18 | - [Ping](#ping) 19 | - [Version](#version) 20 | - [CreateDatabase](#create-database) 21 | - [DeleteDatabase](#delete-database) 22 | - [DescribeDatabases](#describe-databases) 23 | - [Write](#write) 24 | - [Query](#query) 25 | - CreateClusterAdmin(User user); 26 | - DeleteClusterAdmin(string name); 27 | - DescribeClusterAdmins(); 28 | - UpdateClusterAdmin(User user, string name); 29 | - CreateDatabaseUser(string database, User user); 30 | - DeleteDatabaseUser(string database, string name); 31 | - DescribeDatabaseUsers(String database); 32 | - UpdateDatabaseUser(string database, User user, string name); 33 | - AuthenticateDatabaseUser(string database, string user, string password); 34 | - GetContinuousQueries(String database); 35 | - DeleteContinuousQuery(string database, int id); 36 | - DeleteSeries(string database, string name); 37 | - ForceRaftCompaction(); 38 | - Interfaces(); 39 | - Sync(); 40 | - ListServers(); 41 | - RemoveServers(int id); 42 | - CreateShard(Shard shard); 43 | - GetShards(); 44 | - DropShard(int id, Shard.Member servers); 45 | - GetShardSpaces(); 46 | - DropShardSpace(string database, string name); 47 | - CreateShardSpace(string database, ShardSpace shardSpace); 48 | 49 | ## Ping 50 | ```csharp 51 | var _client = new InfluxDb("http://...:8086", "root", "root"); 52 | Pong pong =await _client.PingAsync(); 53 | ``` 54 | ## Version 55 | ```csharp 56 | var _client = new InfluxDb("http://...:8086", "root", "root"); 57 | string version =await _client.VersionAsync(); 58 | ``` 59 | ## Create Database 60 | ```csharp 61 | var _client = new InfluxDb("http://...:8086", "root", "root"); 62 | InfluxDbApiCreateResponse response =await _client.CreateDatabaseAsync("MyDb"); 63 | //Or 64 | InfluxDbApiCreateResponse response = await _client.CreateDatabaseAsync(new DatabaseConfiguration 65 | { 66 | Name = "MyDb" 67 | }); 68 | ``` 69 | ## Delete Database 70 | ```csharp 71 | var _client = new InfluxDb("http://...:8086", "root", "root"); 72 | InfluxDbApiDeleteResponse deleteResponse = await _client.DeleteDatabaseAsync("MyDb"); 73 | ``` 74 | ## Describe Databases 75 | ```csharp 76 | var _client = new InfluxDb("http://...:8086", "root", "root"); 77 | List databases = await _client.ShowDatabasesAsync(); 78 | ``` 79 | ## Write 80 | ```csharp 81 | var _client = new InfluxDb("http://...:8086", "root", "root"); 82 | Serie serie = new Serie.Builder("testSeries") 83 | .Columns("value1", "value2") 84 | .Values(DateTime.Now.Millisecond, 5) 85 | .Build(); 86 | InfluxDbApiResponse writeResponse =await _client.WriteAsync("MyDb", TimeUnit.Milliseconds, serie); 87 | ``` 88 | 89 | ## Query 90 | ```csharp 91 | var _client = new InfluxDb("http://...:8086", "root", "root"); 92 | List series = await _client.QueryAsync("MyDb", "select * from testSeries"), TimeUnit.Milliseconds); 93 | ``` 94 | 95 | ## Bugs 96 | If you encounter a bug, performance issue, or malfunction, please add an [Issue](https://github.com/pootzko/InfluxDB.Net/issues) with steps on how to reproduce the problem. 97 | 98 | ##PowerShell Cmdlet 99 | The *PowerShell Cmdlet* can be tested using the script *TestInfluxDb.ps1*. 100 | 101 | **Installation** 102 | import-module [PATH]\InfluxDb -force 103 | 104 | **Open** 105 | ``` 106 | $db = Open-InfluxDb -Uri:"http://...:8086" -User:"root" -Password:"root" 107 | ``` 108 | 109 | **Ping** 110 | ``` 111 | $pong = Ping-InfluxDb -Connection:$db 112 | ``` 113 | 114 | **Add** 115 | Adds a new database. 116 | ``` 117 | Add-InfluxDb -Connection:$db -Name:"SomeDatabase" 118 | ``` 119 | 120 | **Write** 121 | *Not yet implemented* 122 | ``` 123 | Write-InfluxDb 124 | ``` 125 | 126 | ## License 127 | 128 | Code and documentation are available according to the *MIT* License (see [LICENSE](https://github.com/ziyasal/InfluxDB.Net/blob/master/LICENSE)). 129 | -------------------------------------------------------------------------------- /InfluxDB.Net/Contracts/IInfluxDbClient.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using InfluxDB.Net.Client; 4 | using InfluxDB.Net.Infrastructure.Influx; 5 | using InfluxDB.Net.Models; 6 | using InfluxDB.Net.Enums; 7 | 8 | namespace InfluxDB.Net.Contracts 9 | { 10 | internal interface IInfluxDbClient 11 | { 12 | #region Database 13 | 14 | Task CreateDatabase(IEnumerable errorHandlers, Database database); 15 | 16 | Task DropDatabase(IEnumerable errorHandlers, string name); 17 | 18 | Task ShowDatabases(IEnumerable errorHandlers); 19 | 20 | #endregion Database 21 | 22 | #region Basic Querying 23 | 24 | Task Write(IEnumerable errorHandlers, WriteRequest request, string timePrecision); 25 | 26 | Task Query(IEnumerable errorHandlers, string name, string query); 27 | 28 | Task Query(IEnumerable errorHandlers, string name, List queries); 29 | 30 | #endregion Basic Querying 31 | 32 | #region Continuous Queries 33 | 34 | Task GetContinuousQueries(IEnumerable errorHandlers, string database); 35 | 36 | Task DeleteContinuousQuery(IEnumerable errorHandlers, string database, int id); 37 | 38 | #endregion Continuous Queries 39 | 40 | #region Series 41 | 42 | Task DropSeries(IEnumerable errorHandlers, string database, string name); 43 | 44 | #endregion Series 45 | 46 | #region Clustering 47 | 48 | Task CreateClusterAdmin(IEnumerable errorHandlers, User user); 49 | 50 | Task DeleteClusterAdmin(IEnumerable errorHandlers, string name); 51 | 52 | Task DescribeClusterAdmins(IEnumerable errorHandlers); 53 | 54 | Task UpdateClusterAdmin(IEnumerable errorHandlers, User user, string name); 55 | 56 | #endregion Clustering 57 | 58 | #region Sharding 59 | 60 | Task GetShardSpaces(IEnumerable errorHandlers); 61 | 62 | Task DropShardSpace(IEnumerable errorHandlers, string database, string name); 63 | 64 | Task CreateShardSpace(IEnumerable errorHandlers, string database, ShardSpace shardSpace); 65 | 66 | #endregion Sharding 67 | 68 | #region Users 69 | 70 | Task CreateDatabaseUser(IEnumerable errorHandlers, string database, User user); 71 | 72 | Task DeleteDatabaseUser(IEnumerable errorHandlers, string database, string name); 73 | 74 | Task DescribeDatabaseUsers(IEnumerable errorHandlers, string database); 75 | 76 | Task UpdateDatabaseUser(IEnumerable errorHandlers, string database, User user, string name); 77 | 78 | Task AuthenticateDatabaseUser(IEnumerable errorHandlers, string database, string user, string password); 79 | 80 | #endregion Users 81 | 82 | #region Other 83 | 84 | Task Ping(IEnumerable errorHandlers); 85 | 86 | Task ForceRaftCompaction(IEnumerable errorHandlers); 87 | 88 | Task Interfaces(IEnumerable errorHandlers); 89 | 90 | Task Sync(IEnumerable errorHandlers); 91 | 92 | Task ListServers(IEnumerable errorHandlers); 93 | 94 | Task RemoveServers(IEnumerable errorHandlers, int id); 95 | 96 | Task AlterRetentionPolicy(IEnumerable errorHandlers, string policyName, string dbName, string duration, int replication); 97 | 98 | IFormatter GetFormatter(); 99 | 100 | InfluxVersion GetVersion(); 101 | 102 | #endregion Other 103 | } 104 | } -------------------------------------------------------------------------------- /InfluxDB.Net/Infrastructure/Formatters/FormatterBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using InfluxDB.Net.Models; 5 | using InfluxDB.Net.Contracts; 6 | using InfluxDB.Net.Infrastructure.Validation; 7 | using InfluxDB.Net.Helpers; 8 | 9 | namespace InfluxDB.Net.Infrastructure.Formatters 10 | { 11 | internal class FormatterBase : IFormatter 12 | { 13 | private static readonly string _queryTemplate = "{0} {1} {2}"; // [key] [fields] [time] 14 | 15 | public virtual string GetLineTemplate() 16 | { 17 | return _queryTemplate; 18 | } 19 | 20 | /// 21 | /// Returns a point represented in line protocol format for writing to the InfluxDb API endpoint 22 | /// 23 | /// A string that represents this instance. 24 | /// 25 | /// Example outputs: 26 | /// cpu,host=serverA,region=us_west value = 0.64 27 | /// payment,device=mobile,product=Notepad,method=credit billed = 33, licenses = 3i 1434067467100293230 28 | /// stock,symbol=AAPL bid = 127.46, ask = 127.48 29 | /// temperature,machine=unit42,type=assembly external = 25,internal=37 1434067467000000000 30 | /// 31 | public virtual string PointToString(Point point) 32 | { 33 | Validate.NotNullOrEmpty(point.Measurement, "measurement"); 34 | Validate.NotNull(point.Tags, "tags"); 35 | Validate.NotNull(point.Fields, "fields"); 36 | 37 | var tags = String.Join(",", point.Tags.Select(t => String.Join("=", t.Key, EscapeTagValue(t.Value.ToString())))); 38 | var fields = String.Join(",", point.Fields.Select(t => FormatPointField(t.Key, t.Value))); 39 | 40 | var key = String.IsNullOrEmpty(tags) ? EscapeNonTagValue(point.Measurement) : String.Join(",", EscapeNonTagValue(point.Measurement), tags); 41 | var ts = point.Timestamp.HasValue ? point.Timestamp.Value.ToUnixTime().ToString() : string.Empty; 42 | 43 | var result = String.Format(GetLineTemplate(), key, fields, ts); 44 | 45 | return result; 46 | } 47 | 48 | public virtual Serie PointToSerie(Point point) 49 | { 50 | var s = new Serie 51 | { 52 | Name = point.Measurement 53 | }; 54 | 55 | foreach (var key in point.Tags.Keys.ToList()) 56 | { 57 | s.Tags.Add(key, point.Tags[key].ToString()); 58 | } 59 | 60 | var sortedFields = point.Fields.OrderBy(k => k.Key).ToDictionary(x => x.Key, x => x.Value); 61 | 62 | s.Columns = new string[] { "time" }.Concat(sortedFields.Keys).ToArray(); 63 | 64 | s.Values = new object[][] 65 | { 66 | new object[] { point.Timestamp }.Concat(sortedFields.Values).ToArray() 67 | }; 68 | 69 | return s; 70 | } 71 | 72 | protected virtual string FormatPointField(string key, object value) 73 | { 74 | Validate.NotNullOrEmpty(key, "key"); 75 | Validate.NotNull(value, "value"); 76 | 77 | // Format and escape the values 78 | var result = value.ToString(); 79 | 80 | // surround strings with quotes 81 | if (value.GetType() == typeof(string)) 82 | { 83 | result = QuoteValue(EscapeNonTagValue(value.ToString())); 84 | } 85 | // api needs lowercase booleans 86 | else if (value.GetType() == typeof(bool)) 87 | { 88 | result = value.ToString().ToLower(); 89 | } 90 | // InfluxDb does not support a datetime type for fields or tags 91 | // convert datetime to unix long 92 | else if (value.GetType() == typeof(DateTime)) 93 | { 94 | result = ((DateTime)value).ToUnixTime().ToString(); 95 | } 96 | // For cultures using other decimal characters than '.' 97 | else if (value.GetType() == typeof(decimal)) 98 | { 99 | result = ((decimal)value).ToString("0.0###################", CultureInfo.InvariantCulture); 100 | } 101 | else if (value.GetType() == typeof(float)) 102 | { 103 | result = ((float)value).ToString("0.0###################", CultureInfo.InvariantCulture); 104 | } 105 | else if (value.GetType() == typeof(double)) 106 | { 107 | result = ((double)value).ToString("0.0###################", CultureInfo.InvariantCulture); 108 | } 109 | else if (value.GetType() == typeof(long) || value.GetType() == typeof(int)) 110 | { 111 | result = ToInt(result); 112 | } 113 | 114 | return String.Join("=", EscapeNonTagValue(key), result); 115 | } 116 | 117 | protected virtual string ToInt(string result) 118 | { 119 | return result + "i"; 120 | } 121 | 122 | protected virtual string EscapeNonTagValue(string value) 123 | { 124 | Validate.NotNull(value, "value"); 125 | 126 | var result = value 127 | // literal backslash escaping is broken 128 | // https://github.com/influxdb/influxdb/issues/3070 129 | //.Replace(@"\", @"\\") 130 | .Replace(@"""", @"\""") // TODO: check if this is right or if "" should become \"\" 131 | .Replace(@" ", @"\ ") 132 | .Replace(@"=", @"\=") 133 | .Replace(@",", @"\,"); 134 | 135 | return result; 136 | } 137 | 138 | protected virtual string EscapeTagValue(string value) 139 | { 140 | Validate.NotNull(value, "value"); 141 | 142 | var result = value 143 | .Replace(@" ", @"\ ") 144 | .Replace(@"=", @"\=") 145 | .Replace(@",", @"\,"); 146 | 147 | return result; 148 | } 149 | 150 | protected virtual string QuoteValue(string value) 151 | { 152 | Validate.NotNull(value, "value"); 153 | 154 | return "\"" + value + "\""; 155 | } 156 | } 157 | } -------------------------------------------------------------------------------- /InfluxDB.Net.Tests/InfluxDB.Net.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {56B4EF11-8B2A-4862-8723-FC4368274768} 8 | Library 9 | Properties 10 | InfluxDB.Net.Tests 11 | InfluxDB.Net.Tests 12 | v4.6 13 | 512 14 | ..\ 15 | true 16 | 17 | 18 | 19 | 20 | 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | ..\packages\FluentAssertions.4.1.0\lib\net45\FluentAssertions.dll 40 | True 41 | 42 | 43 | ..\packages\FluentAssertions.4.1.0\lib\net45\FluentAssertions.Core.dll 44 | True 45 | 46 | 47 | ..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll 48 | True 49 | 50 | 51 | ..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.dll 52 | True 53 | 54 | 55 | ..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll 56 | True 57 | 58 | 59 | ..\packages\Moq.4.2.1510.2205\lib\net40\Moq.dll 60 | True 61 | 62 | 63 | ..\packages\NUnit.3.0.1\lib\net45\nunit.framework.dll 64 | True 65 | 66 | 67 | ..\packages\AutoFixture.3.37.3\lib\net40\Ploeh.AutoFixture.dll 68 | True 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | Designer 89 | 90 | 91 | Designer 92 | 93 | 94 | 95 | 96 | {9092CDD0-1585-48DE-B619-98F6FF01F8CC} 97 | InfluxDB.Net 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 108 | 109 | 110 | 111 | 112 | 113 | 120 | -------------------------------------------------------------------------------- /.nuget/NuGet.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildProjectDirectory)\..\ 5 | 6 | 7 | false 8 | 9 | 10 | false 11 | 12 | 13 | true 14 | 15 | 16 | false 17 | 18 | 19 | 20 | 21 | 22 | 26 | 27 | 28 | 29 | 30 | $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) 31 | 32 | 33 | 34 | 35 | $(SolutionDir).nuget 36 | 37 | 38 | 39 | $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config 40 | $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config 41 | 42 | 43 | 44 | $(MSBuildProjectDirectory)\packages.config 45 | $(PackagesProjectConfig) 46 | 47 | 48 | 49 | 50 | $(NuGetToolsPath)\NuGet.exe 51 | @(PackageSource) 52 | 53 | "$(NuGetExePath)" 54 | mono --runtime=v4.0.30319 "$(NuGetExePath)" 55 | 56 | $(TargetDir.Trim('\\')) 57 | 58 | -RequireConsent 59 | -NonInteractive 60 | 61 | "$(SolutionDir) " 62 | "$(SolutionDir)" 63 | 64 | 65 | $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir) 66 | $(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols 67 | 68 | 69 | 70 | RestorePackages; 71 | $(BuildDependsOn); 72 | 73 | 74 | 75 | 76 | $(BuildDependsOn); 77 | BuildPackage; 78 | 79 | 80 | 81 | 82 | 83 | 84 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 99 | 100 | 103 | 104 | 105 | 106 | 108 | 109 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /InfluxDB.Net/InfluxDB.Net.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10.0 6 | Debug 7 | AnyCPU 8 | {9092CDD0-1585-48DE-B619-98F6FF01F8CC} 9 | Library 10 | Properties 11 | InfluxDB.Net 12 | InfluxDB.Net 13 | en-US 14 | 512 15 | {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 16 | Profile344 17 | v4.0 18 | ..\ 19 | true 20 | 21 | 22 | 23 | 24 | true 25 | full 26 | false 27 | bin\Debug\ 28 | DEBUG;TRACE 29 | prompt 30 | 4 31 | 32 | 33 | pdbonly 34 | true 35 | bin\Release\ 36 | TRACE 37 | prompt 38 | 4 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | ..\packages\Microsoft.Bcl.Async.1.0.168\lib\portable-net40+sl4+win8+wp71+wpa81\Microsoft.Threading.Tasks.dll 103 | True 104 | 105 | 106 | ..\packages\Microsoft.Bcl.Async.1.0.168\lib\portable-net40+sl4+win8+wp71+wpa81\Microsoft.Threading.Tasks.Extensions.dll 107 | True 108 | 109 | 110 | ..\packages\Newtonsoft.Json.7.0.1\lib\portable-net40+sl5+wp80+win8+wpa81\Newtonsoft.Json.dll 111 | True 112 | 113 | 114 | ..\packages\Microsoft.Bcl.1.1.10\lib\portable-net40+sl5+win8+wp8+wpa81\System.IO.dll 115 | True 116 | 117 | 118 | ..\packages\Microsoft.Net.Http.2.2.29\lib\portable-net40+sl4+win8+wp71+wpa81\System.Net.Http.dll 119 | True 120 | 121 | 122 | ..\packages\Microsoft.Net.Http.2.2.29\lib\portable-net40+sl4+win8+wp71+wpa81\System.Net.Http.Extensions.dll 123 | True 124 | 125 | 126 | ..\packages\Microsoft.Net.Http.2.2.29\lib\portable-net40+sl4+win8+wp71+wpa81\System.Net.Http.Primitives.dll 127 | True 128 | 129 | 130 | ..\packages\Microsoft.Bcl.1.1.10\lib\portable-net40+sl5+win8+wp8+wpa81\System.Runtime.dll 131 | True 132 | 133 | 134 | ..\packages\Microsoft.Bcl.1.1.10\lib\portable-net40+sl5+win8+wp8+wpa81\System.Threading.Tasks.dll 135 | True 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 144 | 145 | 146 | 147 | 148 | 149 | 156 | -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientAutoVersion.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using InfluxDB.Net.Models; 5 | using InfluxDB.Net.Contracts; 6 | using InfluxDB.Net.Enums; 7 | using InfluxDB.Net.Infrastructure.Influx; 8 | using InfluxDB.Net.Infrastructure.Configuration; 9 | 10 | namespace InfluxDB.Net.Client 11 | { 12 | internal class InfluxDbClientAutoVersion : IInfluxDbClient 13 | { 14 | private readonly IInfluxDbClient _influxDbClient; 15 | 16 | public InfluxDbClientAutoVersion(InfluxDbClientConfiguration influxDbClientConfiguration) 17 | { 18 | _influxDbClient = new InfluxDbClientBase(influxDbClientConfiguration); 19 | var errorHandlers = new List(); 20 | 21 | //NOTE: Only performs ping when the client is connected. (Do not use multiple connections with the "Client Auto Version" setting.) 22 | var result = _influxDbClient.Ping(errorHandlers).Result; 23 | var databaseVersion = result.Body; 24 | 25 | if (databaseVersion.StartsWith("1.1.")) 26 | { 27 | _influxDbClient = new InfluxDbClientV013x(influxDbClientConfiguration); 28 | } 29 | else if (databaseVersion.StartsWith("0.13.")) 30 | { 31 | _influxDbClient = new InfluxDbClientV013x(influxDbClientConfiguration); 32 | } 33 | else if (databaseVersion.StartsWith("0.12.")) 34 | { 35 | _influxDbClient = new InfluxDbClientV012x(influxDbClientConfiguration); 36 | } 37 | else if (databaseVersion.StartsWith("0.11.")) 38 | { 39 | _influxDbClient = new InfluxDbClientV011x(influxDbClientConfiguration); 40 | } 41 | else if (databaseVersion.StartsWith("0.10.")) 42 | { 43 | _influxDbClient = new InfluxDbClientV010x(influxDbClientConfiguration); 44 | } 45 | else if (databaseVersion.StartsWith("0.9.")) 46 | { 47 | switch (databaseVersion) 48 | { 49 | case "0.9.2": 50 | _influxDbClient = new InfluxDbClientV092(influxDbClientConfiguration); 51 | break; 52 | case "0.9.5": 53 | _influxDbClient = new InfluxDbClientV092(influxDbClientConfiguration); 54 | break; 55 | case "0.9.6": 56 | _influxDbClient = new InfluxDbClientV092(influxDbClientConfiguration); 57 | break; 58 | } 59 | } 60 | else 61 | { 62 | _influxDbClient = new InfluxDbClientV0x(influxDbClientConfiguration); 63 | } 64 | } 65 | 66 | #region Database 67 | 68 | public async Task CreateDatabase(IEnumerable errorHandlers, Database database) 69 | { 70 | return await _influxDbClient.CreateDatabase(errorHandlers, database); 71 | } 72 | 73 | public async Task DropDatabase(IEnumerable errorHandlers, string name) 74 | { 75 | return await _influxDbClient.DropDatabase(errorHandlers, name); 76 | } 77 | 78 | public async Task ShowDatabases(IEnumerable errorHandlers) 79 | { 80 | return await _influxDbClient.ShowDatabases(errorHandlers); 81 | } 82 | 83 | #endregion Database 84 | 85 | #region Basic Querying 86 | 87 | public async Task Write(IEnumerable errorHandlers, WriteRequest request, string timePrecision) 88 | { 89 | return await _influxDbClient.Write(errorHandlers, request, timePrecision); 90 | } 91 | 92 | public async Task Query(IEnumerable errorHandlers, string name, string query) 93 | { 94 | return await _influxDbClient.Query(errorHandlers, name, query); 95 | } 96 | 97 | public async Task Query(IEnumerable errorHandlers, string name, List queries) 98 | { 99 | return await _influxDbClient.Query(errorHandlers, name, queries); 100 | } 101 | 102 | #endregion Basic Querying 103 | 104 | #region Continuous Queries 105 | 106 | public async Task GetContinuousQueries(IEnumerable errorHandlers, string database) 107 | { 108 | return await _influxDbClient.GetContinuousQueries(errorHandlers, database); 109 | } 110 | 111 | public async Task DeleteContinuousQuery(IEnumerable errorHandlers, string database, int id) 112 | { 113 | return await _influxDbClient.DeleteContinuousQuery(errorHandlers, database, id); 114 | } 115 | 116 | #endregion Continuous Queries 117 | 118 | #region Series 119 | 120 | public async Task DropSeries(IEnumerable errorHandlers, string database, string name) 121 | { 122 | return await _influxDbClient.DropSeries(errorHandlers, database, name); 123 | } 124 | 125 | #endregion Series 126 | 127 | #region Clustering 128 | 129 | public async Task CreateClusterAdmin(IEnumerable errorHandlers, User user) 130 | { 131 | return await _influxDbClient.CreateClusterAdmin(errorHandlers, user); 132 | } 133 | 134 | public async Task DeleteClusterAdmin(IEnumerable errorHandlers, string name) 135 | { 136 | return await _influxDbClient.DeleteClusterAdmin(errorHandlers, name); 137 | } 138 | 139 | public async Task DescribeClusterAdmins(IEnumerable errorHandlers) 140 | { 141 | return await _influxDbClient.DescribeClusterAdmins(errorHandlers); 142 | } 143 | 144 | public async Task UpdateClusterAdmin(IEnumerable errorHandlers, User user, string name) 145 | { 146 | return await _influxDbClient.UpdateClusterAdmin(errorHandlers, user, name); 147 | } 148 | 149 | #endregion Clustering 150 | 151 | #region Sharding 152 | 153 | public async Task GetShardSpaces(IEnumerable errorHandlers) 154 | { 155 | return await _influxDbClient.GetShardSpaces(errorHandlers); 156 | } 157 | 158 | public async Task DropShardSpace(IEnumerable errorHandlers, string database, string name) 159 | { 160 | return await _influxDbClient.DropShardSpace(errorHandlers, database, name); 161 | } 162 | 163 | public async Task CreateShardSpace(IEnumerable errorHandlers, string database, ShardSpace shardSpace) 164 | { 165 | return await _influxDbClient.CreateShardSpace(errorHandlers, database, shardSpace); 166 | } 167 | 168 | #endregion Sharding 169 | 170 | #region Users 171 | 172 | public async Task CreateDatabaseUser(IEnumerable errorHandlers, string database, User user) 173 | { 174 | return await _influxDbClient.CreateDatabaseUser(errorHandlers, database, user); 175 | } 176 | 177 | public async Task DeleteDatabaseUser(IEnumerable errorHandlers, string database, string name) 178 | { 179 | return await _influxDbClient.DeleteDatabaseUser(errorHandlers, database, name); 180 | } 181 | 182 | public async Task DescribeDatabaseUsers(IEnumerable errorHandlers, string database) 183 | { 184 | return await _influxDbClient.DescribeDatabaseUsers(errorHandlers, database); 185 | } 186 | 187 | public async Task UpdateDatabaseUser(IEnumerable errorHandlers, string database, User user, string name) 188 | { 189 | return await _influxDbClient.UpdateDatabaseUser(errorHandlers, database, user, name); 190 | } 191 | 192 | public async Task AuthenticateDatabaseUser(IEnumerable errorHandlers, string database, string user, string password) 193 | { 194 | return await _influxDbClient.AuthenticateDatabaseUser(errorHandlers, database, user, password); 195 | } 196 | 197 | #endregion Users 198 | 199 | #region Other 200 | 201 | public async Task Ping(IEnumerable errorHandlers) 202 | { 203 | return await _influxDbClient.Ping(errorHandlers); 204 | } 205 | 206 | public async Task ForceRaftCompaction(IEnumerable errorHandlers) 207 | { 208 | return await _influxDbClient.ForceRaftCompaction(errorHandlers); 209 | } 210 | 211 | public async Task Interfaces(IEnumerable errorHandlers) 212 | { 213 | return await _influxDbClient.Interfaces(errorHandlers); 214 | } 215 | 216 | public async Task Sync(IEnumerable errorHandlers) 217 | { 218 | return await _influxDbClient.Sync(errorHandlers); 219 | } 220 | 221 | public async Task ListServers(IEnumerable errorHandlers) 222 | { 223 | return await _influxDbClient.ListServers(errorHandlers); 224 | } 225 | 226 | public async Task RemoveServers(IEnumerable errorHandlers, int id) 227 | { 228 | return await _influxDbClient.RemoveServers(errorHandlers, id); 229 | } 230 | 231 | public async Task AlterRetentionPolicy(IEnumerable errorHandlers, string policyName, string dbName, string duration, int replication) 232 | { 233 | return await _influxDbClient.AlterRetentionPolicy(errorHandlers, policyName, dbName, duration, replication); 234 | } 235 | 236 | public IFormatter GetFormatter() 237 | { 238 | return _influxDbClient.GetFormatter(); 239 | } 240 | 241 | public InfluxVersion GetVersion() 242 | { 243 | return _influxDbClient.GetVersion(); 244 | } 245 | 246 | #endregion Other 247 | } 248 | } -------------------------------------------------------------------------------- /InfluxDB.Net.Tests/InfluxDBTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using FluentAssertions; 5 | using InfluxDB.Net.Models; 6 | using NUnit.Framework; 7 | using Ploeh.AutoFixture; 8 | using System.Configuration; 9 | using System.Threading.Tasks; 10 | using InfluxDB.Net.Contracts; 11 | using InfluxDB.Net.Helpers; 12 | using InfluxDB.Net.Infrastructure.Influx; 13 | using InfluxDB.Net.Enums; 14 | 15 | namespace InfluxDB.Net.Tests 16 | { 17 | public class InfluxDbTests : TestBase 18 | { 19 | private IInfluxDb _influx; 20 | private string _dbName = String.Empty; 21 | private static readonly string _fakeDbPrefix = "FakeDb"; 22 | private static readonly string _fakeMeasurementPrefix = "FakeMeasurement"; 23 | 24 | protected override async Task FinalizeSetUp() 25 | { 26 | //TODO: Have this injectable so it can be executed from the test server with different data 27 | InfluxVersion influxVersion; 28 | if (!Enum.TryParse(ConfigurationManager.AppSettings.Get("version"), out influxVersion)) 29 | influxVersion = InfluxVersion.Auto; 30 | 31 | _influx = new InfluxDb( 32 | ConfigurationManager.AppSettings.Get("url"), 33 | ConfigurationManager.AppSettings.Get("username"), 34 | ConfigurationManager.AppSettings.Get("password"), 35 | influxVersion); 36 | 37 | _influx.Should().NotBeNull(); 38 | 39 | _dbName = CreateRandomDbName(); 40 | 41 | //PurgeFakeDatabases(); 42 | 43 | var createResponse = _influx.CreateDatabaseAsync(_dbName).Result; 44 | createResponse.Success.Should().BeTrue(); 45 | 46 | // workaround for issue https://github.com/influxdb/influxdb/issues/3363 47 | // by first creating a single point in the empty db 48 | var writeResponse = _influx.WriteAsync(_dbName, CreateMockPoints(1)); 49 | writeResponse.Result.Success.Should().BeTrue(); 50 | } 51 | 52 | private async void PurgeFakeDatabases() 53 | { 54 | var databasesResponse = _influx.ShowDatabasesAsync(); 55 | var dbs = databasesResponse.Result; 56 | 57 | foreach (var db in dbs) 58 | { 59 | if (db.Name.StartsWith(_fakeDbPrefix)) 60 | await _influx.DropDatabaseAsync(db.Name); 61 | } 62 | } 63 | 64 | protected override async Task FinalizeTearDown() 65 | { 66 | var deleteResponse = _influx.DropDatabaseAsync(_dbName).Result; 67 | 68 | deleteResponse.Success.Should().BeTrue(); 69 | } 70 | 71 | [Test] 72 | public async Task Influx_OnPing_ShouldReturnVersion() 73 | { 74 | var pong = await _influx.PingAsync(); 75 | 76 | pong.Should().NotBeNull(); 77 | pong.Success.Should().BeTrue(); 78 | pong.Version.Should().NotBeEmpty(); 79 | } 80 | 81 | [Test] 82 | public async Task Influx_OnFakeDbName_ShouldCreateAndDropDb() 83 | { 84 | // Arrange 85 | var dbName = CreateRandomDbName(); 86 | 87 | // Act 88 | var createResponse = await _influx.CreateDatabaseAsync(dbName); 89 | var deleteResponse = await _influx.DropDatabaseAsync(dbName); 90 | 91 | // Assert 92 | createResponse.Success.Should().BeTrue(); 93 | deleteResponse.Success.Should().BeTrue(); 94 | } 95 | 96 | [Test] 97 | public async Task DbShowDatabases_OnDatabaseExists_ShouldReturnDatabaseList() 98 | { 99 | // Arrange 100 | var dbName = CreateRandomDbName(); 101 | var createResponse = await _influx.CreateDatabaseAsync(dbName); 102 | createResponse.Success.Should().BeTrue(); 103 | 104 | // Act 105 | var databases = await _influx.ShowDatabasesAsync(); 106 | 107 | // Assert 108 | databases 109 | .Should() 110 | .NotBeNullOrEmpty(); 111 | 112 | databases 113 | .Where(db => db.Name.Equals(dbName)) 114 | .Single() 115 | .Should() 116 | .NotBeNull(); 117 | } 118 | 119 | [Test] 120 | public async Task DbWrite_OnMultiplePoints_ShouldWritePoints() 121 | { 122 | var points = CreateMockPoints(5); 123 | 124 | var writeResponse = await _influx.WriteAsync(_dbName, points); 125 | writeResponse.Success.Should().BeTrue(); 126 | } 127 | 128 | [Test] 129 | public void DbWrite_OnPointsWithoutFields_ShouldThrowException() 130 | { 131 | var points = CreateMockPoints(1); 132 | points.Single().Timestamp = null; 133 | points.Single().Fields.Clear(); 134 | 135 | Func act = async () => { await _influx.WriteAsync(_dbName, points); }; 136 | act.ShouldThrow(); 137 | } 138 | 139 | [Test] 140 | public void DbQuery_OnInvalidQuery_ShouldThrowException() 141 | { 142 | Func act = async () => { await _influx.QueryAsync(_dbName, "blah"); }; 143 | act.ShouldThrow(); 144 | } 145 | 146 | [Test] 147 | public async Task DbQuery_OnNonExistantSeries_ShouldReturnEmptyList() 148 | { 149 | var result = await _influx.QueryAsync(_dbName, "select * from nonexistentseries"); 150 | result.Should().NotBeNull(); 151 | result.Should().BeEmpty(); 152 | } 153 | 154 | [Test] 155 | public async Task DbQuery_OnNonExistantFields_ShouldReturnEmptyList() 156 | { 157 | var points = CreateMockPoints(1); 158 | var response = await _influx.WriteAsync(_dbName, points); 159 | 160 | response.Success.Should().BeTrue(); 161 | 162 | var result = await _influx.QueryAsync(_dbName, String.Format("select nonexistentfield from \"{0}\"", points.Single().Measurement)); 163 | result.Should().NotBeNull(); 164 | result.Should().BeEmpty(); 165 | } 166 | 167 | [Test] 168 | public async Task DbDropSeries_OnExistingSeries_ShouldDropSeries() 169 | { 170 | var points = CreateMockPoints(1); 171 | var writeResponse = await _influx.WriteAsync(_dbName, points); 172 | writeResponse.Success.Should().BeTrue(); 173 | 174 | var expected = _influx.GetFormatter().PointToSerie(points.First()); 175 | // query 176 | await Query(expected); 177 | 178 | var deleteSerieResponse = await _influx.DropSeriesAsync(_dbName, points.First().Measurement); 179 | deleteSerieResponse.Success.Should().BeTrue(); 180 | } 181 | 182 | [Test] 183 | public async Task DbQuery_OnWhereClauseNotMet_ShouldReturnNoSeries() 184 | { 185 | // Arrange 186 | var points = CreateMockPoints(1); 187 | var writeResponse = await _influx.WriteAsync(_dbName, points); 188 | writeResponse.Success.Should().BeTrue(); 189 | 190 | // Act 191 | var queryResponse = await _influx.QueryAsync(_dbName, String.Format("select * from \"{0}\" where 0=1", points.Single().Measurement)); 192 | 193 | // Assert 194 | queryResponse.Count.Should().Be(0); 195 | } 196 | 197 | [Test] 198 | public async Task DbQuery_Multiple_ShouldReturnTwoSeries() 199 | { 200 | // Arrange 201 | var points = CreateMockPoints(1); 202 | var writeResponse = await _influx.WriteAsync(_dbName, points); 203 | writeResponse.Success.Should().BeTrue(); 204 | 205 | // Act 206 | var query1 = String.Format("select * from \"{0}\"", points.Single().Measurement); 207 | var query2 = String.Format("select * from \"{0}\"", points.Single().Measurement); 208 | var queries = new List { query1, query2 }; 209 | var queryResponse = await _influx.QueryAsync(_dbName, queries); 210 | 211 | // Assert 212 | queryResponse.Count.Should().Be(queries.Count); 213 | } 214 | 215 | [Test] 216 | public void Formats_Point() 217 | { 218 | const string value = @"\=&,""*"" -"; 219 | const string escapedFieldValue = @"\\=&\,\""*\""\ -"; 220 | const string escapedTagValue = @"\\=&\,""*""\ -"; 221 | const string seriesName = @"x"; 222 | const string tagName = @"tag_string"; 223 | const string fieldName = @"field_string"; 224 | var dt = DateTime.Now; 225 | 226 | var point = new Point 227 | { 228 | Measurement = seriesName, 229 | Tags = new Dictionary 230 | { 231 | { tagName, value } 232 | }, 233 | Fields = new Dictionary 234 | { 235 | { fieldName, value } 236 | }, 237 | Timestamp = dt 238 | }; 239 | 240 | var formatter = _influx.GetFormatter(); 241 | var expected = String.Format(formatter.GetLineTemplate(), 242 | /* key */ seriesName + "," + tagName + "=" + escapedTagValue, 243 | /* fields */ fieldName + "=" + "\"" + escapedFieldValue + "\"", 244 | /* timestamp */ dt.ToUnixTime()); 245 | 246 | var actual = formatter.PointToString(point); 247 | 248 | actual.Should().Be(expected); 249 | } 250 | 251 | [Test] 252 | public void WriteRequestGetLines_OnCall_ShouldReturnNewLineSeparatedPoints() 253 | { 254 | var points = CreateMockPoints(2); 255 | var formatter = _influx.GetFormatter(); 256 | var request = new WriteRequest(formatter) 257 | { 258 | Points = points 259 | }; 260 | 261 | var actual = request.GetLines(); 262 | var expected = String.Join("\n", points.Select(p => formatter.PointToString(p))); 263 | 264 | actual.Should().Be(expected); 265 | } 266 | 267 | private async Task> Query(Serie expected) 268 | { 269 | // 0.9.3 need 'group by' to retrieve tags as tags when using select * 270 | var result = await _influx.QueryAsync(_dbName, String.Format("select * from \"{0}\" group by *", expected.Name)); 271 | 272 | result.Should().NotBeNull(); 273 | result.Count().Should().Be(1); 274 | 275 | var actual = result.Single(); 276 | 277 | actual.Name.Should().Be(expected.Name); 278 | actual.Tags.Count.Should().Be(expected.Tags.Count); 279 | actual.Tags.ShouldAllBeEquivalentTo(expected.Tags); 280 | actual.Columns.ShouldAllBeEquivalentTo(expected.Columns); 281 | actual.Columns.Count().Should().Be(expected.Columns.Count()); 282 | actual.Values[0].Count().Should().Be(expected.Values[0].Count()); 283 | ((DateTime)actual.Values[0][0]).ToUnixTime().Should().Be(((DateTime)expected.Values[0][0]).ToUnixTime()); 284 | 285 | return result; 286 | } 287 | 288 | private static string CreateRandomDbName() 289 | { 290 | var timestamp = DateTime.UtcNow.ToUnixTime(); 291 | return String.Format("{0}{1}", _fakeDbPrefix, timestamp); 292 | } 293 | 294 | private static string CreateRandomMeasurementName() 295 | { 296 | var timestamp = DateTime.UtcNow.ToUnixTime(); 297 | return String.Format("{0}{1}", _fakeMeasurementPrefix, timestamp); 298 | } 299 | 300 | private Point[] CreateMockPoints(int amount) 301 | { 302 | var rnd = new Random(); 303 | var fixture = new Fixture(); 304 | 305 | fixture.Customize(c => c 306 | .With(p => p.Measurement, CreateRandomMeasurementName()) 307 | .Do(p => p.Tags = NewTags(rnd)) 308 | .Do(p => p.Fields = NewFields(rnd)) 309 | .OmitAutoProperties()); 310 | 311 | var points = fixture.CreateMany(amount).ToArray(); 312 | var timestamp = DateTime.UtcNow.AddDays(-5); 313 | foreach (var point in points) 314 | { 315 | timestamp = timestamp.AddMinutes(1); 316 | point.Timestamp = timestamp; 317 | } 318 | 319 | return points; 320 | } 321 | 322 | private Dictionary NewTags(Random rnd) 323 | { 324 | return new Dictionary 325 | { 326 | // quotes in the tag value are creating problems 327 | // https://github.com/influxdb/influxdb/issues/3928 328 | //{"tag_string", rnd.NextPrintableString(50).Replace("\"", string.Empty)}, 329 | {"tag_bool", (rnd.Next(2) == 0).ToString()}, 330 | {"tag_datetime", DateTime.Now.ToString()}, 331 | {"tag_decimal", ((decimal) rnd.NextDouble()).ToString()}, 332 | {"tag_float", ((float) rnd.NextDouble()).ToString()}, 333 | {"tag_int", rnd.Next().ToString()} 334 | }; 335 | } 336 | 337 | private Dictionary NewFields(Random rnd) 338 | { 339 | return new Dictionary 340 | { 341 | //{ "field_string", rnd.NextPrintableString(50) }, 342 | { "field_bool", rnd.Next(2) == 0 }, 343 | { "field_int", rnd.Next() }, 344 | { "field_decimal", (decimal)rnd.NextDouble() }, 345 | { "field_float", (float)rnd.NextDouble() }, 346 | { "field_datetime", DateTime.Now } 347 | }; 348 | } 349 | } 350 | } 351 | -------------------------------------------------------------------------------- /InfluxDB.Net/Client/InfluxDbClientBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | using InfluxDB.Net.Models; 10 | using System.Diagnostics; 11 | using InfluxDB.Net.Constants; 12 | using InfluxDB.Net.Contracts; 13 | using InfluxDB.Net.Helpers; 14 | using InfluxDB.Net.Infrastructure.Configuration; 15 | using InfluxDB.Net.Infrastructure.Influx; 16 | using InfluxDB.Net.Enums; 17 | using InfluxDB.Net.Infrastructure.Formatters; 18 | 19 | namespace InfluxDB.Net.Client 20 | { 21 | internal class InfluxDbClientBase : IInfluxDbClient 22 | { 23 | private const string UserAgent = "InfluxDb.Net"; 24 | 25 | private readonly InfluxDbClientConfiguration _configuration; 26 | 27 | private readonly ApiResponseErrorHandlingDelegate _defaultErrorHandlingDelegate = (statusCode, body) => 28 | { 29 | if (statusCode < HttpStatusCode.OK || statusCode >= HttpStatusCode.BadRequest) 30 | { 31 | Debug.WriteLine("[Error] {0} {1}", statusCode, body); 32 | throw new InfluxDbApiException(statusCode, body); 33 | } 34 | }; 35 | 36 | public InfluxDbClientBase(InfluxDbClientConfiguration configuration) 37 | { 38 | _configuration = configuration; 39 | } 40 | 41 | #region Database 42 | 43 | /// Creates the database. 44 | /// The error handlers. 45 | /// The database. 46 | /// 47 | public async Task CreateDatabase(IEnumerable errorHandlers, Database database) 48 | { 49 | return await RequestAsync(errorHandlers, HttpMethod.Get, "query", null, 50 | new Dictionary { { QueryParams.Query, String.Format(QueryStatements.CreateDatabase, database.Name) } }, 51 | requestTimeout: _configuration.RequestTimeout); 52 | } 53 | 54 | /// Drops the database. 55 | /// The error handlers. 56 | /// The name. 57 | /// 58 | public async Task DropDatabase(IEnumerable errorHandlers, string name) 59 | { 60 | return await RequestAsync(errorHandlers, HttpMethod.Get, "query", null, 61 | new Dictionary { { QueryParams.Query, String.Format(QueryStatements.DropDatabase, name) } }, 62 | requestTimeout: _configuration.RequestTimeout); 63 | } 64 | 65 | /// Queries the list of databases. 66 | /// The error handlers. 67 | /// 68 | public async Task ShowDatabases(IEnumerable errorHandlers) 69 | { 70 | return await RequestAsync(errorHandlers, HttpMethod.Get, "query", null, 71 | new Dictionary { { QueryParams.Query, QueryStatements.ShowDatabases } }, 72 | requestTimeout: _configuration.RequestTimeout); 73 | } 74 | 75 | #endregion Database 76 | 77 | #region Basic Querying 78 | 79 | /// Writes the request to the endpoint. 80 | /// The error handlers. 81 | /// The request. 82 | /// The time precision. 83 | /// 84 | public async Task Write(IEnumerable errorHandlers, WriteRequest request, string timePrecision) 85 | { 86 | var content = new StringContent(request.GetLines(), Encoding.UTF8, "text/plain"); 87 | var result = await RequestAsync(errorHandlers, HttpMethod.Post, "write", content, 88 | new Dictionary 89 | { 90 | { QueryParams.Db, request.Database}, 91 | { QueryParams.Precision, timePrecision } 92 | }, true, false, 93 | requestTimeout: _configuration.RequestTimeout); 94 | 95 | return new InfluxDbApiWriteResponse(result.StatusCode, result.Body); 96 | } 97 | 98 | /// Queries the endpoint. 99 | /// The error handlers. 100 | /// The name. 101 | /// The query. 102 | /// 103 | public async Task Query(IEnumerable errorHandlers, string name, string query) 104 | { 105 | return await RequestAsync(errorHandlers, HttpMethod.Get, "query", null, 106 | new Dictionary 107 | { 108 | {QueryParams.Db, name}, 109 | {QueryParams.Query, query} 110 | }, 111 | requestTimeout: _configuration.RequestTimeout); 112 | } 113 | 114 | /// Queries the endpoint. 115 | /// The error handlers. 116 | /// The name. 117 | /// The query list. 118 | /// 119 | public async Task Query(IEnumerable errorHandlers, string name, List queries) 120 | { 121 | return await RequestAsync(errorHandlers, HttpMethod.Get, "query", null, 122 | new Dictionary 123 | { 124 | {QueryParams.Db, name}, 125 | {QueryParams.Query, string.Join("%3B", queries)} 126 | }, 127 | requestTimeout: _configuration.RequestTimeout); 128 | } 129 | 130 | #endregion Basic Querying 131 | 132 | #region Continuous Queries 133 | 134 | public Task GetContinuousQueries(IEnumerable errorHandlers, string database) 135 | { 136 | throw new NotImplementedException(); 137 | } 138 | 139 | public Task DeleteContinuousQuery(IEnumerable errorHandlers, string database, int id) 140 | { 141 | throw new NotImplementedException(); 142 | } 143 | 144 | #endregion Continuous Queries 145 | 146 | #region Series 147 | 148 | public async Task DropSeries(IEnumerable errorHandlers, string database, string name) 149 | { 150 | return await RequestAsync(errorHandlers, HttpMethod.Get, "query", null, 151 | new Dictionary 152 | { 153 | { QueryParams.Db, database }, 154 | { QueryParams.Query, String.Format(QueryStatements.DropSeries, name) } 155 | }, 156 | requestTimeout: _configuration.RequestTimeout); 157 | } 158 | 159 | #endregion Series 160 | 161 | #region Clustering 162 | 163 | public Task CreateClusterAdmin(IEnumerable errorHandlers, User user) 164 | { 165 | throw new NotImplementedException(); 166 | } 167 | 168 | public Task DeleteClusterAdmin(IEnumerable errorHandlers, string name) 169 | { 170 | throw new NotImplementedException(); 171 | } 172 | 173 | public Task DescribeClusterAdmins(IEnumerable errorHandlers) 174 | { 175 | throw new NotImplementedException(); 176 | } 177 | 178 | public Task UpdateClusterAdmin(IEnumerable errorHandlers, User user, string name) 179 | { 180 | throw new NotImplementedException(); 181 | } 182 | 183 | #endregion Clustering 184 | 185 | #region Sharding 186 | 187 | public Task GetShardSpaces(IEnumerable errorHandlers) 188 | { 189 | throw new NotImplementedException(); 190 | } 191 | 192 | public Task DropShardSpace(IEnumerable errorHandlers, string database, string name) 193 | { 194 | throw new NotImplementedException(); 195 | } 196 | 197 | public Task CreateShardSpace(IEnumerable errorHandlers, string database, ShardSpace shardSpace) 198 | { 199 | throw new NotImplementedException(); 200 | } 201 | 202 | #endregion Sharding 203 | 204 | #region Users 205 | 206 | public Task CreateDatabaseUser(IEnumerable errorHandlers, string database, User user) 207 | { 208 | throw new NotImplementedException(); 209 | } 210 | 211 | public Task DeleteDatabaseUser(IEnumerable errorHandlers, string database, string name) 212 | { 213 | throw new NotImplementedException(); 214 | } 215 | 216 | public Task DescribeDatabaseUsers(IEnumerable errorHandlers, string database) 217 | { 218 | throw new NotImplementedException(); 219 | } 220 | 221 | public Task UpdateDatabaseUser(IEnumerable errorHandlers, string database, User user, string name) 222 | { 223 | throw new NotImplementedException(); 224 | } 225 | 226 | public Task AuthenticateDatabaseUser(IEnumerable errorHandlers, string database, string user, string password) 227 | { 228 | throw new NotImplementedException(); 229 | } 230 | 231 | #endregion Users 232 | 233 | #region Other 234 | 235 | /// Pings the server. 236 | /// The error handlers. 237 | /// 238 | public async Task Ping(IEnumerable errorHandlers) 239 | { 240 | return await RequestAsync(errorHandlers, HttpMethod.Get, "ping", null, null, false, true, 241 | requestTimeout: _configuration.RequestTimeout); 242 | } 243 | 244 | public Task ForceRaftCompaction(IEnumerable errorHandlers) 245 | { 246 | throw new NotImplementedException(); 247 | } 248 | 249 | public Task Interfaces(IEnumerable errorHandlers) 250 | { 251 | throw new NotImplementedException(); 252 | } 253 | 254 | public Task Sync(IEnumerable errorHandlers) 255 | { 256 | throw new NotImplementedException(); 257 | } 258 | 259 | public Task ListServers(IEnumerable errorHandlers) 260 | { 261 | throw new NotImplementedException(); 262 | } 263 | 264 | public Task RemoveServers(IEnumerable errorHandlers, int id) 265 | { 266 | throw new NotImplementedException(); 267 | } 268 | 269 | /// Alters the retention policy. 270 | /// The error handlers. 271 | /// Name of the policy. 272 | /// Name of the database. 273 | /// The duration. 274 | /// The replication factor. 275 | /// 276 | public async Task AlterRetentionPolicy(IEnumerable errorHandlers, string policyName, string dbName, string duration, int replication) 277 | { 278 | return await RequestAsync(errorHandlers, HttpMethod.Get, "query", null, 279 | new Dictionary 280 | { 281 | {QueryParams.Query, string.Format(QueryStatements.AlterRetentionPolicy, policyName, dbName, duration, replication) } 282 | }, 283 | requestTimeout: _configuration.RequestTimeout); 284 | } 285 | 286 | public virtual IFormatter GetFormatter() 287 | { 288 | return new FormatterBase(); 289 | } 290 | 291 | public virtual InfluxVersion GetVersion() 292 | { 293 | return InfluxVersion.v09x; 294 | } 295 | 296 | #endregion Other 297 | 298 | #region Base 299 | 300 | private HttpClient GetHttpClient() 301 | { 302 | return _configuration.BuildHttpClient(); 303 | } 304 | 305 | private async Task RequestAsync( 306 | IEnumerable errorHandlers, 307 | HttpMethod method, 308 | string path, 309 | HttpContent content = null, 310 | Dictionary extraParams = null, 311 | bool includeAuthToQuery = true, 312 | bool headerIsBody = false, 313 | TimeSpan? requestTimeout = null) 314 | { 315 | var response = await RequestInnerAsync(requestTimeout, 316 | HttpCompletionOption.ResponseHeadersRead, 317 | CancellationToken.None, 318 | method, 319 | path, 320 | content, 321 | extraParams, 322 | includeAuthToQuery); 323 | 324 | string responseContent = String.Empty; 325 | 326 | if (!headerIsBody) 327 | { 328 | responseContent = await response.Content.ReadAsStringAsync(); 329 | } 330 | else 331 | { 332 | IEnumerable values; 333 | 334 | if (response.Headers.TryGetValues("X-Influxdb-Version", out values)) 335 | { 336 | responseContent = values.First(); 337 | } 338 | } 339 | 340 | HandleIfErrorResponse(response.StatusCode, responseContent, errorHandlers); 341 | 342 | Debug.WriteLine("[Response] {0}", response.ToJson()); 343 | Debug.WriteLine("[ResponseData] {0}", responseContent); 344 | 345 | return new InfluxDbApiResponse(response.StatusCode, responseContent); 346 | } 347 | 348 | private async Task RequestInnerAsync( 349 | TimeSpan? requestTimeout, 350 | HttpCompletionOption completionOption, 351 | CancellationToken cancellationToken, 352 | HttpMethod method, 353 | string path, 354 | HttpContent content = null, 355 | Dictionary extraParams = null, 356 | bool includeAuthToQuery = true) 357 | { 358 | HttpClient client = GetHttpClient(); 359 | 360 | if (requestTimeout.HasValue) 361 | { 362 | client.Timeout = requestTimeout.Value; 363 | } 364 | 365 | StringBuilder uri = BuildUri(path, extraParams, includeAuthToQuery); 366 | HttpRequestMessage request = PrepareRequest(method, content, uri); 367 | 368 | Debug.WriteLine("[Request] {0}", request.ToJson()); 369 | if (content != null) 370 | { 371 | Debug.WriteLine("[RequestData] {0}", content.ReadAsStringAsync().Result); 372 | } 373 | 374 | return await client.SendAsync(request, completionOption, cancellationToken); 375 | } 376 | 377 | private StringBuilder BuildUri(string path, Dictionary extraParams, bool includeAuthToQuery) 378 | { 379 | var urlBuilder = new StringBuilder(); 380 | urlBuilder.AppendFormat("{0}{1}", _configuration.EndpointBaseUri, path); 381 | 382 | if (includeAuthToQuery) 383 | { 384 | urlBuilder.AppendFormat("?{0}={1}&{2}={3}", QueryParams.Username, HttpUtility.UrlEncode(_configuration.Username), QueryParams.Password, HttpUtility.UrlEncode(_configuration.Password)); 385 | } 386 | 387 | if (extraParams != null && extraParams.Count > 0) 388 | { 389 | var keyValues = new List(extraParams.Count); 390 | keyValues.AddRange(extraParams.Select(param => String.Format("{0}={1}", param.Key, param.Value))); 391 | urlBuilder.AppendFormat("{0}{1}", includeAuthToQuery ? "&" : "?", String.Join("&", keyValues)); 392 | } 393 | 394 | return urlBuilder; 395 | } 396 | 397 | private static HttpRequestMessage PrepareRequest(HttpMethod method, HttpContent content, StringBuilder urlBuilder) 398 | { 399 | var request = new HttpRequestMessage(method, urlBuilder.ToString()); 400 | request.Headers.Add("User-Agent", UserAgent); 401 | request.Headers.Add("Accept", "application/json"); 402 | 403 | request.Content = content; 404 | 405 | return request; 406 | } 407 | 408 | private void HandleIfErrorResponse(HttpStatusCode statusCode, string responseBody, IEnumerable handlers) 409 | { 410 | if (handlers == null) 411 | { 412 | throw new ArgumentNullException("handlers"); 413 | } 414 | 415 | foreach (ApiResponseErrorHandlingDelegate handler in handlers) 416 | { 417 | handler(statusCode, responseBody); 418 | } 419 | _defaultErrorHandlingDelegate(statusCode, responseBody); 420 | } 421 | 422 | #endregion Base 423 | } 424 | 425 | internal delegate void ApiResponseErrorHandlingDelegate(HttpStatusCode statusCode, string responseBody); 426 | } -------------------------------------------------------------------------------- /InfluxDB.Net/InfluxDb.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using InfluxDB.Net.Client; 6 | using InfluxDB.Net.Contracts; 7 | using InfluxDB.Net.Enums; 8 | using InfluxDB.Net.Helpers; 9 | using InfluxDB.Net.Infrastructure.Configuration; 10 | using InfluxDB.Net.Infrastructure.Influx; 11 | using InfluxDB.Net.Infrastructure.Validation; 12 | using InfluxDB.Net.Models; 13 | 14 | namespace InfluxDB.Net 15 | { 16 | public class InfluxDb : IInfluxDb 17 | { 18 | internal readonly IEnumerable NoErrorHandlers = Enumerable.Empty(); 19 | 20 | private readonly IInfluxDbClient _influxDbClient; 21 | 22 | public InfluxDb(string url, string username, string password, InfluxVersion influxVersion = InfluxVersion.Auto, TimeSpan? requestTimeout = null) 23 | : this(new InfluxDbClientConfiguration(new Uri(url), username, password, influxVersion, requestTimeout)) 24 | { 25 | Validate.NotNullOrEmpty(url, "The URL may not be null or empty."); 26 | Validate.NotNullOrEmpty(username, "The username may not be null or empty."); 27 | } 28 | 29 | internal InfluxDb(InfluxDbClientConfiguration influxDbClientConfiguration) 30 | { 31 | switch (influxDbClientConfiguration.InfluxVersion) 32 | { 33 | case InfluxVersion.Auto: 34 | _influxDbClient = new InfluxDbClientAutoVersion(influxDbClientConfiguration); 35 | break; 36 | case InfluxVersion.v013x: 37 | _influxDbClient = new InfluxDbClientV013x(influxDbClientConfiguration); 38 | break; 39 | case InfluxVersion.v012x: 40 | _influxDbClient = new InfluxDbClientV012x(influxDbClientConfiguration); 41 | break; 42 | case InfluxVersion.v011x: 43 | _influxDbClient = new InfluxDbClientV011x(influxDbClientConfiguration); 44 | break; 45 | case InfluxVersion.v010x: 46 | _influxDbClient = new InfluxDbClientV010x(influxDbClientConfiguration); 47 | break; 48 | case InfluxVersion.v09x: 49 | _influxDbClient = new InfluxDbClientBase(influxDbClientConfiguration); 50 | break; 51 | case InfluxVersion.v096: 52 | _influxDbClient = new InfluxDbClientV096(influxDbClientConfiguration); 53 | break; 54 | case InfluxVersion.v095: 55 | _influxDbClient = new InfluxDbClientV095(influxDbClientConfiguration); 56 | break; 57 | case InfluxVersion.v092: 58 | _influxDbClient = new InfluxDbClientV092(influxDbClientConfiguration); 59 | break; 60 | case InfluxVersion.v08x: 61 | throw new NotImplementedException(); 62 | default: 63 | throw new ArgumentOutOfRangeException("influxDbClientConfiguration", String.Format("Unknown version {0}.", influxDbClientConfiguration.InfluxVersion)); 64 | } 65 | } 66 | 67 | #region Database 68 | 69 | /// 70 | /// Create a new Database. 71 | /// 72 | /// The name of the new database 73 | /// 74 | public async Task CreateDatabaseAsync(string name) 75 | { 76 | var db = new Database { Name = name }; 77 | 78 | return await _influxDbClient.CreateDatabase(NoErrorHandlers, db); 79 | } 80 | 81 | /// 82 | /// Drop a database. 83 | /// 84 | /// The name of the database to delete. 85 | /// 86 | public async Task DropDatabaseAsync(string name) 87 | { 88 | return await _influxDbClient.DropDatabase(NoErrorHandlers, name); 89 | } 90 | 91 | /// 92 | /// Describe all available databases. 93 | /// 94 | /// A list of all Databases 95 | public async Task> ShowDatabasesAsync() 96 | { 97 | var response = await _influxDbClient.ShowDatabases(NoErrorHandlers); 98 | var queryResult = response.ReadAs(); 99 | var serie = queryResult.Results.Single().Series.Single(); 100 | var databases = new List(); 101 | 102 | foreach (var value in serie.Values) 103 | { 104 | databases.Add(new Database 105 | { 106 | Name = (string)value[0] 107 | }); 108 | } 109 | 110 | return databases; 111 | } 112 | 113 | #endregion Database 114 | 115 | #region Basic Querying 116 | 117 | /// Write a single serie to the given database. 118 | /// The name of the database to write to. 119 | /// A serie . 120 | /// The retenion policy. 121 | /// TODO: comment 122 | public async Task WriteAsync(string database, Point point, string retenionPolicy = "default") 123 | { 124 | return await WriteAsync(database, new[] { point }, retenionPolicy); 125 | } 126 | 127 | /// Write multiple serie points to the given database. 128 | /// The name of the database to write to. 129 | /// A serie . 130 | /// The retenion policy. 131 | /// TODO: comment 132 | public async Task WriteAsync(string database, Point[] points, string retenionPolicy = "default") 133 | { 134 | var request = new WriteRequest(_influxDbClient.GetFormatter()) 135 | { 136 | Database = database, 137 | Points = points, 138 | RetentionPolicy = retenionPolicy 139 | }; 140 | 141 | var result = await _influxDbClient.Write(NoErrorHandlers, request, ToTimePrecision(TimeUnit.Milliseconds)); 142 | 143 | return result; 144 | } 145 | 146 | /// Execute a query against a database. 147 | /// The name of the database. 148 | /// The query to execute. For language specification please see 149 | /// InfluxDb documentation. 150 | /// A list of Series which matched the query. 151 | /// 152 | public async Task> QueryAsync(string database, string query) 153 | { 154 | InfluxDbApiResponse response = await _influxDbClient.Query(NoErrorHandlers, database, query); 155 | 156 | var queryResult = response.ReadAs(); 157 | 158 | Validate.NotNull(queryResult, "queryResult"); 159 | Validate.NotNull(queryResult.Results, "queryResult.Results"); 160 | 161 | // Apparently a 200 OK can return an error in the results 162 | // https://github.com/influxdb/influxdb/pull/1813 163 | var error = queryResult.Results.Single().Error; 164 | if (error != null) 165 | { 166 | throw new InfluxDbApiException(System.Net.HttpStatusCode.BadRequest, error); 167 | } 168 | 169 | var result = queryResult.Results.Single().Series; 170 | 171 | return result != null ? result.ToList() : new List(); 172 | } 173 | 174 | /// Execute queries against a database. 175 | /// The name of the database. 176 | /// Queries to execute. For language specification please see 177 | /// InfluxDb documentation. 178 | /// A list of Series which matched the queries. 179 | /// 180 | public async Task> QueryAsync(string database, List queries) 181 | { 182 | InfluxDbApiResponse response = await _influxDbClient.Query(NoErrorHandlers, database, queries); 183 | 184 | var queryResult = response.ReadAs(); 185 | 186 | Validate.NotNull(queryResult, "queryResult"); 187 | Validate.NotNull(queryResult.Results, "queryResult.Results"); 188 | 189 | // Apparently a 200 OK can return an error in the results 190 | // https://github.com/influxdb/influxdb/pull/1813 191 | var errors = queryResult.Results.Where(res => res.Error != null).Select(res => res.Error).ToList(); 192 | if (errors.Any()) 193 | { 194 | throw new InfluxDbApiException(System.Net.HttpStatusCode.BadRequest, string.Join(", ", errors)); 195 | } 196 | 197 | var result = queryResult.Results.SelectMany(res => res.Series == null ? new List { new Serie() } : res.Series.DefaultIfEmpty(new Serie())); 198 | 199 | return result.ToList(); 200 | } 201 | 202 | #endregion Basic Querying 203 | 204 | #region Continuous Queries 205 | 206 | /// 207 | /// Describe all contious queries in a database. 208 | /// 209 | /// The name of the database for which all continuous queries should be described. 210 | /// A list of all contious queries. 211 | public async Task> DescribeContinuousQueriesAsync(string database) 212 | { 213 | InfluxDbApiResponse response = await _influxDbClient.GetContinuousQueries(NoErrorHandlers, database); 214 | 215 | return response.ReadAs>(); 216 | } 217 | 218 | /// 219 | /// Delete a continous query. 220 | /// 221 | /// The name of the database for which this query should be deleted. 222 | /// The id of the query. 223 | /// 224 | public async Task DeleteContinuousQueryAsync(string database, int id) 225 | { 226 | return await _influxDbClient.DeleteContinuousQuery(NoErrorHandlers, database, id); 227 | } 228 | 229 | #endregion Continuous Queries 230 | 231 | #region Series 232 | 233 | /// 234 | /// Delete a serie. 235 | /// 236 | /// The database in which the given serie should be deleted. 237 | /// The name of the serie. 238 | /// 239 | public async Task DropSeriesAsync(string database, string serieName) 240 | { 241 | return await _influxDbClient.DropSeries(NoErrorHandlers, database, serieName); 242 | } 243 | 244 | #endregion Series 245 | 246 | #region Clustering 247 | 248 | /// 249 | /// Create a new cluster admin. 250 | /// 251 | /// The name of the new admin. 252 | /// The password for the new admin. 253 | /// 254 | public async Task CreateClusterAdminAsync(string username, string adminPassword) 255 | { 256 | var user = new User { Name = username, Password = adminPassword }; 257 | return await _influxDbClient.CreateClusterAdmin(NoErrorHandlers, user); 258 | } 259 | 260 | /// 261 | /// Delete a cluster admin. 262 | /// 263 | /// The name of the admin to delete. 264 | /// 265 | public async Task DeleteClusterAdminAsync(string username) 266 | { 267 | return await _influxDbClient.DeleteClusterAdmin(NoErrorHandlers, username); 268 | } 269 | 270 | /// 271 | /// Describe all cluster admins. 272 | /// 273 | /// A list of all admins. 274 | public async Task> DescribeClusterAdminsAsync() 275 | { 276 | InfluxDbApiResponse response = await _influxDbClient.DescribeClusterAdmins(NoErrorHandlers); 277 | 278 | return response.ReadAs>(); 279 | } 280 | 281 | /// 282 | /// Update the password of the given admin. 283 | /// 284 | /// The name of the admin for which the password should be updated. 285 | /// The new password for the given admin. 286 | /// 287 | public async Task UpdateClusterAdminAsync(string username, string password) 288 | { 289 | var user = new User { Name = username, Password = password }; 290 | 291 | return await _influxDbClient.UpdateClusterAdmin(NoErrorHandlers, user, username); 292 | } 293 | 294 | #endregion Clustering 295 | 296 | #region Sharding 297 | 298 | /// 299 | /// Describe all existing shardspaces. 300 | /// 301 | /// A list of all 's. 302 | public async Task> GetShardSpacesAsync() 303 | { 304 | InfluxDbApiResponse response = await _influxDbClient.GetShardSpaces(NoErrorHandlers); 305 | 306 | return response.ReadAs>(); 307 | } 308 | 309 | /// 310 | /// Drop a existing ShardSpace from a Database. 311 | /// 312 | /// The name of the database. 313 | /// The name of the ShardSpace to delete. 314 | /// 315 | public async Task DropShardSpaceAsync(string database, string name) 316 | { 317 | return await _influxDbClient.DropShardSpace(NoErrorHandlers, database, name); 318 | } 319 | 320 | /// 321 | /// Create a ShardSpace in a Database. 322 | /// 323 | /// The name of the database. 324 | /// The shardSpace to create in this database 325 | /// 326 | public async Task CreateShardSpaceAsync(string database, ShardSpace shardSpace) 327 | { 328 | return await _influxDbClient.CreateShardSpace(NoErrorHandlers, database, shardSpace); 329 | } 330 | 331 | #endregion Sharding 332 | 333 | #region Users 334 | 335 | /// 336 | /// Create a new regular database user. Without any given permissions the new user is allowed to 337 | /// read and write to the database. The permission must be specified in regex which will match 338 | /// for the series. You have to specify either no permissions or both (readFrom and writeTo) permissions. 339 | /// 340 | /// The name of the database where this user is allowed. 341 | /// The name of the new database user. 342 | /// The password for this user. 343 | /// An array of readFrom and writeTo permissions (in this order) and given in regex form. 344 | /// 345 | public async Task CreateDatabaseUserAsync(string database, string name, string password, params string[] permissions) 346 | { 347 | var user = new User { Name = name, Password = password }; 348 | user.SetPermissions(permissions); 349 | return await _influxDbClient.CreateDatabaseUser(NoErrorHandlers, database, user); 350 | } 351 | 352 | /// 353 | /// Delete a database user. 354 | /// 355 | /// The name of the database the given user should be removed from. 356 | /// The name of the user to remove. 357 | /// 358 | public async Task DeleteDatabaseUserAsync(string database, string name) 359 | { 360 | return await _influxDbClient.DeleteDatabaseUser(NoErrorHandlers, database, name); 361 | } 362 | 363 | /// 364 | /// Describe all database users allowed to acces the given database. 365 | /// 366 | /// The name of the database for which all users should be described. 367 | /// A list of all users. 368 | public async Task> DescribeDatabaseUsersAsync(string database) 369 | { 370 | InfluxDbApiResponse response = await _influxDbClient.DescribeDatabaseUsers(NoErrorHandlers, database); 371 | 372 | return response.ReadAs>(); 373 | } 374 | 375 | /// 376 | /// Update the password and/or the permissions of a database user. 377 | /// 378 | /// The name of the database where this user is allowed. 379 | /// The name of the existing database user. 380 | /// The password for this user. 381 | /// An array of readFrom and writeTo permissions (in this order) and given in regex form. 382 | /// 383 | public async Task UpdateDatabaseUserAsync(string database, string name, string password, params string[] permissions) 384 | { 385 | var user = new User { Name = name, Password = password }; 386 | user.SetPermissions(permissions); 387 | return await _influxDbClient.UpdateDatabaseUser(NoErrorHandlers, database, user, name); 388 | } 389 | 390 | /// 391 | /// Alter the admin privilege of a given database user. 392 | /// 393 | /// The name of the database where this user is allowed. 394 | /// The name of the existing database user. 395 | /// If set to true this user is a database admin, otherwise it isnt. 396 | /// An array of readFrom and writeTo permissions (in this order) and given in regex form. 397 | /// 398 | public async Task AlterDatabasePrivilegeAsync(string database, string name, bool isAdmin, params string[] permissions) 399 | { 400 | var user = new User { Name = name, IsAdmin = isAdmin }; 401 | user.SetPermissions(permissions); 402 | return await _influxDbClient.UpdateDatabaseUser(NoErrorHandlers, database, user, name); 403 | } 404 | 405 | /// 406 | /// Authenticate with the given credentials against the database. 407 | /// 408 | /// The name of the database where this user is allowed. 409 | /// The name of the existing database user. 410 | /// The password for this user. 411 | /// 412 | public async Task AuthenticateDatabaseUserAsync(string database, string user, string password) 413 | { 414 | return await _influxDbClient.AuthenticateDatabaseUser(NoErrorHandlers, database, user, password); 415 | } 416 | 417 | #endregion Users 418 | 419 | #region Other 420 | 421 | /// 422 | /// Ping this InfluxDB. 423 | /// 424 | /// The response of the ping execution. 425 | public async Task PingAsync() 426 | { 427 | var watch = Stopwatch.StartNew(); 428 | 429 | var response = await _influxDbClient.Ping(NoErrorHandlers); 430 | 431 | watch.Stop(); 432 | 433 | return new Pong 434 | { 435 | Version = response.Body, 436 | ResponseTime = watch.Elapsed, 437 | Success = true 438 | }; 439 | } 440 | 441 | /// 442 | /// Force Database compaction. 443 | /// 444 | /// 445 | public async Task ForceRaftCompactionAsync() 446 | { 447 | return await _influxDbClient.ForceRaftCompaction(NoErrorHandlers); 448 | } 449 | 450 | /// 451 | /// List all interfaces influxDB is listening. 452 | /// 453 | /// A list of interface names. 454 | public async Task> InterfacesAsync() 455 | { 456 | InfluxDbApiResponse response = await _influxDbClient.Interfaces(NoErrorHandlers); 457 | 458 | return response.ReadAs>(); 459 | } 460 | 461 | /// 462 | /// Sync the database to the filesystem. 463 | /// 464 | /// true|false if successful. 465 | public async Task SyncAsync() 466 | { 467 | InfluxDbApiResponse response = await _influxDbClient.Sync(NoErrorHandlers); 468 | 469 | return response.ReadAs(); 470 | } 471 | 472 | /// 473 | /// List all servers which are member of the cluster. 474 | /// 475 | /// A list of all influxdb servers. 476 | public async Task> ListServersAsync() 477 | { 478 | InfluxDbApiResponse response = await _influxDbClient.ListServers(NoErrorHandlers); 479 | 480 | return response.ReadAs>(); 481 | } 482 | 483 | /// 484 | /// Remove the given Server from the cluster. 485 | /// 486 | /// The id of the server to remove. 487 | /// 488 | public async Task RemoveServersAsync(int id) 489 | { 490 | return await _influxDbClient.RemoveServers(NoErrorHandlers, id); 491 | } 492 | 493 | public IFormatter GetFormatter() 494 | { 495 | return _influxDbClient.GetFormatter(); 496 | } 497 | 498 | public InfluxVersion GetClientVersion() 499 | { 500 | return _influxDbClient.GetVersion(); 501 | } 502 | 503 | #endregion Other 504 | 505 | #region Helpers 506 | 507 | public IInfluxDb SetLogLevel(LogLevel logLevel) 508 | { 509 | switch (logLevel) 510 | { 511 | case LogLevel.None: 512 | 513 | break; 514 | case LogLevel.Basic: 515 | 516 | break; 517 | case LogLevel.Headers: 518 | 519 | break; 520 | case LogLevel.Full: 521 | break; 522 | } 523 | 524 | return this; 525 | } 526 | 527 | private string ToTimePrecision(TimeUnit timeUnit) 528 | { 529 | switch (timeUnit) 530 | { 531 | case TimeUnit.Seconds: 532 | return "s"; 533 | case TimeUnit.Milliseconds: 534 | return "ms"; 535 | case TimeUnit.Microseconds: 536 | return "u"; 537 | default: 538 | throw new ArgumentException("time precision must be " + TimeUnit.Seconds + ", " + TimeUnit.Milliseconds + " or " + TimeUnit.Microseconds); 539 | } 540 | } 541 | 542 | #endregion Helpers 543 | } 544 | } 545 | --------------------------------------------------------------------------------