public cInfluxDriver(tInfluxConfig NewConfig) { var host = NewConfig.Host; var port = NewConfig.Port; _Token = NewConfig.Token; _Bucket = NewConfig.Bucket; _Organisation = NewConfig.Organisation; var pass = NewConfig.Password; if (host is null) { host = "http://localhost:"; } if (port is null) { port = "8086"; } if (_Token is null || _Token == "") { throw new ArgumentException("No token provided. INFLUXDB_TOKEN must be set to the correct token for access to the Influx DB"); } if (_Bucket is null) { _Bucket = "telemetry"; } if (_Organisation is null) { throw new ArgumentException("No organisation provided. INFLUXDB_ORG must be set to the organisation to use"); } if (pass is null || pass == "") { throw new ArgumentException("No password defined. INFLUXDB_PASSWORD must be set to a valid password to configure the Influx DB"); } // Check for default password if (pass == "defaultpassword_changeme") { Log.Log(enLogLevel.Warn, "** SECURITY WARNING ** : The default user password is being used, this should be changed to prevent compromise."); } // Check for default token if (_Token == "defaulttoken_changeme") { Log.Log(enLogLevel.Warn, "** SECURITY WARNING ** : The default access token is being used, this should be changed to prevent compromise."); } var sb = new StringBuilder(); sb.AppendLine("InfluxDB Driver initialised with:"); sb.AppendLine("Host: " + host); sb.AppendLine("Port: " + port); sb.AppendLine("Token: " + _Token); sb.AppendLine("Bucket: " + _Bucket); sb.AppendLine("Organisation: " + _Organisation); Log.Log(enLogLevel.Info, sb.ToString()); _Client = InfluxDBClientFactory.Create(host + ":" + port, _Token.ToCharArray()); }
private static async Task Read(InfluxDBClient influxDBClient) { var flux = $"from(bucket:\"{BucketName}\") |> range(start: 0)"; var fluxTables = await influxDBClient.GetQueryApi().QueryAsync(flux, OrgId); fluxTables.ForEach(fluxTable => { var fluxRecords = fluxTable.Records; fluxRecords.ForEach(fluxRecord => { var msg = $"{fluxRecord.GetTime()}: {fluxRecord.GetMeasurement()}"; foreach (var(key, value) in fluxRecord.Values) { if (!key.StartsWith('_') && key != "result" && key != "table") { msg += $" {key}:{value}"; } } msg += $" field: {fluxRecord.GetField()}"; Console.WriteLine(msg); }); }); }
public override void Configure(IFunctionsHostBuilder builder) { IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Environment.CurrentDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); IConfigurationSection influxDBConfigurationSection = configuration.GetSection("InfluxDB"); IConfigurationSection featuresConfigurationSection = configuration.GetSection("Features"); IInfluxDBConfiguration influxDBConfiguration = new InfluxDBConfiguration(); IFeaturesConfiguration featuresConfiguration = new FeaturesConfiguration(); influxDBConfigurationSection.Bind(influxDBConfiguration); featuresConfigurationSection.Bind(featuresConfiguration); InfluxDBClientOptions influxDBClientOptions = InfluxDBClientOptions.Builder .CreateNew() .Url(influxDBConfiguration.Url) .AuthenticateToken(influxDBConfiguration.Token.ToCharArray()) .Org(influxDBConfiguration.Organisation) .Bucket(influxDBConfiguration.Bucket) .Build(); InfluxDBClient influxDBClient = InfluxDBClientFactory.Create(influxDBClientOptions); ISensorRepository sensorRepository = new SensorRepository(influxDBClient); builder.Services.AddSingleton <IFeaturesConfiguration>(featuresConfiguration); builder.Services.AddSingleton <ISensorRepository>(sensorRepository); builder.Services.AddSensorService(); builder.Services.AddFeatureService(); }
public MailchimpStatsService(IMailChimpManager mailchimp, InfluxDBClient client, ILogger <MailchimpStatsService> logger) { _mailchimp = mailchimp; _client = client; _logger = logger; }
public DbConnector(InfluxDbSettings settings) { this._settings = settings; this._dbClient = new InfluxDBClient(settings.InfluxUrl.ToString(), settings.UserName, settings.Password); }
private void Initialize() { try { if (_client == null) { char[] password = string.IsNullOrWhiteSpace(_settings.Password) ? null : _settings.Password.ToCharArray(); _client = InfluxDBClientFactory.CreateV1(_settings.Url, _settings.Username, password, _settings.Database, _settings.RetentionPolicy); } if (_writeApi == null) { _writeApi = _client.GetWriteApi(new WriteOptions.Builder().BatchSize(_settings.WriteBatchSize).FlushInterval(_settings.WriteFlushIntervalMillis).Build()); _writeApi.EventHandler += OnWriteApiEvent; } } catch (Exception) { _writeApi?.Dispose(); _writeApi = null; _client?.Dispose(); _client = null; throw; } }
public async Task TestPostBooleanPointAsync() { try { var client = new InfluxDBClient(influxUrl, dbUName, dbpwd); var time = DateTime.Now; var valBool = new InfluxDatapoint <bool> (); valBool.UtcTimestamp = DateTime.UtcNow; valBool.Tags.Add("TestDate", time.ToShortDateString()); valBool.Tags.Add("TestTime", time.ToShortTimeString()); valBool.Fields.Add("Booleanfield", time.Ticks % 2 == 0); valBool.MeasurementName = measurementName; valBool.Precision = TimePrecision.Seconds; var r = await client.PostPointAsync(dbName, valBool); Assert.IsTrue(r, "PostPointAsync retunred false"); } catch (Exception e) { Assert.Fail("Unexpected exception of type {0} caught: {1}", e.GetType(), e.Message); return; } }
public void ConnectInfluxDBClientTest() { using (InfluxDBClient client = new InfluxDBClient(influxUrl, dbUName, dbpwd)) { var temp = client; } }
public static async Task GenerateSensorData(Sensor sensor, InfluxDBClient client) { var range = sensor.Max - sensor.Min; var random = new Random(); var currentValue = (random.NextDouble() * range) + sensor.Min; var modifier = Math.Abs(range / 100.0); using var writeApi = client.GetWriteApi(); var dataCache = new List <PointData>(); Console.WriteLine($"Simulating sensor {sensor.Name} for device {Program.DeviceID} at an interval of {sensor.Interval}ms"); while (true) { currentValue += modifier * Math.Max(random.NextDouble(), 0.6); if (currentValue <= sensor.Min || currentValue >= sensor.Max || random.NextDouble() > Math.Max(Math.Tanh((currentValue - sensor.Min) / range), 0.8)) { modifier *= -1; } dataCache.Add(PointData .Measurement("simulatedValues") .Tag("deviceId", Program.DeviceID) .Field(sensor.Name, currentValue)); if (dataCache.Count > 50) { writeApi.WritePoints(Program.ServerBucket, Program.ServerOrg, dataCache); dataCache.Clear(); } await Task.Delay(sensor.Interval); } }
public async Task TestPostDoublePointAsync() { try { var client = new InfluxDBClient(influxUrl, dbUName, dbpwd); var time = DateTime.Now; var rand = new Random(); var valDouble = new InfluxDatapoint <double> (); valDouble.UtcTimestamp = DateTime.UtcNow; valDouble.Tags.Add("TestDate", time.ToShortDateString()); valDouble.Tags.Add("TestTime", time.ToShortTimeString()); valDouble.Fields.Add("Doublefield", rand.NextDouble()); valDouble.Fields.Add("Doublefield2", rand.NextDouble()); valDouble.MeasurementName = measurementName; valDouble.Precision = TimePrecision.Seconds; var r = await client.PostPointAsync(dbName, valDouble); Assert.IsTrue(r, "PostPointAsync retunred false"); } catch (Exception e) { Assert.Fail("Unexpected exception of type {0} caught: {1}", e.GetType(), e.Message); return; } }
private string GenerateWriteToken(InfluxDBClient createBucketClient, Bucket bucket) { var resource = new PermissionResource { Id = bucket.Id, OrgID = _connectionInfo.OrganizationId, Type = PermissionResource.TypeEnum.Buckets }; var write = new Permission(Permission.ActionEnum.Write, resource); var authorizationRequest = new AuthorizationPostRequest(_connectionInfo.OrganizationId, permissions: new List <Permission> { write }, description: $"{nameof(Permission.ActionEnum.Write)} Token for Bucket '{bucket.Name}' (Serilog)"); string token; try { var authorizationCreated = createBucketClient.GetAuthorizationsApi() .CreateAuthorizationAsync(authorizationRequest) .GetAwaiter().GetResult(); token = authorizationCreated?.Token; } catch (HttpException ex) { SelfLog.WriteLine($"Error while trying to get {_connectionInfo.BucketName} (Org: {_connectionInfo.OrganizationId}), Message : {ex.Message}. Check if Token has enough access to read (if only write to bucket then set to False parameter {_connectionInfo.CreateBucketIfNotExists}) or set AllAccessToken or is active token"); throw new InfluxDbClientCreateBucketException($"Cannot create token for bucket {_connectionInfo.BucketName} with write permissions. Check if Token has enough access or set AllAccessToken or is active", ex); } SelfLog.WriteLine($"Token generated successfully for bucket {bucket.Name}, using it for write operations"); return(token); }
public QueryService(DeviceRenamerService deviceRenamerService) { _client = InfluxDBClientFactory.Create("https://eu-central-1-1.aws.cloud2.influxdata.com", "epLboaxSf0aYI6FBjeAoFb-RXykUUvwoeTt62Fc6rT414BD94zO6-2KPu6NbM5MuMdwpfp5zEK3dvnHjIKAynQ==" .ToCharArray()); this.deviceRenamerService = deviceRenamerService; }
public async Task TestPostPointsAsync_FromObject_AutogenRetention() { try { var client = new InfluxDBClient(influxUrl, dbUName, dbpwd); var retention = new InfluxRetentionPolicy() { Name = "autogen", DBName = dbName, Duration = TimeSpan.FromMinutes(0), IsDefault = true }; var points = Enumerable.Range(0, 10).Select(i => new PointObjectWithObjectRetention { Measurement = "RetentionTest", Time = DateTime.UtcNow.AddDays(-i), Retention = retention, Precision = TimePrecision.Milliseconds, StringTag = "FromObject", IntTag = DataGen.RandomInt(), StringField = DataGen.RandomString(), DoubleField = DataGen.RandomDouble(), IntField = DataGen.RandomInt(), BoolField = i % 2 == 0, }); var r = await client.PostPointsAsync(dbName, points); Assert.IsTrue(r, "PostPointsAsync returned false"); } catch (Exception e) { Assert.Fail($"Unexpected exception of type {e.GetType()} caught: {e.Message}"); return; } }
public async Task TestPostObjectPointAsync() { try { var client = new InfluxDBClient(influxUrl, dbUName, dbpwd); var point = new PointObjectWithStringRetention { Time = DateTime.UtcNow, Measurement = measurementName, Precision = TimePrecision.Seconds, StringTag = "FromObject", IntTag = DataGen.RandomInt(), StringField = DataGen.RandomString(), DoubleField = DataGen.RandomDouble(), IntField = DataGen.RandomInt(), BoolField = true, }; var r = await client.PostPointAsync(dbName, point); Assert.IsTrue(r, "PostPointAsync returned false"); } catch (Exception e) { Assert.Fail($"Unexpected exception of type {e.GetType()} caught: {e.Message}"); return; } }
private static async Task <bool> VerifyDatabaseAsync(InfluxDBClient client, string DBName) { try { //verify DB exists, create if not var dbNames = await client.GetInfluxDBNamesAsync(); if (dbNames.Contains(DBName)) { return(true); } else { var filter = settings.FileFormat == FileFormats.Perfmon ? settings.PerfmonFile.Filter : settings.GenericFile.Filter; if (filter == Filters.Measurement || filter == Filters.Field) { Logger.LogLine(LogLevel.Info, "Measurement/Field filtering is not applicable for new database!!"); filter = Filters.None; } return(await client.CreateDatabaseAsync(DBName)); } } catch (Exception e) { Logger.LogLine(LogLevel.Info, "Unexpected exception of type {0} caught: {1}", e.GetType(), e.Message); } return(false); }
public DeviceViewModel() { _tagViewModel = new TagViewModel(); var influxHost = Environment.GetEnvironmentVariable("INFLUX_HOST"); var influxKey = Environment.GetEnvironmentVariable("INFLUX_KEY"); _influxOrg = Environment.GetEnvironmentVariable("INFLUX_ORG"); _influxBucket = Environment.GetEnvironmentVariable("INFLUX_BUCKET"); if (null == influxHost || null == influxKey || null == _influxOrg || null == _influxBucket) { Console.WriteLine("The necessary InfluxDB details have not been set in environment variables."); Console.WriteLine("Please see the project documentation for details: https://github.com/balenalabs-incubator/balenaLocating"); return; } try { _influxDBClient = InfluxDBClientFactory.Create(influxHost, influxKey.ToCharArray()); _influxDBClient.SetLogLevel(LogLevel.Body); } catch (Exception ex) { Debug.WriteLine("Influx exception: " + ex); return; } }
public async Task TestPostPointsAsync_DefaultTimePrecision() { try { var client = new InfluxDBClient(influxUrl, dbUName, dbpwd); var time = DateTime.Now; var TestDate = time.ToShortDateString(); var TestTime = time.ToShortTimeString(); var points = new List <IInfluxDatapoint>(); for (var i = 0; i < 10; i++) { await Task.Delay(1); var point = new InfluxDatapoint <long>(); point.MeasurementName = "DefaultPrecisionTest"; point.Tags.Add("TestDate", TestDate); point.Tags.Add("TestTime", TestTime); point.Fields.Add("Val", i); points.Add(point); } var r = await client.PostPointsAsync(dbName, points); Assert.IsTrue(r, "PostPointsAsync retunred false"); } catch (Exception e) { Assert.Fail($"Unexpected exception of type {e.GetType()} caught: {e.Message}"); return; } }
public async Task <bool> AddRangeAsync(IEnumerable <StockSymbol> stockSymbols) { using (InfluxDBClient client = await influxContext.GetDatabaseClient()) { List <InfluxDatapoint <InfluxValueField> > dataPoints = new List <InfluxDatapoint <InfluxValueField> >(); foreach (StockSymbol stockSymbol in stockSymbols) { InfluxDatapoint <InfluxValueField> point = new InfluxDatapoint <InfluxValueField>(); point.UtcTimestamp = stockSymbol.Date; point.MeasurementName = MeasureName; point.Precision = TimePrecision.Hours; point.Tags.Add("SymbolName", stockSymbol.Name); point.Fields.Add("Date", new InfluxValueField(stockSymbol.Date.ToString("MM-dd-yyyy"))); point.Fields.Add("UserName", new InfluxValueField(stockSymbol.UserName)); point.Fields.Add("SymbolName", new InfluxValueField(stockSymbol.Name)); point.Fields.Add("Open", new InfluxValueField(stockSymbol.Open)); point.Fields.Add("Close", new InfluxValueField(stockSymbol.Close)); point.Fields.Add("High", new InfluxValueField(stockSymbol.High)); point.Fields.Add("Low", new InfluxValueField(stockSymbol.Low)); point.Fields.Add("Volume", new InfluxValueField(stockSymbol.Volume)); dataPoints.Add(point); } return(await client.PostPointsAsync(influxContext.DatabaseName, dataPoints)); } }
public async Task TestGetContinuousQueriesAsync() { var client = new InfluxDBClient(influxUrl, dbUName, dbpwd); var cqList = await client.GetContinuousQueriesAsync(); Assert.IsNotNull(cqList, "GetContinuousQueriesAsync returned Null"); }
public async Task TestPostPointAsyncNonDefaultRetention() { try { var client = new InfluxDBClient(influxUrl, dbUName, dbpwd); var time = DateTime.Now; var rand = new Random(); var valMixed = new InfluxDatapoint <InfluxValueField>(); valMixed.UtcTimestamp = DateTime.UtcNow; valMixed.Tags.Add("TestDate", time.ToShortDateString()); valMixed.Tags.Add("TestTime", time.ToShortTimeString()); valMixed.Fields.Add("Doublefield", new InfluxValueField(rand.NextDouble())); valMixed.Fields.Add("Stringfield", new InfluxValueField(DataGen.RandomString())); valMixed.Fields.Add("Boolfield", new InfluxValueField(true)); valMixed.Fields.Add("Int Field", new InfluxValueField(rand.Next())); valMixed.MeasurementName = measurementName; valMixed.Precision = TimePrecision.Seconds; valMixed.Retention = new InfluxRetentionPolicy() { Duration = TimeSpan.FromHours(6) }; var r = await client.PostPointAsync(dbName, valMixed); Assert.IsTrue(r && valMixed.Saved, "PostPointAsync retunred false"); } catch (Exception e) { Assert.Fail($"Unexpected exception of type {e.GetType()} caught: {e.Message}"); return; } }
public async Task TestGetRetentionPoliciesAsync() { var client = new InfluxDBClient(influxUrl, dbUName, dbpwd); var policies = await client.GetRetentionPoliciesAsync(dbName); Assert.IsNotNull(policies, "GetRetentionPoliciesAsync returned Null"); }
public async Task TestPostPointsAsync_DifferentTypeFailure() { var client = new InfluxDBClient(influxUrl, dbUName, dbpwd); var points = new List <IInfluxDatapoint>(); var firstPoint = new InfluxDatapoint <int>(); firstPoint.UtcTimestamp = DateTime.UtcNow; firstPoint.Fields.Add("value", 1); firstPoint.MeasurementName = "SameKeyDifferentType"; firstPoint.Precision = TimePrecision.Milliseconds; points.Add(firstPoint); var secondPoint = new InfluxDatapoint <double>(); secondPoint.UtcTimestamp = DateTime.UtcNow; secondPoint.Fields.Add("value", 123.1234); secondPoint.MeasurementName = "SameKeyDifferentType"; secondPoint.Precision = TimePrecision.Milliseconds; points.Add(secondPoint); var r = await AssertEx.ThrowsAsync <InfluxDBException>(() => client.PostPointsAsync(dbName, points)); }
public Task <List <TelemetryDataDto> > GetTelemetryLatest(Guid deviceId) { InfluxDBClient _taos = _taospool.Get(); var query = _taos.GetQueryApi(); var v = query.QueryAsync(@$ " from(bucket: " "{_bucket}" ") |> range(start: {_latest})
protected override void ActivateInternal() { var setting = Resolver.GetInstance <InfluxDbSetting>(); var threadManager = Resolver.GetInstance <IThreadManager>(); var schedulingService = Resolver.GetInstance <ISchedulingService>(); var loggerFactory = Resolver.GetInstance <ILogManager>(); Logger.Info("Establishing connection to server [{0}]", setting.Server); var influxDbClient = new InfluxDBClient(setting.Server, setting.Username, setting.Password); var upload = new InfluxDbUpload(loggerFactory.GetLogger(typeof(InfluxDbUpload)), influxDbClient, threadManager, schedulingService); var uploadRegistration = new SingletonRegistration <IInfluxDbUpload>(upload); ConfigurationResolver.AddRegistration(uploadRegistration); var read = new InfluxDbRead(influxDbClient); var readRegistration = new SingletonRegistration <IInfluxDbRead>(read); ConfigurationResolver.AddRegistration(readRegistration); var management = new InfluxDbManagement(influxDbClient, loggerFactory.GetLogger(typeof(InfluxDbManagement))); var managementRegistration = new SingletonRegistration <IInfluxDbManagement>(management); ConfigurationResolver.AddRegistration(managementRegistration); }
public async Task InitAsync(string influxUrl, string influxUName, string influxUPwd, string influxDbName, long influxRetentionHours) { if (_hasInited) { return; } _hasInited = true; //保存初始化的参数 _influxUrl = influxUrl; _influxUName = influxUName; _influxUPwd = influxUPwd; _influxDbName = influxDbName; _influxRetentionHours = influxRetentionHours; try { influxClient = new InfluxDBClient(influxUrl, influxUName, influxUPwd); //检查数据库是否存在,如果数据库不存在,则新建数据库,并且新建数据保留策略 await CreateDatabaseAndRetentionPolicyAsync(influxDbName); } catch (Exception ex) { _logger.LogError("初始化InfluxDB失败,原因:" + ex.Message); _logger.LogError("程序即将退出..."); Environment.Exit(0); } }
private async Task <Authorization> CreateAuthorizationToken(InfluxDBClient influxDBClient, Bucket bucket) { var resource = new PermissionResource { Id = bucket.Id, OrgID = bucket.OrgID, Type = PermissionResource.TypeEnum.Buckets }; var read = new Permission(Permission.ActionEnum.Read, resource); var write = new Permission(Permission.ActionEnum.Write, resource); var authorizations = await influxDBClient.GetAuthorizationsApi().FindAuthorizationsAsync(); var authorization = authorizations.FirstOrDefault(a => a.OrgID == bucket.OrgID && a.User == _options.User); if (authorization == null) { authorization = await influxDBClient.GetAuthorizationsApi() .CreateAuthorizationAsync(new Authorization( bucket.OrgID, new List <Permission> { read, write } )); } return(authorization); }
private async void ReloadChart_influx(object Chartdata) { ChartData chart = (ChartData)Chartdata; chart.set.Clear(); chart.cur.Clear(); chart.onff.Clear(); chart.Rectangles.Clear(); chart.onfftime = 0; InfluxDBClient client = head.getClient(); var tables = await DB_influx.ExcuteInflux(client, DB_influx.GetQuery(chart.searches)); if (tables.Count == 0) { MessageBox.Show("데이터를 찾을 수 없습니다."); return; } ChartDataInput(ref chart, tables); int index = Vms.IndexOf(chart); Vms.Remove(chart); chart.ReFresh(); Vms.Insert(index, chart); }
// CHART 생성 함수 private async void CreateChart_influx(object Searchdata) { SearchData data = (SearchData)Searchdata; var chart = new ChartData(head.val); InfluxDBClient client = head.getClient(); //var tables = await DB_influx.ExcuteInflux(client, DB_influx.GetQuery_Group(data)); var tables = await DB_influx.ExcuteInflux(client, DB_influx.GetQuery(data)); if (tables.Count == 0) { MessageBox.Show($"[ROOM:{data.ROOM_ID}] 데이터를 찾을 수 없습니다."); return; } Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { Vms.Add(chart); ChartDataInput(ref chart, tables); chart.searches = new SearchData(data); chart.Drawing(); })); }
public async Task TestGetServerVersionAsync() { var client = new InfluxDBClient(influxUrl, dbUName, dbpwd); var version = await client.GetServerVersionAsync(); Assert.IsFalse(String.IsNullOrWhiteSpace(version)); Assert.IsTrue(version != "Unknown"); }
public InfluxConnector(String server, String _token, String _bucket, String _org) { token = _token; bucket = _bucket; org = _org; client = InfluxDBClientFactory.Create(server, token.ToCharArray()); }
public void PerformanceTest() { var client = new InfluxDBClient("192.168.1.100", 8086, "root", "root", "PerfTests"); // Create a database for this test List<string> databaseList = client.GetDatabaseList(); if (!databaseList.Contains("PerfTests")) { client.CreateDatabase("PerfTests"); } client.Query("DROP SERIES foo"); // Create var serie = new Serie {Name = "foo", ColumnNames = new[] {"value", "value_str"}}; var series = new List<Serie> {serie}; const int N = 10000; for (int i = 0; i < N; i++) { serie.Points.Add(new object[] {i, "yoyo"}); } // Measure insert Stopwatch chrono = Stopwatch.StartNew(); client.Insert(series); chrono.Stop(); Debug.Write("Insert Elapsed:" + chrono.Elapsed.TotalMilliseconds + " ms" + Environment.NewLine); // Ugly Thread.Sleep(1000); // Give some time to the database to process insert. There must be a better way to do this // Make sure write was succesful List<Serie> result = client.Query("select count(value) from foo"); Assert.AreEqual(N, result[0].Points[0][1]); // Measure query chrono.Restart(); result = client.Query("select * from foo"); chrono.Stop(); Assert.AreEqual(N, result[0].Points.Count); Debug.Write("Query Elapsed:" + chrono.Elapsed.TotalMilliseconds + " ms" + Environment.NewLine); // Clean up client.DeleteDatabase("PerfTests"); }