Пример #1
0
        public void GetInstanceIdInternalThrowsIfContextIsNull()
        {
            // Act
            var ex = Assert.Throws <ArgumentNullException>(() => InstanceIdUtility.GetInstanceIdInternal(context: null, machineName: null));

            // Assert
            Assert.Equal("context", ex.ParamName);
        }
Пример #2
0
        protected JobLogger(string statusFileName, IEnvironment environment, ITraceFactory traceFactory)
        {
            _statusFileName = statusFileName;
            TraceFactory    = traceFactory;
            Environment     = environment;

            InstanceId = InstanceIdUtility.GetShortInstanceId();
        }
Пример #3
0
        private IDisposable WriteStartElement(string title, IDictionary <string, string> attribs)
        {
            try
            {
                var info = new TraceInfo(title, attribs);

                var ensureMaxXmlFiles = false;
                if (String.IsNullOrEmpty(_file))
                {
                    ensureMaxXmlFiles = true;

                    // generate trace file name base on attribs
                    _file = GenerateFileName(info);
                }

                var strb = new StringBuilder();

                if (_isStartElement)
                {
                    strb.AppendLine(">");
                }

                strb.Append(new String(' ', _infos.Count * 2));
                strb.AppendFormat("<step title=\"{0}\" ", XmlUtility.EscapeXmlText(title));
                strb.AppendFormat("date=\"{0}\" ", info.StartTime.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
                if (_infos.Count == 0)
                {
                    strb.AppendFormat("instance=\"{0}\" ", InstanceIdUtility.GetShortInstanceId());
                }

                foreach (var attrib in attribs)
                {
                    if (TraceExtensions.IsNonDisplayableAttribute(attrib.Key))
                    {
                        continue;
                    }

                    strb.AppendFormat("{0}=\"{1}\" ", attrib.Key, XmlUtility.EscapeXmlText(attrib.Value));
                }

                FileSystemHelpers.AppendAllTextToFile(_file, strb.ToString());
                _infos.Push(info);
                _isStartElement = true;

                if (ensureMaxXmlFiles)
                {
                    EnsureMaxXmlFiles();
                }

                return(new DisposableAction(() => WriteEndTrace()));
            }
            catch (Exception ex)
            {
                WriteUnexpectedException(ex);
            }

            return(DisposableAction.Noop);
        }
Пример #4
0
        protected JobLogger(string statusFileName, IEnvironment environment, ITraceFactory traceFactory)
        {
            _statusFileName = statusFileName;
            TraceFactory    = traceFactory;
            Environment     = environment;
            Analytics       = new Analytics(null, new ServerConfiguration(), traceFactory);

            InstanceId = InstanceIdUtility.GetShortInstanceId();
        }
Пример #5
0
        internal static string GetProfilePath(int processId, bool iisProfiling)
        {
            string profileFileName = "";

            if (iisProfiling)
            {
                profileFileName = string.Format("profile_{0}_{1}_{2}_{3}.diagsession", InstanceIdUtility.GetShortInstanceId(), "IISProfiling", System.Diagnostics.Process.GetProcessById(processId).ProcessName, processId);
            }
            else
            {
                profileFileName = string.Format("profile_{0}_{1}_{2}.diagsession", InstanceIdUtility.GetShortInstanceId(), System.Diagnostics.Process.GetProcessById(processId).ProcessName, processId);
            }
            return(System.Environment.ExpandEnvironmentVariables("%LOCAL_EXPANDED%\\Temp\\" + profileFileName));
        }
Пример #6
0
        public void GetInstanceIdUsesMachineNameIfServerVariableIsUnavailable()
        {
            // Arrange
            var serverVariables = new NameValueCollection();
            var request         = new Mock <HttpRequestBase>();

            request.Setup(r => r.ServerVariables).Returns(serverVariables);
            var context = new Mock <HttpContextBase>();

            context.Setup(c => c.Request).Returns(request.Object);

            var result = InstanceIdUtility.GetInstanceIdInternal(context.Object, "some-name");

            // Assert
            Assert.Equal("829611378102ce70a80e34fd0f614a95c68f8c0aa6a86456d61bc893edf787d0", result);
        }
        /// <summary>
        /// Update the status and the detailed status of the job.
        /// The status is the status of one of the instances,
        /// The detailed status contains status for all instances and looks like:
        ///
        /// aabbcc - Running
        /// 112233 - PendingRestart
        ///
        /// </summary>
        private void UpdateDetailedStatus(ContinuousJob job, string jobsSpecificDataPath)
        {
            string instanceId = InstanceIdUtility.GetShortInstanceId();

            string[] statusFiles = FileSystemHelpers.GetFiles(jobsSpecificDataPath, StatusFilesSearchPattern);
            if (statusFiles.Length <= 0)
            {
                // If no status files exist update to default values
                string status = ContinuousJobStatus.Initializing.Status;

                job.DetailedStatus = instanceId + " - " + status;
                job.Status         = status;

                return;
            }

            string lastStatus    = null;
            var    stringBuilder = new StringBuilder();

            foreach (string statusFile in statusFiles)
            {
                // Extract instance id from the file name
                int    statusFileNameIndex  = statusFile.IndexOf(ContinuousJobStatus.FileNamePrefix, StringComparison.OrdinalIgnoreCase);
                string statusFileInstanceId = statusFile.Substring(statusFileNameIndex + ContinuousJobStatus.FileNamePrefix.Length);

                // Try to delete file, it'll be deleted if no one holds a lock on it
                // That way we know the status file is obsolete
                if (String.Equals(statusFileInstanceId, instanceId, StringComparison.OrdinalIgnoreCase) ||
                    !TryDelete(statusFile))
                {
                    // If we couldn't delete the file, we know it holds the status of an actual instance holding it
                    var continuousJobStatus = GetStatus <ContinuousJobStatus>(statusFile) ?? ContinuousJobStatus.Initializing;

                    stringBuilder.AppendLine(statusFileInstanceId + " - " + continuousJobStatus.Status);
                    if (lastStatus == null ||
                        !ContinuousJobStatus.InactiveInstance.Equals(continuousJobStatus))
                    {
                        lastStatus = continuousJobStatus.Status;
                    }
                }
            }

            // Job status will only show one of the statuses
            job.Status         = lastStatus;
            job.DetailedStatus = stringBuilder.ToString();
        }
Пример #8
0
        private static Dictionary <string, string> GetTraceAttributes(HttpContext httpContext)
        {
            var attribs = new Dictionary <string, string>
            {
                { "url", httpContext.Request.RawUrl },
                { "method", httpContext.Request.HttpMethod },
                { "type", "request" },
                { "instance", InstanceIdUtility.GetShortInstanceId() }
            };

            // Add an attribute containing the process, AppDomain and Thread ids to help debugging
            attribs.Add("pid", String.Join(",",
                                           Process.GetCurrentProcess().Id,
                                           AppDomain.CurrentDomain.Id.ToString(),
                                           System.Threading.Thread.CurrentThread.ManagedThreadId));

            return(attribs);
        }
Пример #9
0
        public void GetInstanceIdUsesLocalIdServerVariable()
        {
            // Arrange
            var serverVariables = new NameValueCollection();

            serverVariables["LOCAL_ADDR"] = "this-would-be-some-ip";
            var request = new Mock <HttpRequestBase>();

            request.Setup(r => r.ServerVariables).Returns(serverVariables);
            var context = new Mock <HttpContextBase>();

            context.Setup(c => c.Request).Returns(request.Object);

            var result = InstanceIdUtility.GetInstanceIdInternal(context.Object, "");

            // Assert
            Assert.Equal("f11600af8c2f753d24f85c01d217855fe65352b2d785057c2c1f2010e87dbea9", result);
        }
Пример #10
0
        // such as <datetime>_<instance>_<salt>_get_<url>_<statusCode>.xml
        // sample: 2014-11-17T04-59-21_d10e51_366_GET_api-deployments_200.xml
        private string GenerateFileName(TraceInfo info)
        {
            var strb = new StringBuilder();

            // add salt to avoid collision
            // mathematically improbable for salt to overflow
            strb.AppendFormat("{0}_{1}_{2:000}",
                              info.StartTime.ToString("yyyy-MM-ddTHH-mm-ss"),
                              InstanceIdUtility.GetShortInstanceId(),
                              Interlocked.Increment(ref _salt) % 1000);

            if (info.Title == XmlTracer.IncomingRequestTrace)
            {
                var path = info.Attributes["url"].Split('?')[0].Trim('/');
                strb.AppendFormat("_{0}_{1}", info.Attributes["method"], path.ToSafeFileName());
            }
            else if (info.Title == XmlTracer.StartupRequestTrace)
            {
                var path = info.Attributes["url"].Split('?')[0].Trim('/');
                strb.AppendFormat("_Startup_{0}_{1}", info.Attributes["method"], path.ToSafeFileName());
            }
            else if (info.Title == XmlTracer.ProcessShutdownTrace)
            {
                strb.Append("_Shutdown");
            }
            else if (info.Title == XmlTracer.ExecutingExternalProcessTrace)
            {
                var path = info.Attributes["path"].Split('\\').Last();
                strb.AppendFormat("_{0}", path);
            }
            else if (string.Equals(XmlTracer.BackgroundTrace, info.Title, StringComparison.Ordinal))
            {
                var path = info.Attributes["url"].Split('?')[0].Trim('/');
                strb.AppendFormat("_Background_{0}_{1}", info.Attributes["method"], path.ToSafeFileName());
            }
            else if (!String.IsNullOrEmpty(info.Title))
            {
                strb.AppendFormat("_{0}", info.Title.ToSafeFileName());
            }

            strb.Append(PendingXml);

            return(Path.Combine(_path, strb.ToString()));
        }
Пример #11
0
        private void WriteUnexpectedException(Exception ex)
        {
            try
            {
                var strb = new StringBuilder();
                strb.AppendFormat("{0}_{1}_{2:000}_UnexpectedException.xml",
                                  DateTime.UtcNow.ToString("yyyy-MM-ddTHH-mm-ss"),
                                  InstanceIdUtility.GetShortInstanceId(),
                                  Interlocked.Increment(ref _salt) % 1000);

                FileSystemHelpers.AppendAllTextToFile(
                    Path.Combine(_path, strb.ToString()),
                    String.Format("<exception>{0}</exception>", XmlUtility.EscapeXmlText(ex.ToString())));
            }
            catch
            {
                // no-op
            }
        }
Пример #12
0
        private static string GetResponseFileName(string prefix, string ext)
        {
            var context = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current);

            return(String.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2:MM-dd-HH-mm-ss}.{3}", prefix, InstanceIdUtility.GetShortInstanceId(context), DateTime.UtcNow, ext));
        }
Пример #13
0
 private static string GetResponseFileName(string prefix, string ext)
 {
     return(String.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2:MM-dd-HH-mm-ss}.{3}", prefix, InstanceIdUtility.GetShortInstanceId(), DateTime.UtcNow, ext));
 }
Пример #14
0
 internal static string GetStatusFileName()
 {
     return(ContinuousJobStatus.FileNamePrefix + InstanceIdUtility.GetShortInstanceId());
 }
Пример #15
0
        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.UtcNow.ToString("MM/dd H:mm:ss")),
                                              new XAttribute("instance", InstanceIdUtility.GetShortInstanceId()));

            foreach (var pair in attributes)
            {
                if (TraceExtensions.IsNonDisplayableAttribute(pair.Key))
                {
                    continue;
                }

                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 if (ShouldTrace(stepElement.LastNode as XElement))
                    {
                        // 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);
                }
            }));
        }