Example #1
0
        /// <summary>
        /// Instantiates and composes the composers.
        /// </summary>
        public void Compose()
        {
            // make sure it is there
            _composition.WithCollectionBuilder <ComponentCollectionBuilder>();

            IEnumerable <Type> orderedComposerTypes;

            using (_logger.DebugDuration <Composers>("Preparing composer types.", "Prepared composer types."))
            {
                orderedComposerTypes = PrepareComposerTypes();
            }

            var composers = InstantiateComposers(orderedComposerTypes);

            using (_logger.DebugDuration <Composers>($"Composing composers. (log when >{LogThresholdMilliseconds}ms)", "Composed composers."))
            {
                foreach (var composer in composers)
                {
                    var componentType = composer.GetType();
                    using (_logger.DebugDuration <Composers>($"Composing {componentType.FullName}.", $"Composed {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
                    {
                        composer.Compose(_composition);
                    }
                }
            }
        }
Example #2
0
        private MacroContent Render(MacroModel macro, IPublishedContent content, IDictionary pageElements)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            var macroInfo = $"Render Macro: {macro.Name}, type: {macro.MacroType}, cache: {macro.CacheDuration}";

            using (_plogger.DebugDuration <MacroRenderer>(macroInfo, "Rendered Macro."))
            {
                // parse macro parameters ie replace the special [#key], [$key], etc. syntaxes
                foreach (var prop in macro.Properties)
                {
                    prop.Value = ParseAttribute(pageElements, prop.Value);
                }

                var cultureName = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
                macro.CacheIdentifier = GetContentCacheIdentifier(macro, content.Id, cultureName);

                // get the macro from cache if it is there
                var macroContent = GetMacroContentFromCache(macro);

                // macroContent.IsEmpty may be true, meaning the macro produces no output,
                // but still can be cached because its execution did not trigger any error.
                // so we need to actually render, only if macroContent is null
                if (macroContent != null)
                {
                    return(macroContent);
                }

                // this will take care of errors
                // it may throw, if we actually want to throw, so better not
                // catch anything here and let the exception be thrown
                var attempt = ExecuteMacroOfType(macro, content);

                // by convention ExecuteMacroByType must either throw or return a result
                // just check to avoid internal errors
                macroContent = attempt.Result;
                if (macroContent == null)
                {
                    throw new Exception("Internal error, ExecuteMacroOfType returned no content.");
                }

                // add to cache if render is successful
                // content may be empty but that's not an issue
                if (attempt.Success)
                {
                    // write to cache (if appropriate)
                    AddMacroContentToCache(macro, macroContent);
                }

                return(macroContent);
            }
        }
Example #3
0
    private void AcquireMainDom()
    {
        using DisposableTimer? timer = _profilingLogger.DebugDuration <CoreRuntime>("Acquiring MainDom.", "Acquired.");

        try
        {
            _mainDom.Acquire(_applicationShutdownRegistry);
        }
        catch
        {
            timer?.Fail();
            throw;
        }
    }
 public void Initialize()
 {
     using (_profilingLogger.DebugDuration <ComponentCollection>($"Initializing. (log components when >{LogThresholdMilliseconds}ms)", "Initialized."))
     {
         foreach (var component in this)
         {
             var componentType = component.GetType();
             using (_profilingLogger.DebugDuration <ComponentCollection>($"Initializing {componentType.FullName}.", $"Initialized {componentType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
             {
                 component.Initialize();
             }
         }
     }
 }
Example #5
0
        public void Can_Deep_Clone_Perf_Test()
        {
            // Arrange
            ContentType contentType = ContentTypeBuilder.CreateTextPageContentType();

            contentType.Id = 99;
            Content content = ContentBuilder.CreateTextpageContent(contentType, "Textpage", -1);
            int     i       = 200;

            foreach (IProperty property in content.Properties)
            {
                property.Id = ++i;
            }

            content.Id         = 10;
            content.CreateDate = DateTime.Now;
            content.CreatorId  = 22;
            content.Key        = Guid.NewGuid();
            content.Level      = 3;
            content.Path       = "-1,4,10";
            content.ContentSchedule.Add(DateTime.Now, DateTime.Now.AddDays(1));
            //// content.ChangePublishedState(PublishedState.Published);
            content.SortOrder  = 5;
            content.TemplateId = 88;
            content.Trashed    = false;
            content.UpdateDate = DateTime.Now;
            content.WriterId   = 23;

            var runtimeCache = new ObjectCacheAppCache();

            runtimeCache.Insert(content.Id.ToString(CultureInfo.InvariantCulture), () => content);

            IProfilingLogger proflog = GetTestProfilingLogger();

            using (proflog.DebugDuration <ContentTests>("STARTING PERF TEST WITH RUNTIME CACHE"))
            {
                for (int j = 0; j < 1000; j++)
                {
                    object clone = runtimeCache.Get(content.Id.ToString(CultureInfo.InvariantCulture));
                }
            }

            using (proflog.DebugDuration <ContentTests>("STARTING PERF TEST WITHOUT RUNTIME CACHE"))
            {
                for (int j = 0; j < 1000; j++)
                {
                    var clone = (ContentType)contentType.DeepClone();
                }
            }
        }
Example #6
0
        /// <inheritdoc />
        public override object ConvertIntermediateToObject(IPublishedElement owner, PublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            using (_proflog.DebugDuration <PublishedPropertyType>($"ConvertPropertyToNestedContent ({propertyType.DataType.Id})"))
            {
                var configuration = propertyType.DataType.ConfigurationAs <NestedContentConfiguration>();
                var contentTypes  = configuration.ContentTypes;
                var elements      = contentTypes.Length == 1
                    ? PublishedModelFactory.CreateModelList(contentTypes[0].Alias)
                    : new List <IPublishedElement>();

                var value = (string)inter;
                if (string.IsNullOrWhiteSpace(value))
                {
                    return(elements);
                }

                var objects = JsonConvert.DeserializeObject <List <JObject> >(value);
                if (objects.Count == 0)
                {
                    return(elements);
                }

                foreach (var sourceObject in objects)
                {
                    var element = ConvertToElement(sourceObject, referenceCacheLevel, preview);
                    if (element != null)
                    {
                        elements.Add(element);
                    }
                }

                return(elements);
            }
        }
Example #7
0
 protected override IComponent CreateItem(IFactory factory, Type itemType)
 {
     using (_logger.DebugDuration <ComponentCollectionBuilder>($"Creating {itemType.FullName}.", $"Created {itemType.FullName}.", thresholdMilliseconds: LogThresholdMilliseconds))
     {
         return(base.CreateItem(factory, itemType));
     }
 }
        /// <summary>
        /// Tries to find the document matching the request, by running the IPublishedContentFinder instances.
        /// </summary>
        /// <exception cref="InvalidOperationException">There is no finder collection.</exception>
        internal void FindPublishedContent(PublishedRequest request)
        {
            const string tracePrefix = "FindPublishedContent: ";

            // look for the document
            // the first successful finder, if any, will set this.PublishedContent, and may also set this.Template
            // some finders may implement caching

            using (_profilingLogger.DebugDuration <PublishedRouter>(
                       $"{tracePrefix}Executing finders...",
                       $"{tracePrefix}Completed executing finders"))
            {
                //iterate but return on first one that finds it
                var found = _contentFinders.Any(finder =>
                {
                    _logger.Debug <PublishedRouter>("Finder {ContentFinderType}", finder.GetType().FullName);
                    return(finder.TryFindContent(request));
                });

                _profilingLogger.Debug <PublishedRouter>(
                    "Found? {Found} Content: {PublishedContentId}, Template: {TemplateAlias}, Domain: {Domain}, Culture: {Culture}, Is404: {Is404}, StatusCode: {StatusCode}",
                    found,
                    request.HasPublishedContent ? request.PublishedContent.Id : "NULL",
                    request.HasTemplate ? request.TemplateAlias : "NULL",
                    request.HasDomain ? request.Domain.ToString() : "NULL",
                    request.Culture?.Name ?? "NULL",
                    request.Is404,
                    request.ResponseStatusCode);
            }

            // indicate that the published content (if any) we have at the moment is the
            // one that was found by the standard finders before anything else took place.
            request.SetIsInitialPublishedContent();
        }
Example #9
0
        /// <summary>
        /// Tries to find the document matching the request, by running the IPublishedContentFinder instances.
        /// </summary>
        /// <exception cref="InvalidOperationException">There is no finder collection.</exception>
        internal bool FindPublishedContent(IPublishedRequestBuilder request)
        {
            const string tracePrefix = "FindPublishedContent: ";

            // look for the document
            // the first successful finder, if any, will set this.PublishedContent, and may also set this.Template
            // some finders may implement caching
            using (_profilingLogger.DebugDuration <PublishedRouter>(
                       $"{tracePrefix}Begin finders",
                       $"{tracePrefix}End finders"))
            {
                // iterate but return on first one that finds it
                var found = _contentFinders.Any(finder =>
                {
                    _logger.LogDebug("Finder {ContentFinderType}", finder.GetType().FullName);
                    return(finder.TryFindContent(request));
                });

                _logger.LogDebug(
                    "Found? {Found}, Content: {PublishedContentId}, Template: {TemplateAlias}, Domain: {Domain}, Culture: {Culture}, StatusCode: {StatusCode}",
                    found,
                    request.HasPublishedContent() ? request.PublishedContent.Id : "NULL",
                    request.HasTemplate() ? request.Template?.Alias : "NULL",
                    request.HasDomain() ? request.Domain.ToString() : "NULL",
                    request.Culture ?? "NULL",
                    request.ResponseStatusCode);

                return(found);
            }
        }
Example #10
0
        public override bool PerformRun()
        {
            switch (_runtime.ServerRole)
            {
            case ServerRole.Replica:
                _logger.Debug <LogScrubber>("Does not run on replica servers.");
                return(true);    // DO repeat, server role can change

            case ServerRole.Unknown:
                _logger.Debug <LogScrubber>("Does not run on servers with unknown role.");
                return(true);    // DO repeat, server role can change
            }

            // ensure we do not run if not main domain, but do NOT lock it
            if (_runtime.IsMainDom == false)
            {
                _logger.Debug <LogScrubber>("Does not run if not MainDom.");
                return(false); // do NOT repeat, going down
            }

            // Ensure we use an explicit scope since we are running on a background thread.
            using (var scope = _scopeProvider.CreateScope())
                using (_logger.DebugDuration <LogScrubber>("Log scrubbing executing", "Log scrubbing complete"))
                {
                    _auditService.CleanLogs(GetLogScrubbingMaximumAge(_settings));
                    scope.Complete();
                }

            return(true); // repeat
        }
Example #11
0
        // internal/virtual for tests (i.e. hack, do not port to netcore)
        internal virtual void DetermineRuntimeLevel(IUmbracoDatabaseFactory databaseFactory, IProfilingLogger profilingLogger)
        {
            using (var timer = profilingLogger.DebugDuration <CoreRuntime>("Determining runtime level.", "Determined."))
            {
                try
                {
                    _state.DetermineRuntimeLevel(databaseFactory);

                    profilingLogger.Debug <CoreRuntime, RuntimeLevel, RuntimeLevelReason>("Runtime level: {RuntimeLevel} - {RuntimeLevelReason}", _state.Level, _state.Reason);

                    if (_state.Level == RuntimeLevel.Upgrade)
                    {
                        profilingLogger.Debug <CoreRuntime>("Configure database factory for upgrades.");
                        databaseFactory.ConfigureForUpgrade();
                    }
                }
                catch
                {
                    _state.Level  = RuntimeLevel.BootFailed;
                    _state.Reason = RuntimeLevelReason.BootFailedOnException;
                    timer?.Fail();
                    throw;
                }
            }
        }
Example #12
0
        /// <summary>
        /// The RegEx matches any HTML attribute values that start with a tilde (~), those that match are passed to ResolveUrl to replace the tilde with the application path.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        /// <remarks>
        /// When used with a Virtual-Directory set-up, this would resolve all URLs correctly.
        /// The recommendation is that the "ResolveUrlsFromTextString" option (in umbracoSettings.config) is set to false for non-Virtual-Directory installs.
        /// </remarks>
        public string EnsureUrls(string text)
        {
            if (_contentSection.ResolveUrlsFromTextString == false)
            {
                return(text);
            }

            using (var timer = _logger.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete"))
            {
                // find all relative URLs (ie. URLs that contain ~)
                var tags = ResolveUrlPattern.Matches(text);
                _logger.Debug <long, int>(typeof(IOHelper), "After regex: {Duration} matched: {TagsCount}", timer.Stopwatch.ElapsedMilliseconds, tags.Count);
                foreach (Match tag in tags)
                {
                    var url = "";
                    if (tag.Groups[1].Success)
                    {
                        url = tag.Groups[1].Value;
                    }

                    // The richtext editor inserts a slash in front of the URL. That's why we need this little fix
                    //                if (url.StartsWith("/"))
                    //                    text = text.Replace(url, ResolveUrl(url.Substring(1)));
                    //                else
                    if (string.IsNullOrEmpty(url) == false)
                    {
                        var resolvedUrl = (url.Substring(0, 1) == "/") ? IOHelper.ResolveUrl(url.Substring(1)) : IOHelper.ResolveUrl(url);
                        text = text.Replace(url, resolvedUrl);
                    }
                }
            }

            return(text);
        }
Example #13
0
        public override bool PerformRun()
        {
            switch (_runtime.ServerRole)
            {
            case ServerRole.Replica:
                _logger.Debug <LogScrubber>("Does not run on replica servers.");
                return(true);    // DO repeat, server role can change

            case ServerRole.Unknown:
                _logger.Debug <LogScrubber>("Does not run on servers with unknown role.");
                return(true);    // DO repeat, server role can change
            }

            // ensure we do not run if not main domain, but do NOT lock it
            if (_runtime.IsMainDom == false)
            {
                _logger.Debug <LogScrubber>("Does not run if not MainDom.");
                return(false); // do NOT repeat, going down
            }

            // running on a background task, and Log.CleanLogs uses the old SqlHelper,
            // better wrap in a scope and ensure it's all cleaned up and nothing leaks
            using (var scope = _scopeProvider.CreateScope())
                using (_logger.DebugDuration <LogScrubber>("Log scrubbing executing", "Log scrubbing complete"))
                {
                    _auditService.CleanLogs(GetLogScrubbingMaximumAge(_settings));
                    scope.Complete();
                }

            return(true); // repeat
        }
        /// <summary>
        ///  add the given section to the given user group
        /// </summary>
        /// <remarks>
        ///  if umbraco throws an exception here, we capture it
        ///  because if we don't umbraco won't startup and that
        ///  might be a bad thing :(
        /// </remarks>
        /// <param name="groupAlias"></param>
        /// <param name="sectionAlias"></param>
        private void AddSection(string groupAlias, string sectionAlias)
        {
            using (logger.DebugDuration <CustomSectionComponent>($"Adding Section {sectionAlias} to {groupAlias}"))
            {
                var group = userService.GetUserGroupByAlias(groupAlias);
                if (group != null)
                {
                    if (!group.AllowedSections.Contains(sectionAlias))
                    {
                        group.AddAllowedSection(sectionAlias);

                        try
                        {
                            userService.Save(group);
                            logger.Info <CustomSectionComponent>($"Section {sectionAlias} added to {groupAlias} group");
                        }
                        catch (Exception ex)
                        {
                            logger.Warn <CustomSectionComponent>("Error adding section {0} to group {1} [{2}]",
                                                                 sectionAlias, groupAlias, ex.Message);
                        }
                    }
                }
            }
        }
Example #15
0
        public override async Task <bool> PerformRunAsync(CancellationToken token)
        {
            switch (_runtime.ServerRole)
            {
            case ServerRole.Replica:
                _logger.Debug <ScheduledTasks>("Does not run on replica servers.");
                return(true);    // DO repeat, server role can change

            case ServerRole.Unknown:
                _logger.Debug <ScheduledTasks>("Does not run on servers with unknown role.");
                return(true);    // DO repeat, server role can change
            }

            // ensure we do not run if not main domain, but do NOT lock it
            if (_runtime.IsMainDom == false)
            {
                _logger.Debug <ScheduledTasks>("Does not run if not MainDom.");
                return(false); // do NOT repeat, going down
            }

            using (_logger.DebugDuration <ScheduledTasks>("Scheduled tasks executing", "Scheduled tasks complete"))
            {
                try
                {
                    await ProcessTasksAsync(token);
                }
                catch (Exception ex)
                {
                    _logger.Error <ScheduledTasks>(ex, "Error executing scheduled task");
                }
            }

            return(true); // repeat
        }
Example #16
0
    public override Task PerformExecuteAsync(object?state)
    {
        switch (_serverRegistrar.CurrentServerRole)
        {
        case ServerRole.Subscriber:
            _logger.LogDebug("Does not run on subscriber servers.");
            return(Task.CompletedTask);

        case ServerRole.Unknown:
            _logger.LogDebug("Does not run on servers with unknown role.");
            return(Task.CompletedTask);
        }

        // Ensure we do not run if not main domain, but do NOT lock it
        if (_mainDom.IsMainDom == false)
        {
            _logger.LogDebug("Does not run if not MainDom.");
            return(Task.CompletedTask);
        }

        // Ensure we use an explicit scope since we are running on a background thread.
        using (ICoreScope scope = _scopeProvider.CreateCoreScope())
            using (_profilingLogger.DebugDuration <LogScrubber>("Log scrubbing executing", "Log scrubbing complete"))
            {
                _auditService.CleanLogs((int)_settings.MaxLogAge.TotalMinutes);
                _ = scope.Complete();
            }

        return(Task.CompletedTask);
    }
Example #17
0
        public override object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
        {
            using (_proflog.DebugDuration <MultiUrlPickerValueConverter>($"ConvertPropertyToLinks ({propertyType.DataType.Id})"))
            {
                var maxNumber = propertyType.DataType.ConfigurationAs <MultiUrlPickerConfiguration>().MaxNumber;

                if (inter == null)
                {
                    return(maxNumber == 1 ? null : Enumerable.Empty <Link>());
                }

                var links             = new List <Link>();
                var dtos              = _jsonSerializer.Deserialize <IEnumerable <MultiUrlPickerValueEditor.LinkDto> >(inter.ToString());
                var publishedSnapshot = _publishedSnapshotAccessor.GetRequiredPublishedSnapshot();
                foreach (var dto in dtos)
                {
                    var type = LinkType.External;
                    var url  = dto.Url;

                    if (dto.Udi != null)
                    {
                        type = dto.Udi.EntityType == Constants.UdiEntityType.Media
                            ? LinkType.Media
                            : LinkType.Content;

                        var content = type == LinkType.Media ?
                                      publishedSnapshot.Media.GetById(preview, dto.Udi.Guid) :
                                      publishedSnapshot.Content.GetById(preview, dto.Udi.Guid);

                        if (content == null || content.ContentType.ItemType == PublishedItemType.Element)
                        {
                            continue;
                        }
                        url = content.Url(_publishedUrlProvider);
                    }

                    links.Add(
                        new Link
                    {
                        Name   = dto.Name,
                        Target = dto.Target,
                        Type   = type,
                        Udi    = dto.Udi,
                        Url    = url + dto.QueryString,
                    }
                        );
                }

                if (maxNumber == 1)
                {
                    return(links.FirstOrDefault());
                }
                if (maxNumber > 0)
                {
                    return(links.Take(maxNumber));
                }
                return(links);
            }
        }
Example #18
0
        public override async Task PerformExecuteAsync(object?state)
        {
            if (_healthChecksSettings.Notification.Enabled == false)
            {
                return;
            }

            if (_runtimeState.Level != RuntimeLevel.Run)
            {
                return;
            }

            switch (_serverRegistrar.CurrentServerRole)
            {
            case ServerRole.Subscriber:
                _logger.LogDebug("Does not run on subscriber servers.");
                return;

            case ServerRole.Unknown:
                _logger.LogDebug("Does not run on servers with unknown role.");
                return;
            }

            // Ensure we do not run if not main domain, but do NOT lock it
            if (_mainDom.IsMainDom == false)
            {
                _logger.LogDebug("Does not run if not MainDom.");
                return;
            }

            // Ensure we use an explicit scope since we are running on a background thread and plugin health
            // checks can be making service/database calls so we want to ensure the CallContext/Ambient scope
            // isn't used since that can be problematic.
            using (ICoreScope scope = _scopeProvider.CreateCoreScope())
                using (_profilingLogger.DebugDuration <HealthCheckNotifier>("Health checks executing", "Health checks complete"))
                {
                    // Don't notify for any checks that are disabled, nor for any disabled just for notifications.
                    Guid[] disabledCheckIds = _healthChecksSettings.Notification.DisabledChecks
                                              .Select(x => x.Id)
                                              .Union(_healthChecksSettings.DisabledChecks
                                                     .Select(x => x.Id))
                                              .Distinct()
                                              .ToArray();

                    IEnumerable <HealthCheck> checks = _healthChecks
                                                       .Where(x => disabledCheckIds.Contains(x.Id) == false);

                    var results = await HealthCheckResults.Create(checks);

                    results.LogResults();

                    // Send using registered notification methods that are enabled.
                    foreach (IHealthCheckNotificationMethod notificationMethod in _notifications.Where(x => x.Enabled))
                    {
                        await notificationMethod.SendAsync(results);
                    }
                }
        }
        public bool GetHtmlByUrl(string url, out string fullHtml)
        {
            using (_profilingLogger.DebugDuration <HtmlService>("GetHtmlByUrl(" + url + ")", "GetHtmlByUrl(" + url + ") done"))
            {
                if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
                {
                    fullHtml = "";
                    return(false);
                }

                try
                {
                    var httpTimeout = _fullTextConfig.GetHttpTimeout();

                    var cookieDictionary = GetQueryStringCollection();
                    var webRequest       = (HttpWebRequest)WebRequest.Create(uri);
                    httpTimeout         *= 1000;
                    webRequest.Timeout   = httpTimeout;
                    webRequest.UserAgent = "FullTextIndexer";

                    if (cookieDictionary != null && cookieDictionary.Count > 0)
                    {
                        var container = new CookieContainer();
                        var domain    = webRequest.Address.DnsSafeHost;
                        foreach (var cookie in cookieDictionary)
                        {
                            container.Add(new Cookie(cookie.Key, cookie.Value, "/", domain));
                        }
                        webRequest.CookieContainer = container;
                    }
                    var webResponse = (HttpWebResponse)webRequest.GetResponse();
                    using (var sr = new StreamReader(webResponse.GetResponseStream()))
                    {
                        fullHtml = sr.ReadToEnd();
                    }
                    return(true);
                }
                catch (WebException ex)
                {
                    _logger.Error <HtmlService>(ex, "Error in FullTextSearch retrieval.");
                    fullHtml = string.Empty;
                }
                return(false);
            }
        }
Example #20
0
        protected override IEnumerable <IComponent> CreateItems(IFactory factory)
        {
            _logger = factory.GetInstance <IProfilingLogger>();

            using (_logger.DebugDuration <ComponentCollectionBuilder>($"Creating components. (log when >{LogThresholdMilliseconds}ms)", "Created."))
            {
                return(base.CreateItems(factory));
            }
        }
Example #21
0
        public override async Task <bool> PerformRunAsync(CancellationToken token)
        {
            if (_runtimeState.Level != RuntimeLevel.Run)
            {
                return(true); // repeat...
            }
            switch (_runtimeState.ServerRole)
            {
            case ServerRole.Replica:
                _logger.Debug <HealthCheckNotifier>("Does not run on replica servers.");
                return(true);    // DO repeat, server role can change

            case ServerRole.Unknown:
                _logger.Debug <HealthCheckNotifier>("Does not run on servers with unknown role.");
                return(true);    // DO repeat, server role can change
            }

            // ensure we do not run if not main domain, but do NOT lock it
            if (_runtimeState.IsMainDom == false)
            {
                _logger.Debug <HealthCheckNotifier>("Does not run if not MainDom.");
                return(false); // do NOT repeat, going down
            }

            // Ensure we use an explicit scope since we are running on a background thread and plugin health
            // checks can be making service/database calls so we want to ensure the CallContext/Ambient scope
            // isn't used since that can be problematic.
            using (var scope = _scopeProvider.CreateScope())
                using (_logger.DebugDuration <HealthCheckNotifier>("Health checks executing", "Health checks complete"))
                {
                    var healthCheckConfig = Current.Configs.HealthChecks();

                    // Don't notify for any checks that are disabled, nor for any disabled
                    // just for notifications
                    var disabledCheckIds = healthCheckConfig.NotificationSettings.DisabledChecks
                                           .Select(x => x.Id)
                                           .Union(healthCheckConfig.DisabledChecks
                                                  .Select(x => x.Id))
                                           .Distinct()
                                           .ToArray();

                    var checks = _healthChecks
                                 .Where(x => disabledCheckIds.Contains(x.Id) == false);

                    var results = new HealthCheckResults(checks);
                    results.LogResults();

                    // Send using registered notification methods that are enabled
                    foreach (var notificationMethod in _notifications.Where(x => x.Enabled))
                    {
                        await notificationMethod.SendAsync(results, token);
                    }
                }

            return(true); // repeat
        }
Example #22
0
    /// <summary>
    ///     Tries to find the document matching the request, by running the IPublishedContentFinder instances.
    /// </summary>
    /// <exception cref="InvalidOperationException">There is no finder collection.</exception>
    internal async Task <bool> FindPublishedContent(IPublishedRequestBuilder request)
    {
        const string tracePrefix = "FindPublishedContent: ";

        // look for the document
        // the first successful finder, if any, will set this.PublishedContent, and may also set this.Template
        // some finders may implement caching
        DisposableTimer?profilingScope = null;

        try
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                profilingScope = _profilingLogger.DebugDuration <PublishedRouter>(
                    $"{tracePrefix}Begin finders",
                    $"{tracePrefix}End finders");
            }

            // iterate but return on first one that finds it
            var found = false;
            foreach (IContentFinder contentFinder in _contentFinders)
            {
                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug("Finder {ContentFinderType}", contentFinder.GetType().FullName);
                }

                found = await contentFinder.TryFindContent(request);

                if (found)
                {
                    break;
                }
            }

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug(
                    "Found? {Found}, Content: {PublishedContentId}, Template: {TemplateAlias}, Domain: {Domain}, Culture: {Culture}, StatusCode: {StatusCode}",
                    found,
                    request.HasPublishedContent() ? request.PublishedContent?.Id : "NULL",
                    request.HasTemplate() ? request.Template?.Alias : "NULL",
                    request.HasDomain() ? request.Domain?.ToString() : "NULL",
                    request.Culture ?? "NULL",
                    request.ResponseStatusCode);
            }

            return(found);
        }
        finally
        {
            profilingScope?.Dispose();
        }
    }
    protected override IComponent CreateItem(IServiceProvider factory, Type itemType)
    {
        IProfilingLogger logger = factory.GetRequiredService <IProfilingLogger>();

        using (logger.DebugDuration <ComponentCollectionBuilder>(
                   $"Creating {itemType.FullName}.",
                   $"Created {itemType.FullName}.",
                   thresholdMilliseconds: LogThresholdMilliseconds))
        {
            return(base.CreateItem(factory, itemType));
        }
    }
        public override async Task <bool> PerformRunAsync(CancellationToken token)
        {
            if (_runtimeState.Level != RuntimeLevel.Run)
            {
                return(true); // repeat...
            }
            switch (_runtimeState.ServerRole)
            {
            case ServerRole.Replica:
                _logger.Debug <HealthCheckNotifier>("Does not run on replica servers.");
                return(true);    // DO repeat, server role can change

            case ServerRole.Unknown:
                _logger.Debug <HealthCheckNotifier>("Does not run on servers with unknown role.");
                return(true);    // DO repeat, server role can change
            }

            // ensure we do not run if not main domain, but do NOT lock it
            if (_runtimeState.IsMainDom == false)
            {
                _logger.Debug <HealthCheckNotifier>("Does not run if not MainDom.");
                return(false); // do NOT repeat, going down
            }

            using (_logger.DebugDuration <HealthCheckNotifier>("Health checks executing", "Health checks complete"))
            {
                var healthCheckConfig = Current.Configs.HealthChecks();

                // Don't notify for any checks that are disabled, nor for any disabled
                // just for notifications
                var disabledCheckIds = healthCheckConfig.NotificationSettings.DisabledChecks
                                       .Select(x => x.Id)
                                       .Union(healthCheckConfig.DisabledChecks
                                              .Select(x => x.Id))
                                       .Distinct()
                                       .ToArray();

                var checks = _healthChecks
                             .Where(x => disabledCheckIds.Contains(x.Id) == false);

                var results = new HealthCheckResults(checks);
                results.LogResults();

                // Send using registered notification methods that are enabled
                foreach (var notificationMethod in _notifications.Where(x => x.Enabled))
                {
                    await notificationMethod.SendAsync(results, token);
                }
            }

            return(true); // repeat
        }
Example #25
0
    public override async Task PerformExecuteAsync(object?state)
    {
        if (_keepAliveSettings.DisableKeepAliveTask)
        {
            return;
        }

        // Don't run on replicas nor unknown role servers
        switch (_serverRegistrar.CurrentServerRole)
        {
        case ServerRole.Subscriber:
            _logger.LogDebug("Does not run on subscriber servers.");
            return;

        case ServerRole.Unknown:
            _logger.LogDebug("Does not run on servers with unknown role.");
            return;
        }

        // Ensure we do not run if not main domain, but do NOT lock it
        if (_mainDom.IsMainDom == false)
        {
            _logger.LogDebug("Does not run if not MainDom.");
            return;
        }

        using (_profilingLogger.DebugDuration <KeepAlive>("Keep alive executing", "Keep alive complete"))
        {
            var umbracoAppUrl = _hostingEnvironment.ApplicationMainUrl?.ToString();
            if (umbracoAppUrl.IsNullOrWhiteSpace())
            {
                _logger.LogWarning("No umbracoApplicationUrl for service (yet), skip.");
                return;
            }

            // If the config is an absolute path, just use it
            var keepAlivePingUrl = WebPath.Combine(
                umbracoAppUrl !,
                _hostingEnvironment.ToAbsolute(_keepAliveSettings.KeepAlivePingUrl));

            try
            {
                var        request    = new HttpRequestMessage(HttpMethod.Get, keepAlivePingUrl);
                HttpClient httpClient = _httpClientFactory.CreateClient(Constants.HttpClients.IgnoreCertificateErrors);
                _ = await httpClient.SendAsync(request);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Keep alive failed (at '{keepAlivePingUrl}').", keepAlivePingUrl);
            }
        }
    }
Example #26
0
        /// <summary>
        /// Returns a list of all installed file paths
        /// </summary>
        /// <param name="compiledPackage"></param>
        /// <param name="packageFile"></param>
        /// <param name="targetRootFolder">
        /// The absolute path of where to extract the package files (normally the application root)
        /// </param>
        /// <returns></returns>
        public IEnumerable <string> InstallFiles(CompiledPackage compiledPackage, FileInfo packageFile, string targetRootFolder)
        {
            using (_logger.DebugDuration <PackageFileInstallation>(
                       "Installing package files for package " + compiledPackage.Name,
                       "Package file installation complete for package " + compiledPackage.Name))
            {
                var sourceAndRelativeDest = _parser.ExtractSourceDestinationFileInformation(compiledPackage.Files);
                var sourceAndAbsDest      = AppendRootToDestination(targetRootFolder, sourceAndRelativeDest);

                _packageExtraction.CopyFilesFromArchive(packageFile, sourceAndAbsDest);

                return(sourceAndRelativeDest.Select(sd => sd.appRelativePath).ToArray());
            }
        }
Example #27
0
        public override async Task <bool> PerformRunAsync(CancellationToken token)
        {
            // not on replicas nor unknown role servers
            switch (_runtime.ServerRole)
            {
            case ServerRole.Replica:
                _logger.Debug <KeepAlive>("Does not run on replica servers.");
                return(true);    // role may change!

            case ServerRole.Unknown:
                _logger.Debug <KeepAlive>("Does not run on servers with unknown role.");
                return(true);    // role may change!
            }

            // ensure we do not run if not main domain, but do NOT lock it
            if (_runtime.IsMainDom == false)
            {
                _logger.Debug <KeepAlive>("Does not run if not MainDom.");
                return(false); // do NOT repeat, going down
            }

            using (_logger.DebugDuration <KeepAlive>("Keep alive executing", "Keep alive complete"))
            {
                var keepAlivePingUrl = _keepAliveSection.KeepAlivePingUrl;
                try
                {
                    if (keepAlivePingUrl.Contains("{umbracoApplicationUrl}"))
                    {
                        var umbracoAppUrl = _runtime.ApplicationUrl.ToString();
                        if (umbracoAppUrl.IsNullOrWhiteSpace())
                        {
                            _logger.Warn <KeepAlive>("No umbracoApplicationUrl for service (yet), skip.");
                            return(true); // repeat
                        }

                        keepAlivePingUrl = keepAlivePingUrl.Replace("{umbracoApplicationUrl}", umbracoAppUrl.TrimEnd(Constants.CharArrays.ForwardSlash));
                    }

                    var request = new HttpRequestMessage(HttpMethod.Get, keepAlivePingUrl);
                    var result  = await _httpClient.SendAsync(request, token);
                }
                catch (Exception ex)
                {
                    _logger.Error <KeepAlive>(ex, "Keep alive failed (at '{keepAlivePingUrl}').", keepAlivePingUrl);
                }
            }

            return(true); // repeat
        }
Example #28
0
        public override bool PerformRun()
        {
            if (!_fullTextConfig.IsFullTextIndexingEnabled())
            {
                return(false);
            }
            if (!_examineManager.TryGetIndex("ExternalIndex", out IIndex index))
            {
                _logger.Error <PerformCacheTasks>(new InvalidOperationException("No index found by name ExternalIndex"));
                return(false);
            }

            try
            {
                using (_profilingLogger.DebugDuration <PerformCacheTasks>("PerformCacheTasks", "PerformCacheTasks done"))
                {
                    var tasks = _cacheService.GetCacheTasks();

                    foreach (var task in tasks)
                    {
                        _cacheService.SetTaskAsStarted(task);
                    }

                    foreach (var task in tasks)
                    {
                        var content = _contentService.GetById(task.NodeId);
                        if (content != null)
                        {
                            _cacheService.AddToCache(task.NodeId);
                            index.IndexItems(_valueSetBuilder.GetValueSets(content));
                        }
                        else
                        {
                            _cacheService.DeleteFromCache(task.NodeId);
                        }
                        _cacheService.DeleteCacheTask(task.Id);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error <PerformCacheTasks>(e);
            }

            return(true);
        }
Example #29
0
        public void Initialize()
        {
            if (runtimeState.Level <= RuntimeLevel.Run)
            {
                logger.Info <uSyncBackofficeComponent>("Umbraco is not in Run Mode {0} so uSync is not going to run", runtimeState.Level);
                return;
            }

            if (runtimeState.ServerRole == Umbraco.Core.Sync.ServerRole.Replica)
            {
                logger.Info <uSyncBackofficeComponent>("This is a replica server, uSync will not run any of the startup events");
                return;
            }

            using (logger.DebugDuration <uSyncBackofficeComponent>("uSync Starting"))
            {
                InitBackOffice();
            }
        }
Example #30
0
        /// <summary>
        /// Returns a unique hash for a combination of FileInfo objects.
        /// </summary>
        /// <param name="filesAndFolders">A collection of files.</param>
        /// <param name="logger">A profiling logger.</param>
        /// <returns>The hash.</returns>
        // internal for tests
        public static string GetFileHash(IEnumerable <FileSystemInfo> filesAndFolders, IProfilingLogger logger)
        {
            using (logger.DebugDuration <TypeLoader>("Determining hash of code files on disk", "Hash determined"))
            {
                using (var generator = new HashGenerator())
                {
                    // get the distinct file infos to hash
                    var uniqInfos = new HashSet <string>();

                    foreach (var fileOrFolder in filesAndFolders)
                    {
                        if (uniqInfos.Contains(fileOrFolder.FullName))
                        {
                            continue;
                        }
                        uniqInfos.Add(fileOrFolder.FullName);
                        generator.AddFileSystemItem(fileOrFolder);
                    }
                    return(generator.GenerateHash());
                }
            }
        }