Example #1
0
 public void Write(string data)
 {
     using (WriteApi writeApi = _client.GetWriteApi())
     {
         writeApi.WriteRecord(DB_BUCKET, DB_ORGANIZATION, InfluxDB.Client.Api.Domain.WritePrecision.Ms, data);
     }
 }
        public void DisposeCallFromInfluxDbClientToWriteApi()
        {
            var writeApi = _influxDbClient.GetWriteApi();

            Assert.False(writeApi.Disposed);
            _influxDbClient.Dispose();
            Assert.True(writeApi.Disposed);
        }
        public void WriteData()
        {
            var point = PointData
                        .Measurement("influxData")
                        .Tag("assetId", "1")
                        .Field("used_percent", 23.43234543)
                        .Timestamp(DateTime.UtcNow, WritePrecision.Ns);

            using (var writeApi = client.GetWriteApi())
            {
                writeApi.WritePoint(bucket, org, point);
            }
        }
Example #4
0
 public void Write(string bucket, string org, PointData point)
 {
     using (var writeApi = client.GetWriteApi())
     {
         writeApi.WritePoint(bucket, org, point);
     }
 }
Example #5
0
        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 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);
            }
        }
Example #7
0
        public void Save(string id, string name, double amount, string measure)
        {
            using var writeApi = _influxDbClient.GetWriteApi();
            var health = _influxDbClient.HealthAsync().GetAwaiter().GetResult();

            PointData point = null;

            if (measure == "%")
            {
                point = PointData.Measurement("sensor")
                        .Tag("id", id)
                        .Tag("name", name)
                        .Field("Humidity", amount)
                        .Timestamp(DateTime.UtcNow, WritePrecision.S);
            }
            else if (measure == "°C")
            {
                point = PointData.Measurement("sensor")
                        .Tag("id", id)
                        .Tag("name", name)
                        .Field("Temperature", amount)
                        .Timestamp(DateTime.UtcNow, WritePrecision.S);
            }

            if (point != null)
            {
                writeApi.WritePoint("AnimusHeart", "AnimusHeart", point);
            }
        }
Example #8
0
        static void update(EnvAgencyRainfall api, EnvAgencyRainfall.GetStationsData stations, InfluxDBClient influxDBClient)
        {
            // Write Data to influx
            using (var writeApi = influxDBClient.GetWriteApi())
            {
                foreach (var s in stations.items)
                {
                    if (s.measures == null || s.measures.Count == 0)
                    {
                        continue;
                    }
                    var rainfallMeasure = s.measures.Find(x => x.parameter.Equals("rainfall"));
                    if (rainfallMeasure == null)
                    {
                        continue;
                    }

                    var measurement = api.GetLatestMeasurement(s.stationReference);
                    if (measurement == null)
                    {
                        // TODO: One instance of this is a rainfall sensor returning value: [0, 0.4], as array instead of single value
                        // There doesn't appear to be anything in the api to signify this, will need to read the docs to tell if it's
                        // an actual error. No big deal really just that sensor won't be read
                        continue;
                    }
                    if (measurement.items != null && measurement.items.Count > 0)
                    {
                        foreach (var i in measurement.items)
                        {
                            if (!i.parameter.Equals("rainfall"))
                            {
                                continue;
                            }

                            var absReading  = i.latestReading.value;
                            var mmPerPeriod = absReading;
                            if (!i.unit.Equals("http://qudt.org/1.1/vocab/unit#Millimeter"))
                            {
                                // Again TODO - Ignore for now as most sensors seem to be mm based.
                                // Should just scale up and we'd be good
                                continue;
                            }
                            var mmPerHour = mmPerPeriod * (3600.0 / i.period);

                            Console.WriteLine($"{s.stationReference} : {s.lat},{s.lon} : {mmPerHour}mm/h");
                            /// ///////////////////////////////////////////

                            // TODO: Take actual timestamp from rainfall reading. This is currently just polling, so less accurate/etc
                            var point = PointData.Measurement("rainfall")
                                        .Tag("location", s.stationReference)
                                        .Field("value", mmPerHour)
                                        .Timestamp(DateTime.UtcNow, WritePrecision.S);

                            writeApi.WritePoint(BucketName, OrgName, point);
                        }
                    }
                }
            }
        }
Example #9
0
        public void ReportError()
        {
            var pointdata = PointData.Measurement("error");

            pointdata.Field("message", "TODO: use error messages :)");
            pointdata.Timestamp(DateTime.UtcNow, InfluxDB.Client.Api.Domain.WritePrecision.Ms);

            errors_client.GetWriteApi().WritePoint(pointdata);
        }
Example #10
0
        public void ReportWeight(string tag, int weight)
        {
            var pointdata = PointData.Measurement("weight");

            pointdata.Tag("vegetable", tag);
            pointdata.Field("weight", weight);
            pointdata.Timestamp(DateTime.UtcNow, InfluxDB.Client.Api.Domain.WritePrecision.Ms);

            data_client.GetWriteApi().WritePoint(pointdata);
        }
Example #11
0
        public void WriteData(Bot bot, Mem mem)
        {
            mem = new Mem {
                Host = "host1", UsedPercent = 23.43234543, Time = DateTime.UtcNow
            };

            using (var writeApi = _client.GetWriteApi())
            {
                writeApi.WriteMeasurement(bot.Bucket, bot.Org, WritePrecision.Ms, mem);
            }
        }
Example #12
0
        public void LogLevelWithQueryString()
        {
            var writer = new StringWriter();

            Trace.Listeners.Add(new TextWriterTraceListener(writer));

            _client.SetLogLevel(LogLevel.Headers);

            MockServer
            .Given(Request.Create().WithPath("/api/v2/write").UsingPost())
            .RespondWith(CreateResponse("{}"));

            using (var writeApi = _client.GetWriteApi())
            {
                writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
                                     "h2o_feet,location=coyote_creek water_level=1.0 1");
            }

            StringAssert.Contains("org=org1", writer.ToString());
            StringAssert.Contains("bucket=b1", writer.ToString());
            StringAssert.Contains("precision=ns", writer.ToString());
        }
Example #13
0
        private async void QueueUpdate(QueueCountEventArgs e, string queue)
        {
            await CheckInflux();

            using var db = _influxDb.GetWriteApi();
            var datapoint = new DataPoint()
            {
                Count = e.QueueCount,
                Queue = queue
            };

            db.WriteMeasurement("shoko", "default", WritePrecision.Ms, datapoint);
        }
Example #14
0
        public void GzipDisabledWrite()
        {
            _client.DisableGzip();

            MockServer
            .Given(Request.Create().UsingPost())
            .RespondWith(CreateResponse(""));

            var writeApi = _client.GetWriteApi();
            var listener = new WriteApiTest.EventListener(writeApi);

            writeApi.WriteRecord("my-bucket", "my-org", WritePrecision.Ns,
                                 "h2o_feet,location=coyote_creek water_level=1.0 1");
            writeApi.Flush();
            listener.WaitToSuccess();

            var requestEntry = MockServer.LogEntries.Last();

            Assert.AreEqual($"{MockServerUrl}/api/v2/write?org=my-org&bucket=my-bucket&precision=ns",
                            requestEntry.RequestMessage.Url);
            Assert.AreEqual("identity", requestEntry.RequestMessage.Headers["Content-Encoding"].First());
            Assert.AreEqual("identity", requestEntry.RequestMessage.Headers["Accept-Encoding"].First());
        }
Example #15
0
        public SensorDataModel UpdateSensor(SensorDataModel sensorData)
        {
            using (var writeApi = _infux.GetWriteApi())
            {
                var point = PointData.Measurement("moisture")
                            .Tag("device", sensorData.Device)
                            .Field("value", sensorData.Reading)
                            .Timestamp(DateTime.UtcNow, WritePrecision.Ns);

                writeApi.WritePoint("Sensors", "Droppy", point);
            }

            return(sensorData);
        }
Example #16
0
        private NightFluxConnection(Configuration configuration)
        {
            Configuration = configuration;
            InfluxClient  = InfluxDBClientFactory.Create(Configuration.InfluxUrl, Configuration.InfluxToken.ToCharArray());
            var wo = WriteOptions.CreateNew()
                     .BatchSize(8192)
                     .WriteScheduler(new NewThreadScheduler())
                     .RetryInterval(750)
                     .JitterInterval(136)
                     .FlushInterval(1000)
                     .Build();

            InfluxWriteApi = InfluxClient.GetWriteApi(wo);
        }
Example #17
0
        public static void insertDetection(Detection detectionInflux, InfluxDBClient influxDBClient, string bucket, string org)
        {
            using (var writeApi = influxDBClient.GetWriteApi())
            {
                try {
                    var point = PointData.Measurement("detection")
                                .Field("SensorId", (double)detectionInflux.SensorId)
                                .Field("ScooterId", (double)detectionInflux.ScooterId)
                                .Timestamp(DateTime.UtcNow.AddSeconds(-10), WritePrecision.Ns);

                    writeApi.WriteRecord(bucket, org, WritePrecision.Ns, "detection, sensor_id=1, scooter_id=2");
                }
                catch (Exception e) { Console.WriteLine(e.Message); }
            }
        }
Example #18
0
        public bool WriteToDB(cTelemetryEntry TelemetryEntry, string SatName)
        {
            var point = PointData
                        .Measurement("mem")
                        .Tag("host", SatName + "-ID" + TelemetryEntry.Id.ToString("00"))
                        .Field("value", TelemetryEntry.Value)
                        .Timestamp(TelemetryEntry.Timestamp, WritePrecision.Ns);

            using (var writeApi = _Client.GetWriteApi())
            {
                writeApi.WritePoint(_Bucket, _Organisation, point);
            }

            return(true);
        }
Example #19
0
            public ClientV2(List <CommandOption> options, WriteOptions writeOptions) : base(options, InfluxDb2Bucket, InfluxDb2Url, InfluxDb2Token)
            {
                if (writeOptions == null)
                {
                    var batchSize     = int.Parse(Benchmark.GetOptionValue(GetOption(options, "batchSize"), "50000"));
                    var flushInterval = int.Parse(Benchmark.GetOptionValue(GetOption(options, "flushInterval"), "10000"));
                    writeOptions = WriteOptions.CreateNew().BatchSize(batchSize).FlushInterval(flushInterval).Build();
                }
                InfluxDBClientOptions opts = InfluxDBClientOptions.Builder.CreateNew()
                                             .Url(InfluxDb2Url)
                                             .AuthenticateToken(InfluxDb2Token.ToCharArray())
                                             .LogLevel(LogLevel.Headers).Build();

                _client   = InfluxDBClientFactory.Create(opts);
                _writeApi = _client.GetWriteApi(writeOptions);
            }
        /// <inheritdoc />
        /// <summary>
        /// Emit a batch of log events, running asynchronously.
        /// </summary>
        /// <param name="events">The events to emit.</param>
        /// <remarks>Override either <see cref="M:Serilog.Sinks.PeriodicBatching.PeriodicBatchingSink.EmitBatch(System.Collections.Generic.IEnumerable{Serilog.Events.LogEvent})" /> or <see cref="M:Serilog.Sinks.PeriodicBatching.PeriodicBatchingSink.EmitBatchAsync(System.Collections.Generic.IEnumerable{Serilog.Events.LogEvent})" />,
        /// not both.</remarks>
        protected override void EmitBatch(IEnumerable <LogEvent> events)
        {
            if (events == null)
            {
                throw new ArgumentNullException(nameof(events));
            }

            var logEvents = events as List <LogEvent> ?? events.ToList();
            var points    = new List <PointData>(logEvents.Count);

            foreach (var logEvent in logEvents)
            {
                // Create point data object
                var point = PointData.Measurement(_source);

                // Add tags
                point = point.Tag("level", logEvent.Level.ToString());
                point = point.Tag("hostname", Environment.MachineName);
                if (logEvent.Exception != null)
                {
                    point = point.Tag("exceptionType", logEvent.Exception.GetType().Name);
                }
                if (logEvent.MessageTemplate != null)
                {
                    point = point.Tag("messageTemplate", logEvent.MessageTemplate.Text);
                }

                // Add fields
                foreach (var property in logEvent.Properties)
                {
                    point = point.Field(property.Key, property.Value.ToString());
                }
                point = point.Field("message", logEvent.RenderMessage(_formatProvider));

                // Set the log event timestamp
                point = point.Timestamp(DateTime.UtcNow, InfluxDB.Client.Api.Domain.WritePrecision.Ns);

                // Add a point in the list of points
                points.Add(point);
            }

            // Send log events to InfluxDB instance.
            using var writeApi = _influxDbClient.GetWriteApi();
            writeApi.WritePoints(_connectionInfo.Bucket, _connectionInfo.Organization, points);
        }
Example #21
0
        public void WriteRoomData(HeatHub hub)
        {
            using (var writeApi = client.GetWriteApi())
            {
                foreach (var room in hub.Room)
                {
                    if (room.CalculatedTemperature < -1000.0)
                    {
                        this.logger.LogWarning("{roomName} is not reporting temperature ({reportedTemp}/{alexaTemp}).", room.Name, room.CalculatedTemperature, room.RoundedAlexaTemperature);
                        continue;
                    }

                    writeApi.WriteMeasurement(this.options.BucketId, this.options.OrgId, WritePrecision.S, room.AsRoomDataMeasurement());
                }

                writeApi.Flush();
            }
        }
Example #22
0
        /// <summary>
        /// Scrittura telemetria su database
        /// </summary>
        /// <param name="jsonTelemetry">Telemetria in formato json</param>
        /// <returns></returns>
        public async Task WriteData(String jsonTelemetry)
        {
            try
            {
                //deserializzazione stringa json in dizionario
                Dictionary <string, object> values = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonTelemetry);

                using (var writeApi = client.GetWriteApi())
                {
                    //ottengo id della macchina a partire dalla telemetria
                    var machine_id = values.First(u => u.Key.Equals("machine_id"));

                    //COSTRUZIONE NUOVA ENTRY (POINT)
                    //Questa entry verrĂ  inserita nella serie (tabella/measurement) denominata dal'identificativo
                    //della macchina (machine_id)

                    var point = PointData.Measurement(machine_id.Value.ToString());
                    values.Remove(machine_id.Key);

                    foreach (KeyValuePair <string, object> kv in values)
                    {
                        if (kv.Key == "ts")
                        {
                            point = point.Timestamp(Convert.ToInt64(kv.Value), WritePrecision.Ms);
                        }
                        else
                        {
                            point = point.Field(kv.Key, Convert.ToInt64(kv.Value));
                        }
                    }

                    //scrittura su db
                    writeApi.WritePoint(point);
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("!ERROR: {0}", e.ToString());
            }
        }
Example #23
0
 public InfluxDbClientWriter(InfluxDBClient client, BufferedChannelOptions options)
 {
     _api     = client.GetWriteApi();
     _channel = new BufferedChannel <PointData>(options);
     _channel.RegisterConsumer(SendDataPoints);
 }
Example #24
0
        public static async Task Example(InfluxDBClient influxDB)
        {
            var organizationClient = influxDB.GetOrganizationsApi();

            var medicalGMBH = await organizationClient
                              .CreateOrganization("Medical Corp " +
                                                  DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
                                                                           CultureInfo.InvariantCulture));


            //
            // Create New Bucket with retention 1h
            //
            var temperatureBucket = await influxDB.GetBucketsApi().CreateBucket("temperature-sensors", medicalGMBH.Id);

            //
            // Add Permissions to read and write to the Bucket
            //
            var resource = new PermissionResource
            {
                Type = PermissionResource.TypeEnum.Buckets, OrgID = medicalGMBH.Id, Id = temperatureBucket.Id
            };
            var readBucket = new Permission
            {
                Resource = resource,
                Action   = Permission.ActionEnum.Read
            };

            var writeBucket = new Permission
            {
                Resource = resource,
                Action   = Permission.ActionEnum.Write
            };

            var authorization = await influxDB.GetAuthorizationsApi()
                                .CreateAuthorization(medicalGMBH, new List <Permission> {
                readBucket, writeBucket
            });

            Console.WriteLine($"The token to write to temperature-sensors bucket is: {authorization.Token}");

            influxDB.Dispose();

            //
            // Create new client with specified authorization token
            //

            influxDB = InfluxDBClientFactory.Create("http://localhost:9999", authorization.Token.ToCharArray());

            var writeOptions = WriteOptions
                               .CreateNew()
                               .BatchSize(5000)
                               .FlushInterval(1000)
                               .JitterInterval(1000)
                               .RetryInterval(5000)
                               .Build();

            //
            // Write data
            //
            using (var writeClient = influxDB.GetWriteApi(writeOptions))
            {
                //
                // Write by POCO
                //
                var temperature = new Temperature {
                    Location = "south", Value = 62D, Time = DateTime.UtcNow
                };
                writeClient.WriteMeasurement("temperature-sensors", medicalGMBH.Id, WritePrecision.Ns, temperature);

                //
                // Write by Point
                //
                var point = Point.Measurement("temperature")
                            .Tag("location", "west")
                            .Field("value", 55D)
                            .Timestamp(DateTime.UtcNow.AddSeconds(-10), WritePrecision.Ns);
                writeClient.WritePoint("temperature-sensors", medicalGMBH.Id, point);

                //
                // Write by LineProtocol
                //
                var record = "temperature,location=north value=60.0";
                writeClient.WriteRecord("temperature-sensors", medicalGMBH.Id, WritePrecision.Ns, record);

                writeClient.Flush();
                Thread.Sleep(2000);
            }

            //
            // Read data
            //
            var fluxTables = await influxDB.GetQueryApi().Query("from(bucket:\"temperature-sensors\") |> range(start: 0)", medicalGMBH.Id);

            fluxTables.ForEach(fluxTable =>
            {
                var fluxRecords = fluxTable.Records;
                fluxRecords.ForEach(fluxRecord =>
                {
                    Console.WriteLine($"{fluxRecord.GetTime()}: {fluxRecord.GetValue()}");
                });
            });


            influxDB.Dispose();
        }
Example #25
0
        private void WriteToDb()
        {
            if (dbClient != null)
            {
                try
                {
                    Log.Trace("WriteToDb");
                    var data     = OverviewData.GetOverviewData();
                    var dbConfig = WorkersManager.GetWorkersManager().Config;
                    var point    = Point.Measurement("air")
                                   .Tag("location", dbConfig.Location != null ? dbConfig.Location : "prosek")
                                   .Tag("device_id", dbConfig.DeviceId);
                    int validFields = 0;
                    if (!double.IsNaN(data.CurrentTemperature))
                    {
                        point.Field("temperature", data.CurrentTemperature);
                        ++validFields;
                    }
                    if (!double.IsNaN(data.CurrentPressure))
                    {
                        point.Field("pressure", data.CurrentPressure);
                        ++validFields;
                    }
                    if (!double.IsNaN(data.CurrentHumidity))
                    {
                        point.Field("humidity", data.CurrentHumidity);
                        ++validFields;
                    }
                    if (validFields > 0)
                    {
                        using (var dbWriteApi = dbClient.GetWriteApi())
                        {
                            dbWriteApi.EventHandler += DbWriteApi_EventHandler;
                            dbWriteApi.WritePoint(dbConfig.Bucket, dbConfig.OrgId, point);
                            dbWriteApi.Flush();
                        }

                        if (delay != originalDelay)
                        {
                            delay = originalDelay;
                            Log.Info($"Restoring delay to {delay}");
                        }
                    }
                    else
                    {
                        Log.Debug("InfluxDbWorker:WriteToDb - nothing to write, all values are invalid");
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("Db Write error", ex);
                    OnStatusChanged("DB Write Error: " + ex.Message);
                    //probably temporarly net down or db error, prolong delay to not overload with exception
                    if (delay == originalDelay)
                    {
                        delay *= 5;
                        Log.Info($"Prolonging delay to {delay}");
                    }
                }
            }
        }
        public async Task CreateMonitoringAndAlerting()
        {
            MockServer
            .Given(Request.Create().UsingGet())
            .RespondWith(CreateResponse("{}", "application/json"));

            MockServer
            .Given(Request.Create().UsingPost())
            .RespondWith(CreateResponse("{}", "application/json"));

            var org = (await _client.GetOrganizationsApi().FindOrganizationsAsync())
                      .First(organization => organization.Name.Equals("my-org"));

            var checksApi = _client.GetChecksApi();
            var notificationEndpointsApi = _client.GetNotificationEndpointsApi();
            var notificationRulesApi     = _client.GetNotificationRulesApi();

            var checks = await checksApi.FindChecksAsync(org.Id, new FindOptions());

            foreach (var delete in checks._Checks.Where(ne => ne.Name.EndsWith("-IT")))
            {
                await checksApi.DeleteCheckAsync(delete);
            }

            var rules = await notificationRulesApi.FindNotificationRulesAsync(org.Id, new FindOptions());

            foreach (var delete in rules._NotificationRules.Where(ne => ne.Name.EndsWith("-IT")))
            {
                await notificationRulesApi.DeleteNotificationRuleAsync(delete);
            }

            var endpoints = await notificationEndpointsApi.FindNotificationEndpointsAsync(org.Id, new FindOptions());

            foreach (var delete in endpoints._NotificationEndpoints.Where(ne => ne.Name.EndsWith("-IT")))
            {
                await notificationEndpointsApi.DeleteNotificationEndpointAsync(delete);
            }

            //
            // Create Threshold Check
            //
            // Set status to 'Critical' if the 'current' value for 'stock' measurement is lesser than '35'
            //
            var query = "from(bucket: \"my-bucket\") "
                        + "|> range(start: v.timeRangeStart, stop: v.timeRangeStop)  "
                        + "|> filter(fn: (r) => r._measurement == \"stock\")  "
                        + "|> filter(fn: (r) => r.company == \"zyz\")  "
                        + "|> aggregateWindow(every: 5s, fn: mean)  "
                        + "|> filter(fn: (r) => r._field == \"current\")  "
                        + "|> yield(name: \"mean\")";

            var threshold = new LesserThreshold(value: 35F, level: CheckStatusLevel.CRIT,
                                                type: LesserThreshold.TypeEnum.Lesser);

            var message = "The Stock price for XYZ is on: ${ r._level } level!";

            await checksApi.CreateThresholdCheckAsync(AbstractItClientTest.GenerateName("XYZ Stock value"), query, "5s", message, threshold, org.Id);


            //
            // Create Slack Notification endpoint
            //
            var url      = MockServerUrl;
            var endpoint =
                await notificationEndpointsApi.CreateSlackEndpointAsync(
                    AbstractItClientTest.GenerateName("Slack Endpoint"), url, org.Id);

            //
            // Create Notification Rule
            //
            // Send message if the status is 'Critical'
            //
            await notificationRulesApi.CreateSlackRuleAsync(
                AbstractItClientTest.GenerateName("Critical status to Slack"), "10s", "${ r._message }",
                RuleStatusLevel.CRIT, endpoint, org.Id);


            //
            // Write Data
            //
            var now    = DateTime.UtcNow;
            var point1 = PointData
                         .Measurement("stock")
                         .Tag("company", "zyz")
                         .Field("current", 33.65)
                         .Timestamp(now, WritePrecision.Ns);

            var writeApi = _client.GetWriteApi();
            var listener = new WriteApiTest.EventListener(writeApi);

            writeApi.WritePoint("my-bucket", "my-org", point1);
            writeApi.Flush();
            listener.WaitToSuccess();


            var start = DateTime.UtcNow;

            while (!MockServer.LogEntries.Any() && (DateTime.UtcNow - start).TotalSeconds < 30)
            {
                Thread.Sleep(100);
            }

            var requestEntry = MockServer.LogEntries.Last();

            Assert.AreEqual($"{MockServerUrl}/", requestEntry.RequestMessage.Url);

            var json = (JObject)requestEntry.RequestMessage.BodyAsJson;

            Assert.IsNotNull(json.GetValue("attachments"));

            var attachments = (JArray)json.GetValue("attachments");

            Assert.AreEqual(1, attachments.Count);

            Assert.AreEqual("The Stock price for XYZ is on: crit level!", attachments[0]["text"].ToString());
        }
Example #27
0
        public async Task TrailingSlashInUrl()
        {
            MockServer
            .Given(Request.Create().WithPath("/api/v2/write").UsingPost())
            .RespondWith(CreateResponse("{}"));

            using (var writeApi = _client.GetWriteApi())
            {
                writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
                                     "h2o_feet,location=coyote_creek water_level=1.0 1");
            }

            var request = MockServer.LogEntries.Last();

            Assert.AreEqual(MockServerUrl + "/api/v2/write?org=org1&bucket=b1&precision=ns",
                            request.RequestMessage.AbsoluteUrl);

            _client.Dispose();
            _client = InfluxDBClientFactory.Create(MockServerUrl + "/");

            using (var writeApi = _client.GetWriteApi())
            {
                writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
                                     "h2o_feet,location=coyote_creek water_level=1.0 1");
            }

            request = MockServer.LogEntries.Last();
            Assert.AreEqual(MockServerUrl + "/api/v2/write?org=org1&bucket=b1&precision=ns",
                            request.RequestMessage.AbsoluteUrl);

            _client.Dispose();
            _client = InfluxDBClientFactory.Create(new InfluxDBClientOptions.Builder().Url(MockServerUrl)
                                                   .AuthenticateToken("my-token").Build());

            using (var writeApi = _client.GetWriteApi())
            {
                writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
                                     "h2o_feet,location=coyote_creek water_level=1.0 1");
            }

            request = MockServer.LogEntries.Last();
            Assert.AreEqual(MockServerUrl + "/api/v2/write?org=org1&bucket=b1&precision=ns",
                            request.RequestMessage.AbsoluteUrl);

            _client.Dispose();
            _client = InfluxDBClientFactory.Create(new InfluxDBClientOptions.Builder().Url(MockServerUrl + "/")
                                                   .AuthenticateToken("my-token").Build());

            using (var writeApi = _client.GetWriteApi())
            {
                writeApi.WriteRecord("b1", "org1", WritePrecision.Ns,
                                     "h2o_feet,location=coyote_creek water_level=1.0 1");
            }

            request = MockServer.LogEntries.Last();
            Assert.AreEqual(MockServerUrl + "/api/v2/write?org=org1&bucket=b1&precision=ns",
                            request.RequestMessage.AbsoluteUrl);

            Assert.True(MockServer.LogEntries.Any());
            foreach (var logEntry in MockServer.LogEntries)
            {
                StringAssert.StartsWith(MockServerUrl + "/api/v2/", logEntry.RequestMessage.AbsoluteUrl);
            }
        }
Example #28
0
 public WriteApi GetWriteApi()
 {
     return(_client.GetWriteApi());
 }