Exemplo n.º 1
0
 public Metric(string name, MetricType type, long timestamp, string unit, IDictionary <string, string> tags, double value)
 {
     this.Name      = name;
     this.Type      = type.ToString().ToLowerInvariant();
     this.Timestamp = timestamp;
     this.Tags      = tags;
     this.Unit      = unit;
     this.Value     = value;
 }
Exemplo n.º 2
0
        private void SendMetric(MetricType metricType, string metricName, string[] customTags, string value)
        {
            // Tags are used by datadog to allow metric aggregation across logical groups. (https://docs.datadoghq.com/tagging/)
            if (_MetricTagCache == null)
            {
                _MetricTagCache = new[] { $"env:{_Environment}", $"source:{_ApplicationName}" }
            }
            ;

            var tagsList = new List <string>();

            tagsList.AddRange(_MetricTagCache);

            if (customTags != null && customTags.Length > 0)
            {
                tagsList.AddRange(customTags);
            }

            var tags = tagsList.ToArray();

            var buffer = new MetricsPayload()
            {
                Series = new MetricData[]
                {
                    new MetricData()
                    {
                        Host       = Environment.MachineName,
                        MetricName = metricName,
                        Tags       = tags,
                        MetricType = metricType.ToString(),
                        DataPoints = new string[][]
                        {
                            new string[]
                            {
                                DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(),
                value
                            }
                        }
                    }
                }
            };

            if (_FullUrlCache == null)
            {
                _FullUrlCache = $"{_UrlEndpoint}?api_key={_ApiKey}";
            }

            // fire and forget task
            Task.Factory.StartNew(() => Post(_FullUrlCache, buffer));
        }
Exemplo n.º 3
0
        public IResult UpdateMetric(Uri uri, MetricType metricType, Func <IInstanceMetric, IInstanceMetric> updateRecipe)
        {
            if (!_instances.TryGetValue(uri, out var instance))
            {
                return(Result.Failure(Messages.InstanceDoesntExistMessage(uri)));
            }

            if (!instance.Metrics.TryGetValue(metricType, out var metric))
            {
                return(Result.Failure(Messages.CanNotUpdateMetric(metricType.ToString())));
            }
            UpdateMetricInternal(instance.Metrics, metricType, updateRecipe(metric));

            return(Result.Success(Messages.MetricHasBeenUpdated(instance.Metrics[metricType])));
        }
Exemplo n.º 4
0
        private string GetMetricType(MetricType type)
        {
            switch (type)
            {
            case MetricType.Counter: return("c");

            case MetricType.Gauge: return("g");

            case MetricType.Set: return("s");

            case MetricType.Timer: return("ms");

            default: throw new Exception($"Invalid metric type {type.ToString()}");
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Returns an enumerable of <see cref="Metadata"/> which describes this metric.
        /// </summary>
        public virtual IEnumerable <Metadata> GetMetadata()
        {
            for (var i = 0; i < Suffixes.Length; i++)
            {
                string metricType;
                switch (MetricType)
                {
                case MetricType.Counter:
                case MetricType.CumulativeCounter:
                    metricType = "counter";
                    break;

                case MetricType.Gauge:
                    metricType = "gauge";
                    break;

                default:
                    metricType = MetricType.ToString().ToLower();
                    break;
                }

                var suffix = Suffixes[i];

                yield return(new Metadata(suffix.Name, MetadataNames.Rate, Tags, metricType));

                var desc = suffix.Description;
                if (!string.IsNullOrEmpty(desc))
                {
                    yield return(new Metadata(suffix.Name, MetadataNames.Description, Tags, desc));
                }

                var unit = suffix.Unit;
                if (!string.IsNullOrEmpty(unit))
                {
                    yield return(new Metadata(suffix.Name, MetadataNames.Unit, Tags, unit));
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Returns an enumerable of <see cref="MetaData"/> which which describes this metric.
        /// </summary>
        public virtual IEnumerable <MetaData> GetMetaData()
        {
            for (var i = 0; i < SuffixesArray.Length; i++)
            {
                var fullName = Name + SuffixesArray[i];

                var metricType = string.Empty;
                switch (MetricType)
                {
                case MetricType.Counter:
                case MetricType.CumulativeCounter:
                    metricType = "counter";
                    break;

                case MetricType.Gauge:
                    metricType = "gauge";
                    break;

                default:
                    metricType = MetricType.ToString().ToLower();
                    break;
                }

                yield return(new MetaData(fullName, MetadataNames.Rate, null, metricType));

                var desc = GetDescription(i);
                if (!string.IsNullOrEmpty(desc))
                {
                    yield return(new MetaData(fullName, MetadataNames.Description, Tags, desc));
                }

                var unit = GetUnit(i);
                if (!string.IsNullOrEmpty(unit))
                {
                    yield return(new MetaData(fullName, MetadataNames.Unit, null, unit));
                }
            }
        }
Exemplo n.º 7
0
 public static JToken ExtractMetricSampleFromResourceFile(this MetricType metricType)
 {
     return(ExtractJsonFromEmbeddedResource(metricType.ToString().ToLower()));
 }
Exemplo n.º 8
0
        internal static string printMetric(MetricType metric)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine();
            sb.AppendLine(metric.ToString());

            Dictionary<long, int> histogram;
            if (!data_.TryGetValue(metric, out histogram))
            {
                sb.AppendLine("No data collected");
                return sb.ToString();
            }

            /*
            for (Dictionary<long, int>.Enumerator i = histogram.GetEnumerator(); i.MoveNext(); )
            {
                KeyValuePair<long, int> pair = i.Current;
                sb.Append(pair.Key);
                sb.Append(": ");
                sb.AppendLine(pair.Value);
            }
             */

            List<long> keys = histogram.Keys.ToList<long>();
            keys.Sort();
            foreach (long key in keys)
            {
                sb.Append(key);
                sb.Append(": ");
                sb.AppendLine(histogram[key].ToString());
            }

            return sb.ToString();
        }
        public override System.Xml.XmlDocument XmlSerialize()
        {
            System.Xml.XmlDocument document = base.XmlSerialize();

            System.Xml.XmlNode propertiesNode = document.ChildNodes[1].ChildNodes[0];


            #region Properties

            CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "EventTypeInt32", ((Int32)EventType).ToString());

            CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "EventType", EventType.ToString());

            CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "MetricTypeInt32", ((Int32)MetricType).ToString());

            CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "MetricType", MetricType.ToString());


            CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "MetricMinimum", MetricMinimum.ToString());

            CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "MetricMaximum", MetricMaximum.ToString());



            if (AuthorizedService != null)
            {
                CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "AuthorizedServiceId", AuthorizedService.Id.ToString());

                CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "AuthorizedServiceName", AuthorizedService.Name);
            }

            if (Service != null)
            {
                CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "ServiceId", Service.Id.ToString());

                CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "ServiceName", Service.Name);
            }

            if (Metric != null)
            {
                CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "MetricId", Metric.Id.ToString());

                CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "MetricName", Metric.Name);
            }


            if (ProblemStatement != null)
            {
                CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "ProblemStatementId", ProblemStatement.Id.ToString());

                CommonFunctions.XmlDocumentAppendPropertyNode(document, propertiesNode, "ProblemStatementName", ProblemStatement.Name);
            }

            #endregion


            #region Object Nodes

            if (Action != null)
            {
                document.LastChild.AppendChild(document.ImportNode(Action.XmlSerialize().LastChild, true));
            }

            #endregion


            #region Dependencies Nodes

            System.Xml.XmlNode dependenciesNode = document.CreateElement("Dependencies");

            document.LastChild.InsertBefore(dependenciesNode, propertiesNode);

            if (AuthorizedService != null)
            {
                dependenciesNode.AppendChild(document.ImportNode(AuthorizedService.XmlSerialize().LastChild, true));
            }

            if (Service != null)
            {
                dependenciesNode.AppendChild(document.ImportNode(Service.XmlSerialize().LastChild, true));
            }

            if (Metric != null)
            {
                dependenciesNode.AppendChild(document.ImportNode(Metric.XmlSerialize().LastChild, true));
            }

            if (ProblemStatement != null)
            {
                dependenciesNode.AppendChild(document.ImportNode(ProblemStatement.XmlSerialize().LastChild, true));
            }

            #endregion


            return(document);
        }
Exemplo n.º 10
0
        private static StringBuilder ExecuteAndParseMetricQuery(SqlConnection m_sql_connection, MetricType m_metrictype, string m_sqlscript)

        {
            StringBuilder m_result     = new StringBuilder();
            SqlCommand    m_sqlcommand = new SqlCommand(m_sqlscript);
            SqlDataReader m_sql_reader = null;

            try
            {
                m_sqlcommand.Connection = m_sql_connection;

                Log.Debug("Executing SQL Command...");

                m_sql_reader = m_sqlcommand.ExecuteReader();

                Log.Debug("Done!");

                m_sqlcommand.Dispose();

                if (m_sql_reader != null && m_sql_reader.HasRows == true)
                {
                    List <string> m_columns          = new List <string>();
                    List <string> m_metric_blacklist = new List <string>();

                    switch (m_metrictype)

                    {
                    case MetricType.DatabaseIO:

                        m_metric_blacklist = GetDefaultColumnBlacklist();
                        m_metric_blacklist.Add("file_type");

                        double m_total_read_bytes_row  = 0;
                        double m_total_write_bytes_row = 0;
                        double m_total_read_bytes_log  = 0;
                        double m_total_write_bytes_log = 0;
                        string m_sql_instance          = String.Empty;

                        m_columns = ParseColumns(m_sql_reader, m_metric_blacklist);

                        if (m_columns.Count == 0)
                        {
                            throw new Exception("failed to get columns!");
                        }

                        while (m_sql_reader.Read())

                        {
                            foreach (string m_column in m_columns)
                            {
                                //host.mssql.measurement.sql_instance.databasename.filetype.field value timestamp
                                m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3}.{4}.{5} {6} {7}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), GetValueByColumnName(m_sql_reader, "sql_instance"), GetValueByColumnName(m_sql_reader, "database_name"), GetValueByColumnName(m_sql_reader, "file_type"), m_column.ToLower(), GetValueByColumnName(m_sql_reader, m_column), Helper.CreateTimeStamp().ToString()));
                            }

                            if (GetValueByColumnName(m_sql_reader, "file_type").ToLower().Equals("rows"))
                            {
                                m_total_read_bytes_row  += Double.Parse(GetValueByColumnName(m_sql_reader, "read_bytes"));
                                m_total_write_bytes_row += Double.Parse(GetValueByColumnName(m_sql_reader, "write_bytes"));
                            }
                            else
                            {
                                m_total_read_bytes_log  += Double.Parse(GetValueByColumnName(m_sql_reader, "read_bytes"));
                                m_total_write_bytes_log += Double.Parse(GetValueByColumnName(m_sql_reader, "write_bytes"));
                            }

                            m_sql_instance = GetValueByColumnName(m_sql_reader, "sql_instance");
                        }

                        m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3}.{4}.{5} {6} {7}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), m_sql_instance, "Total", "ROWS", "read_bytes", m_total_read_bytes_row, Helper.CreateTimeStamp().ToString()));
                        m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3}.{4}.{5} {6} {7}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), m_sql_instance, "Total", "ROWS", "write_bytes", m_total_write_bytes_row, Helper.CreateTimeStamp().ToString()));

                        m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3}.{4}.{5} {6} {7}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), m_sql_instance, "Total", "LOG", "read_bytes", m_total_read_bytes_log, Helper.CreateTimeStamp().ToString()));
                        m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3}.{4}.{5} {6} {7}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), m_sql_instance, "Total", "LOG", "write_bytes", m_total_write_bytes_log, Helper.CreateTimeStamp().ToString()));

                        break;


                    case MetricType.ServerProperties:

                        m_metric_blacklist = GetDefaultColumnBlacklist();

                        m_columns = ParseColumns(m_sql_reader, m_metric_blacklist);

                        while (m_sql_reader.Read())

                        {
                            foreach (string m_column in m_columns)
                            {
                                //host.mssql.measurement.sql_instance.field value timestamp
                                m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3} {4} {5}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), GetValueByColumnName(m_sql_reader, "sql_instance"), m_column.ToLower(), GetValueByColumnName(m_sql_reader, m_column), Helper.CreateTimeStamp().ToString()));
                            }
                        }

                        break;


                    case MetricType.PerformanceCounter:

                        while (m_sql_reader.Read())

                        {
                            string m_instance = GetValueByColumnName(m_sql_reader, "instance", true);

                            if (String.IsNullOrWhiteSpace(m_instance))
                            {
                                m_instance = "none";
                            }

                            //host.mssql.measurement.sql_instance.object.instance/database.counter/field value timestamp
                            m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3}.{4}.{5} {6} {7}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), GetValueByColumnName(m_sql_reader, "sql_instance"), GetValueByColumnName(m_sql_reader, "object", true), m_instance, GetValueByColumnName(m_sql_reader, "counter", true), GetValueByColumnName(m_sql_reader, "value"), Helper.CreateTimeStamp().ToString()));
                        }

                        break;


                    case MetricType.PerformanceMetrics:

                        m_metric_blacklist = GetDefaultColumnBlacklist();
                        m_columns          = ParseColumns(m_sql_reader, m_metric_blacklist);
                        m_metric_blacklist.Add("type");

                        while (m_sql_reader.Read())

                        {
                            foreach (string m_column in m_columns)
                            {
                                //host.mssql.measurement.sql_instance.field value timestamp
                                Log.Debug("Column Name:{0}", m_column);
                                m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3} {4} {5}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), GetValueByColumnName(m_sql_reader, "sql_instance"), m_column, GetValueByColumnName(m_sql_reader, m_column), Helper.CreateTimeStamp().ToString()));
                            }
                        }

                        break;

                    case MetricType.WaitStats:

                        m_metric_blacklist = GetDefaultColumnBlacklist();
                        m_metric_blacklist.Add("wait_category");
                        m_metric_blacklist.Add("wait_type");

                        m_columns = ParseColumns(m_sql_reader, m_metric_blacklist);

                        while (m_sql_reader.Read())

                        {
                            foreach (string m_column in m_columns)
                            {
                                //host.mssql.measurement.sql_instance.waittype.waitcategory.field value timestamp
                                m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3}.{4}.{5} {6} {7}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), GetValueByColumnName(m_sql_reader, "sql_instance"), GetValueByColumnName(m_sql_reader, "wait_type"), GetValueByColumnName(m_sql_reader, "wait_category", true), m_column.ToLower(), GetValueByColumnName(m_sql_reader, m_column), Helper.CreateTimeStamp().ToString()));
                            }
                        }

                        break;


                    case MetricType.MemoryClerk:

                        while (m_sql_reader.Read())

                        {
                            //host.mssql.measurement.sql_instance.field value timestamp
                            m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3} {4} {5}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), GetValueByColumnName(m_sql_reader, "sql_instance"), GetValueByColumnName(m_sql_reader, "clerk_type", true), GetValueByColumnName(m_sql_reader, "size_kb"), Helper.CreateTimeStamp().ToString()));
                        }

                        break;


                    case MetricType.DatabaseSize:

                        m_metric_blacklist = GetDefaultColumnBlacklist();
                        m_metric_blacklist.Add("type");

                        m_columns = ParseColumns(m_sql_reader, m_metric_blacklist);

                        if (m_columns.Count == 0)
                        {
                            throw new Exception("failed to get columns!");
                        }

                        while (m_sql_reader.Read())

                        {
                            foreach (string m_column in m_columns)
                            {
                                //host.mssql.measurement.sql_instance.databasename.field value timestamp
                                m_result.AppendLine(String.Format("{0}.mssql.{1}.{2}.{3}.{4} {5} {6}", Helper.GetFQDN().ToLower(), m_metrictype.ToString(), GetValueByColumnName(m_sql_reader, "sql_instance"), m_column, GetValueByColumnName(m_sql_reader, "measurement"), GetValueByColumnName(m_sql_reader, m_column), Helper.CreateTimeStamp().ToString()));
                            }
                        }

                        break;

                    default:
                        throw new Exception("undefined metrictype!");
                    }
                }
                else
                {
                    Log.Error("SQL Reader is null or has no rows!");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, ex.Message);
                m_result = null;
            }
            finally
            {
                if (m_sql_reader != null)
                {
                    m_sql_reader.Close();
                }
            }

            return(m_result);
        }
Exemplo n.º 11
0
        public async Task <BasicFinancials> GetBasicFinancials(string symbol, MetricType metricType)
        {
            if (string.IsNullOrWhiteSpace(symbol))
            {
                throw new ArgumentException(nameof(symbol));
            }

            return(await _finnhubClient.SendAsync <BasicFinancials>("stock/metric", JsonDeserialiser.Default,
                                                                    new Field(FieldKeys.Symbol, symbol),
                                                                    new Field(FieldKeys.Metric, metricType.ToString())));
        }
Exemplo n.º 12
0
 public string GetMetricType()
 {
     return(displayMetric.ToString());
 }
Exemplo n.º 13
0
 public string CalcNameKey()
 {
     return(Category.ToLower() + "-" + ((Name ?? "Missing Name")).ToLower() + "-" + MetricType.ToString());
 }
Exemplo n.º 14
0
 public void CalcAndSetAggregateKey()
 {
     this.AggregateKey = Category.ToLower() + "-" + ((Name ?? "Missing Name")).ToLower() + "-" + MetricType.ToString() + "-" + GetRoundedTime().ToString("s");
 }
Exemplo n.º 15
0
 public string AggregateKey()
 {
     return((Category ?? "Missing Category").ToLower() + "-" + ((Name ?? "Missing Name")).ToLower() + "-" + MetricType.ToString() + "-" + OccurredUtc.Floor(TimeSpan.FromMinutes(1)).ToString("s"));
 }