|
| 1 | +// Copyright 2020 New Relic, Inc. All rights reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Linq; |
| 7 | +using NewRelic.Agent.Configuration; |
| 8 | +using NewRelic.Agent.Core.DataTransport; |
| 9 | +using NewRelic.Agent.Core.Time; |
| 10 | +using NewRelic.Agent.Core.WireModels; |
| 11 | + |
| 12 | +namespace NewRelic.Agent.Core.Utilities |
| 13 | +{ |
| 14 | + public class UpdatedLoadedModulesService : DisposableService |
| 15 | + { |
| 16 | + private readonly IList<string> _loadedModulesSeen = new List<string>(); |
| 17 | + private readonly IScheduler _scheduler; |
| 18 | + private readonly IDataTransportService _dataTransportService; |
| 19 | + private readonly IConfigurationService _configurationService; |
| 20 | + private IConfiguration _configuration => _configurationService?.Configuration; |
| 21 | + |
| 22 | + public UpdatedLoadedModulesService(IScheduler scheduler, IDataTransportService dataTransportService, IConfigurationService configurationService) |
| 23 | + { |
| 24 | + _configurationService = configurationService; |
| 25 | + _dataTransportService = dataTransportService; |
| 26 | + _scheduler = scheduler; |
| 27 | + _scheduler.ExecuteEvery(GetLoadedModules, _configuration.UpdateLoadedModulesCycle); |
| 28 | + } |
| 29 | + |
| 30 | + private void GetLoadedModules() |
| 31 | + { |
| 32 | + var assemblies = AppDomain.CurrentDomain.GetAssemblies() |
| 33 | + .Where(assembly => assembly != null) |
| 34 | + .Where(assembly => !_loadedModulesSeen.Contains(assembly.GetName().Name)) |
| 35 | +#if NETFRAMEWORK |
| 36 | + .Where(assembly => !(assembly is System.Reflection.Emit.AssemblyBuilder)) |
| 37 | +#endif |
| 38 | + .ToList(); |
| 39 | + |
| 40 | + if (assemblies.Count < 1) |
| 41 | + { |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + var loadedModulesCollection = LoadedModuleWireModelCollection.Build(assemblies); |
| 46 | + |
| 47 | + SendUpdatedLoadedModules(loadedModulesCollection); |
| 48 | + } |
| 49 | + |
| 50 | + private void SendUpdatedLoadedModules(LoadedModuleWireModelCollection loadedModulesCollection) |
| 51 | + { |
| 52 | + var responseStatus = _dataTransportService.Send(loadedModulesCollection); |
| 53 | + if (responseStatus != DataTransportResponseStatus.RequestSuccessful) |
| 54 | + { |
| 55 | + // Try again next time |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + foreach (var module in loadedModulesCollection.LoadedModules) |
| 60 | + { |
| 61 | + _loadedModulesSeen.Add(module.Data["namespace"].ToString()); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments