kudu /Kudu.Core/Tracing/Tracer.cs

Language C# Lines 225
MD5 Hash 22f14248ae3e2330f2903f1b982eac09
Repository https://github.com/moacap/kudu.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Abstractions;
using System.Linq;
using System.Xml.Linq;
using Kudu.Contracts.Tracing;
using Kudu.Core.Infrastructure;

namespace Kudu.Core.Tracing
{
    public class Tracer : ITracer
    {
        // TODO: Make this configurable
        private const int MaxLogEntries = 1000;

        private readonly Stack<TraceStep> _currentSteps = new Stack<TraceStep>();
        private readonly List<TraceStep> _steps = new List<TraceStep>();
        private readonly Stack<XElement> _elements = new Stack<XElement>();

        private readonly string _path;
        private readonly IFileSystem _fileSystem;

        private const string TraceRoot = "trace";

        private static readonly ConcurrentDictionary<string, object> _pathLocks = new ConcurrentDictionary<string, object>();

        public Tracer(string path)
            : this(new FileSystem(), path)
        {

        }

        public Tracer(IFileSystem fileSystem, string path)
        {
            _fileSystem = fileSystem;
            _path = path;

            if (!_pathLocks.ContainsKey(path))
            {
                _pathLocks.TryAdd(path, new object());
            }
        }

        public IEnumerable<TraceStep> Steps
        {
            get
            {
                return _steps.AsReadOnly();
            }
        }

        public IDisposable Step(string title, IDictionary<string, string> attributes)
        {
            var newStep = new TraceStep(title);
            var newStepElement = new XElement("step", new XAttribute("title", title),
                                                      new XAttribute("date", DateTime.Now.ToString("MM/dd H:mm:ss")));

            foreach (var pair in attributes)
            {
                string safeValue = XmlUtility.Sanitize(pair.Value);
                newStepElement.Add(new XAttribute(pair.Key, safeValue));
            }

            if (_currentSteps.Count == 0)
            {
                // Add a new top level step
                _steps.Add(newStep);
            }

            _currentSteps.Push(newStep);
            _elements.Push(newStepElement);

            // Start profiling
            newStep.Start();

            return new DisposableAction(() =>
            {
                try
                {
                    // If there's no steps then do nothing (guard against double dispose)
                    if (_currentSteps.Count == 0)
                    {
                        return;
                    }

                    // Stop the current step
                    _currentSteps.Peek().Stop();

                    TraceStep current = _currentSteps.Pop();
                    XElement stepElement = _elements.Pop();

                    stepElement.Add(new XAttribute("elapsed", current.ElapsedMilliseconds));

                    if (_elements.Count > 0)
                    {
                        XElement parent = _elements.Peek();
                        parent.Add(stepElement);
                    }
                    else
                    {
                        // Add this element to the list
                        Save(stepElement);
                    }

                    if (_currentSteps.Count > 0)
                    {
                        TraceStep parent = _currentSteps.Peek();
                        parent.Children.Add(current);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            });
        }

        private void Save(XElement stepElement)
        {
            lock (_pathLocks[_path])
            {
                XDocument document = GetDocument();

                // Make sure the size of the log doesn't go over the limit
                EnsureSize(document);

                document.Root.Add(stepElement);
                document.Save(_path);
            }
        }

        public void Trace(string value, IDictionary<string, string> attributes)
        {
            // Add a fake step
            using (Step(value, attributes)) { }
        }

        private void EnsureSize(XDocument document)
        {
            try
            {
                List<XElement> entries = document.Root.Elements().ToList();

                // Amount of entries we have to trim. It should be 1 all of the time
                // but just in case something went wrong, we're going to try to fix it this time around
                int trim = entries.Count - MaxLogEntries + 1;

                if (trim <= 0)
                {
                    return;
                }

                // Search for all skippable requests first
                var filteredEntries = entries.Take(MaxLogEntries / 2)
                                             .Where(Skippable)
                                             .ToList();

                // If we didn't find skippable entries just remove the oldest
                if (filteredEntries.Count == 0)
                {
                    // If there's none just use the full list
                    filteredEntries = entries;
                }

                foreach (var e in filteredEntries.Take(trim))
                {
                    e.Remove();
                }
            }
            catch (Exception ex)
            {
                // Something went wrong so just continue
                Debug.WriteLine(ex.Message);
            }
        }

        private static bool Skippable(XElement e)
        {
            // Git requests have type git="true"
            bool isGit = e.Attribute("git") != null;

            // The only top level exe is kudu
            bool isKudu = e.Attribute("type") != null && e.Attribute("path") != null;

            return !isGit && !isKudu;
        }

        private XDocument GetDocument()
        {
            if (!_fileSystem.File.Exists(_path))
            {
                _fileSystem.Directory.CreateDirectory(Path.GetDirectoryName(_path));
                return CreateDocumentRoot();
            }

            try
            {
                XDocument document;
                using (var stream = _fileSystem.File.OpenRead(_path))
                {
                    document = XDocument.Load(stream);
                }

                return document;
            }
            catch
            {
                // If the profile gets corrupted then delete it
                FileSystemHelpers.DeleteFileSafe(_path);

                // Return a new document
                return CreateDocumentRoot();
            }
        }

        private static XDocument CreateDocumentRoot()
        {
            return new XDocument(new XElement(TraceRoot));
        }
    }
}
Back to Top