ProcessInfluxDBError() public static method

public static ProcessInfluxDBError ( string InfluxError ) : InfluxDBException
InfluxError string
return InfluxDBException
Ejemplo n.º 1
0
        /// <summary>
        /// Posts an InfluxDataPoint to given measurement
        /// </summary>
        /// <param name="dbName">InfluxDB database name</param>
        /// <param name="point">Influx data point to be written</param>
        /// <returns>True:Success, False:Failure</returns>
        ///<exception cref="UnauthorizedAccessException">When Influx needs authentication, and no user name password is supplied or auth fails</exception>
        ///<exception cref="HttpRequestException">all other HTTP exceptions</exception>
        public async Task <bool> PostPointAsync(string dbName, IInfluxDatapoint point)
        {
            ByteArrayContent requestContent = new ByteArrayContent(Encoding.UTF8.GetBytes(point.ConvertToInfluxLineProtocol()));
            var endPoint = new Dictionary <string, string>()
            {
                { "db", dbName },
                { "precision", precisionLiterals[(int)point.Precision] }
            };

            if (!String.IsNullOrWhiteSpace(point.Retention?.Name))
            {
                endPoint.Add("rp", point.Retention?.Name);
            }
            HttpResponseMessage response = await PostAsync(endPoint, requestContent);

            if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                throw InfluxDBException.ProcessInfluxDBError(await response.Content.ReadAsStringAsync());
            }
            else if (response.StatusCode == HttpStatusCode.NoContent)
            {
                point.Saved = true;
                return(true);
            }
            else
            {
                point.Saved = false;
                return(false);
            }
        }
        private async Task <HttpResponseMessage> GetAsync(Dictionary <string, string> Query, HttpCompletionOption completion = HttpCompletionOption.ResponseContentRead)
        {
            var querybaseUrl = new Uri($"{InfluxUrl}/query?");
            var builder      = new UriBuilder(querybaseUrl);

            builder.Query = await new FormUrlEncodedContent(Query).ReadAsStringAsync();
            try
            {
                HttpResponseMessage response = await _client.GetAsync(builder.Uri, completion);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(response);
                }
                else if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.BadGateway || (response.StatusCode == HttpStatusCode.InternalServerError && response.ReasonPhrase == "INKApi Error")) //502 Connection refused
                {
                    throw new UnauthorizedAccessException("InfluxDB needs authentication. Check uname, pwd parameters");
                }
                else if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    throw InfluxDBException.ProcessInfluxDBError(await response.Content.ReadAsStringAsync());
                }
            }
            catch (HttpRequestException e)
            {
                if (e.InnerException.Message == "Unable to connect to the remote server" ||
                    e.InnerException.Message == "A connection with the server could not be established" ||
                    e.InnerException.Message.StartsWith("The remote name could not be resolved:"))
                {
                    throw new ServiceUnavailableException();
                }
            }
            return(null);
        }
        private async Task <HttpResponseMessage> PostAsync(Dictionary <string, string> EndPoint, byte[] requestContent)
        {
            var querybaseUrl = new Uri(InfluxUrl);
            var builder      = new UriBuilder(querybaseUrl);

            builder.Path += "write";

            builder.Query = await new FormUrlEncodedContent(EndPoint).ReadAsStringAsync();
            //if (requestContent.Headers.ContentType == null)
            //{
            //    requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            //    requestContent.Headers.ContentType.CharSet = "UTF-8";
            //}

            try
            {
                using (var outStream = new MemoryStream())
                {
                    using (var gZipStream = new GZipStream(outStream, CompressionMode.Compress, true))
                    {
                        using (var byeteArrayStream = new MemoryStream(requestContent))
                            await byeteArrayStream.CopyToAsync(gZipStream);
                    }
                    var zippedByteArrayContent = new ByteArrayContent(outStream.ToArray());
                    zippedByteArrayContent.Headers.ContentEncoding.Add("gzip");
                    HttpResponseMessage response = await _client.PostAsync(builder.Uri, zippedByteArrayContent);

                    if (response.StatusCode == HttpStatusCode.Unauthorized ||
                        (response.StatusCode == HttpStatusCode.InternalServerError && response.ReasonPhrase == "INKApi Error") ||
                        response.StatusCode == HttpStatusCode.Forbidden ||
                        response.StatusCode == HttpStatusCode.ProxyAuthenticationRequired ||
                        (int)response.StatusCode == 511)   //511 NetworkAuthenticationRequired
                    {
                        throw new UnauthorizedAccessException("InfluxDB needs authentication. Check uname, pwd parameters");
                    }
                    else if (response.StatusCode == HttpStatusCode.BadGateway || response.StatusCode == HttpStatusCode.GatewayTimeout)
                    {
                        throw new ServiceUnavailableException(await response.Content.ReadAsStringAsync());
                    }
                    else if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        throw InfluxDBException.ProcessInfluxDBError(await response.Content.ReadAsStringAsync());
                    }

                    return(response);
                }
            }
            catch (HttpRequestException e)
            {
                if (e.InnerException.Message == "Unable to connect to the remote server")
                {
                    throw new ServiceUnavailableException();
                }
            }
            return(null);
        }
        /// <summary>
        /// InfluxDB engine version
        /// </summary>
        public async Task <string> GetServerVersionAsync()
        {
            var querybaseUrl = new Uri(InfluxUrl);
            var builder      = new UriBuilder(querybaseUrl);

            builder.Path += "ping";
            try
            {
                HttpResponseMessage response = await _client.GetAsync(builder.Uri);

                if (response.StatusCode == HttpStatusCode.NoContent)
                {
                    return(response.Headers.GetValues("X-Influxdb-Version").FirstOrDefault());
                }
                if (response.StatusCode == HttpStatusCode.Unauthorized ||
                    (response.StatusCode == HttpStatusCode.InternalServerError && response.ReasonPhrase == "INKApi Error") ||
                    response.StatusCode == HttpStatusCode.Forbidden ||
                    response.StatusCode == HttpStatusCode.ProxyAuthenticationRequired ||
                    (int)response.StatusCode == 511)       //511 NetworkAuthenticationRequired
                {
                    throw new UnauthorizedAccessException("InfluxDB needs authentication. Check uname, pwd parameters");
                }
                else if (response.StatusCode == HttpStatusCode.BadGateway || response.StatusCode == HttpStatusCode.GatewayTimeout)
                {
                    throw new ServiceUnavailableException(await response.Content.ReadAsStringAsync());
                }
                else if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    throw InfluxDBException.ProcessInfluxDBError(await response.Content.ReadAsStringAsync());
                }
            }
            catch (HttpRequestException e)
            {
                if (e.InnerException.Message == "Unable to connect to the remote server")
                {
                    throw new ServiceUnavailableException();
                }
            }
            return("Unknown");
        }
Ejemplo n.º 5
0
        private async Task <bool> PostPointsAsync(string dbName, TimePrecision precision, string retention, IEnumerable <IInfluxDatapoint> points)
        {
            Regex multiLinePattern = new Regex(@"([\P{Cc}].*?) '([\P{Cc}].*?)':([\P{Cc}].*?)\\n", RegexOptions.Compiled, TimeSpan.FromSeconds(5));
            Regex oneLinePattern   = new Regex(@"{\""error"":""([9\P{Cc}]+) '([\P{Cc}]+)':([a-zA-Z0-9 ]+)", RegexOptions.Compiled, TimeSpan.FromSeconds(5));

            var line = new StringBuilder();

            foreach (var point in points)
            {
                line.AppendFormat("{0}\n", point.ConvertToInfluxLineProtocol());
            }
            //remove last \n
            line.Remove(line.Length - 1, 1);

            ByteArrayContent requestContent = new ByteArrayContent(Encoding.UTF8.GetBytes(line.ToString()));
            var endPoint = new Dictionary <string, string>()
            {
                { "db", dbName }
            };

            if (precision > 0)
            {
                endPoint.Add("precision", precisionLiterals[(int)precision]);
            }

            if (!String.IsNullOrWhiteSpace(retention))
            {
                endPoint.Add("rp", retention);
            }
            HttpResponseMessage response = await PostAsync(endPoint, requestContent);

            if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.BadGateway || (response.StatusCode == HttpStatusCode.InternalServerError && response.ReasonPhrase == "INKApi Error")) //502 Connection refused
            {
                throw new UnauthorizedAccessException("InfluxDB needs authentication. Check uname, pwd parameters");
            }
            //if(response.StatusCode==HttpStatusCode.NotFound)
            else if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                var content = await response.Content.ReadAsStringAsync();

                //regex assumes error text from https://github.com/influxdata/influxdb/blob/master/models/points.go ParsePointsWithPrecision
                //fmt.Sprintf("'%s': %v", string(block[start:len(block)])
                List <string> parts = null; string l = "";

                if (content.Contains("partial write"))
                {
                    try
                    {
                        if (content.Contains("\\n"))
                        {
                            parts = multiLinePattern.Matches(content.Substring(content.IndexOf("partial write:\\n") + 16)).ToList();
                        }
                        else
                        {
                            parts = oneLinePattern.Matches(content.Substring(content.IndexOf("partial write:\\n") + 16)).ToList();
                        }

                        if (parts.Count == 0)
                        {
                            throw new InfluxDBException("Partial Write", new Regex(@"\""error\"":\""(.*?)\""").Match(content).Groups[1].Value);
                        }

                        if (parts[1].Contains("\\n"))
                        {
                            l = parts[1].Substring(0, parts[1].IndexOf("\\n")).Unescape();
                        }
                        else
                        {
                            l = parts[1].Unescape();
                        }
                    }
                    catch (InfluxDBException e)
                    {
                        throw e;
                    }
                    catch (Exception)
                    {
                    }

                    var point = points.Where(p => p.ConvertToInfluxLineProtocol() == l).FirstOrDefault();
                    if (point != null)
                    {
                        throw new InfluxDBException("Partial Write", $"Partial Write : {parts?[0]} due to {parts?[2]}", point);
                    }
                    else
                    {
                        throw new InfluxDBException("Partial Write", $"Partial Write : {parts?[0]} due to {parts?[2]}", l);
                    }
                }
                else
                {
                    throw InfluxDBException.ProcessInfluxDBError(content);
                }
            }
            else if (response.StatusCode == HttpStatusCode.NoContent)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }