public bool Initialize(ILogger logger)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            bool success;

            this.conversionToolPath = GetExeToolPath(logger);

            if (this.conversionToolPath == null)
            {
                logger.LogWarning(Resources.CONV_WARN_FailToFindConversionTool);
                success = false;
            }
            else
            {
                Debug.Assert(File.Exists(this.conversionToolPath), "Expecting the code coverage exe to exist. Full name: " + this.conversionToolPath);
                logger.LogDebug(Resources.CONV_DIAG_CommandLineToolInfo, this.conversionToolPath);
                success = true;
            }
            return success;
        }
Exemple #2
0
    /// <summary>
    /// Registers the bundles.
    /// </summary>
    /// <param name="bundles">The bundles.</param>
    /// <param name="logger">The logger.</param>
    public static void RegisterBundles(BundleCollection bundles, ILogger logger)
    {
      logger.LogDebug("START: ModuleConfig.RegisterBundles");
      try
      {
        logger.Indent();
        logger.LogDebug("GetViewModules");
        var vModules = MEFConfig.Container.GetExports<IViewModule>();

        // process each module
        logger.LogDebug("Iterating ViewModules");
        logger.Indent();
        foreach (var module in vModules)
        {
          // get the non lazy module value
          var mod = module.Value; // as IViewModule;

          if (mod != null)
          {
            // add any bundles the module may need
            mod.RegisterBundles(bundles);
          }

          logger.LogDebug(mod.GetType().FullName);
        }
        logger.UnIndent();

      }
      finally
      {
        logger.UnIndent();
        logger.LogDebug("END: ModuleConfig.RegisterBundles");
      }
    }
        public const int DelayBetweenRetriesInMilliseconds = 499; // Period to wait between retries

        #region Public methods

        /// <summary>
        /// Attempts to load the analysis config from the specified directory.
        /// Will retry if the file is locked.
        /// </summary>
        /// <returns>The loaded configuration, or null if the file does not exist or could not be
        /// loaded e.g. due to being locked</returns>
        public static AnalysisConfig TryGetConfig(string configDir, ILogger logger)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            AnalysisConfig config = null;
            if (string.IsNullOrEmpty(configDir)) // not specified
            {
                return null;
            }

            string fullAnalysisPath = Path.Combine(configDir, FileConstants.ConfigFileName);
            logger.LogDebug(Resources.Shared_ReadingConfigFile, fullAnalysisPath);
            if (!File.Exists(fullAnalysisPath))
            {
                logger.LogDebug(Resources.Shared_ConfigFileNotFound);
                return null;
            }

            bool succeeded = Utilities.Retry(MaxConfigRetryPeriodInMilliseconds, DelayBetweenRetriesInMilliseconds, logger,
                () => DoLoadConfig(fullAnalysisPath, logger, out config));
            if (succeeded)
            {
                logger.LogDebug(Resources.Shared_ReadingConfigSucceeded, fullAnalysisPath);
            }
            else
            {
                logger.LogError(Resources.Shared_ReadingConfigFailed, fullAnalysisPath);
            }
            return config;
        }
        private static LoggerVerbosity ComputeVerbosity(string sonarVerboseValue, string sonarLogValue, ILogger logger)
        {
            if (!String.IsNullOrWhiteSpace(sonarVerboseValue))
            {
                if (sonarVerboseValue.Equals("true", StringComparison.Ordinal))
                {
                    logger.LogDebug(Resources.MSG_SonarVerboseWasSpecified, sonarVerboseValue, LoggerVerbosity.Debug);
                    return LoggerVerbosity.Debug;
                }
                else if (sonarVerboseValue.Equals("false", StringComparison.Ordinal))
                {
                    logger.LogDebug(Resources.MSG_SonarVerboseWasSpecified, sonarVerboseValue, LoggerVerbosity.Info);
                    return LoggerVerbosity.Info;
                }
                else
                {
                    logger.LogWarning(Resources.WARN_SonarVerboseNotBool, sonarVerboseValue);
                }
            }

            if (!String.IsNullOrWhiteSpace(sonarLogValue))
            {
                if (sonarLogValue.Split('|').Any(s => s.Equals(SonarLogDebugValue, StringComparison.Ordinal)))
                {
                    logger.LogDebug(Resources.MSG_SonarLogLevelWasSpecified, sonarLogValue);
                    return LoggerVerbosity.Debug;
                }
            }

            return DefaultLoggingVerbosity;
        }
        public async Task HandleEvent(object evt, long?position)
        {
            var updateTask = GetUpdate(evt);
            var update     = updateTask == NoOp ? null : await updateTask;

            if (update == null)
            {
                _log?.LogDebug("No handler for {Event}", evt.GetType().Name);
                return;
            }

            _log?.LogDebug("Projecting {Event}", evt);

            var task = update switch {
                OtherOperation <T> operation => operation.Task,
                CollectionOperation <T> col => col.Execute(Collection),
                UpdateOperation <T> upd => ExecuteUpdate(upd),
                _ => Task.CompletedTask
            };

            await task;

            Task ExecuteUpdate(UpdateOperation <T> upd)
            => Collection.UpdateOneAsync(
                upd.Filter,
                upd.Update.Set(x => x.Position, position),
                new UpdateOptions {
                IsUpsert = true
            }
                );
        }
    public static List<string> FindWeaverConfigs(string solutionDirectoryPath, string projectDirectory, ILogger logger)
    {
        var files = new List<string>();
        var fodyDirConfigFilePath = Path.Combine(AssemblyLocation.CurrentDirectory, "FodyWeavers.xml");
        if (File.Exists(fodyDirConfigFilePath))
        {
            files.Add(fodyDirConfigFilePath);
            logger.LogDebug(string.Format("Found path to weavers file '{0}'.", fodyDirConfigFilePath));
        }

        var solutionConfigFilePath = Path.Combine(solutionDirectoryPath, "FodyWeavers.xml");
        if (File.Exists(solutionConfigFilePath))
        {
            files.Add(solutionConfigFilePath);
            logger.LogDebug(string.Format("Found path to weavers file '{0}'.", solutionConfigFilePath));
        }

		var projectConfigFilePath = Path.Combine(projectDirectory, "FodyWeavers.xml");
        if (File.Exists(projectConfigFilePath))
        {
            files.Add(projectConfigFilePath);
            logger.LogDebug(string.Format("Found path to weavers file '{0}'.", projectConfigFilePath));
        }


        if (files.Count == 0)
        {
            var pathsSearched = string.Join("', '", fodyDirConfigFilePath, solutionConfigFilePath, projectConfigFilePath);
            logger.LogDebug(string.Format("Could not find path to weavers file. Searched '{0}'.", pathsSearched));
        }
        return files;
    }
Exemple #7
0
    /// <summary>
    /// Start the Application.
    /// </summary>
    protected void Application_Start()
    {
      System.Diagnostics.Trace.WriteLine("{0} :: Application Starting".FormatWith(DateTime.Now.ToString("HH:mm:ss.ff")));

      // MEF will load all the modules from the specified path.
      // Currently this is just the normal bin folder as having them
      // anywhere else can cause problems for the views
      System.Diagnostics.Trace.WriteLine("{0} ::  Initialising MEF".FormatWith(DateTime.Now.ToString("HH:mm:ss.ff")));
      MEFConfig.RegisterMEF(this, Server.MapPath(@"~\bin\"));

      _logger = MEFConfig.Container.GetExport<ILogger>().Value;
      _settings = MEFConfig.Container.GetExport<ISettings>().Value;

      // once mef is configured we can check the database
      CheckDatabase();

      _logger.Indent();
      try
      {
        _logger.LogDebug("Configuring View Engine");
        // Setup a custom view engine.
        // This knows how to deal with views in module folders.
        ViewEngines.Engines.Clear();

        // WARNING!!! Helpers assume that JonesieViewEngine is the first index in the ViewEngines array!!! Changing this
        // will break a lot of things.
        ViewEngines.Engines.Add(new JonesieViewEngine(MEFConfig.Container.GetExports<IViewModule>()));

        // Just the usual MVC startup fluff
        AreaRegistration.RegisterAllAreas();
        AuthConfig.RegisterAuth(_settings);
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        // need to map the SignalR hub early
        RouteTable.Routes.MapHubs();

        // register routes for service and view modules and bundles for view modules
        ModuleConfig.RegisterRoutes(RouteTable.Routes, GlobalConfiguration.Configuration.Routes, _logger);
        ModuleConfig.RegisterBundles(BundleTable.Bundles, _logger);

        // now that everything else is done we can tell the modules to go ahead and get ready 
        ModuleConfig.InitialiseModules(_logger);

        // register the default routes and bundle after the modules
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        // we need to do this early so we can use IsInRole for security trimming the menus
        _logger.LogDebug("Initialising Web Security");
        WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", false);
      }
      finally
      {
        _logger.UnIndent();
      }

      _logger.LogDebug("Application Started");
    }
        /// <summary>
        /// Builds and returns the download URLs for all code coverage reports for the specified build
        /// </summary>
        public IEnumerable<string> GetCodeCoverageReportUrls(string tfsUri, string buildUri, ILogger logger)
        {
            if (string.IsNullOrWhiteSpace(tfsUri))
            {
                throw new ArgumentNullException("tfsUri");
            }
            if (string.IsNullOrWhiteSpace(buildUri))
            {
                throw new ArgumentNullException("buildUri");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            List<string> urls = new List<string>();

            logger.LogDebug(Resources.URL_DIAG_ConnectingToTfs);
            using (TfsTeamProjectCollection collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(tfsUri)))
            {
                IBuildServer buildServer = collection.GetService<IBuildServer>();

                logger.LogDebug(Resources.URL_DIAG_FetchingBuildInfo);
                IBuildDetail build = buildServer.GetMinimalBuildDetails(new Uri(buildUri));
                string projectName = build.TeamProject;

                logger.LogDebug(Resources.URL_DIAG_FetchingCoverageReportInfo);
                ITestManagementService tcm = collection.GetService<ITestManagementService>();
                ITestManagementTeamProject testProject = tcm.GetTeamProject(projectName);

                // TODO: investigate further. It looks as if we might be requesting the coverage reports
                // before the service is able to provide them.
                // For the time being, we're retrying with a time out.
                IBuildCoverage[] coverages = null;
                Utilities.Retry(TimeoutInMs, RetryPeriodInMs, logger, () => { return TryGetCoverageInfo(testProject, buildUri, out coverages); });

                foreach (IBuildCoverage coverage in coverages)
                {
                    logger.LogDebug(Resources.URL_DIAG_CoverageReportInfo, coverage.Configuration.Id, coverage.Configuration.BuildPlatform, coverage.Configuration.BuildPlatform);

                    string coverageFileUrl = CoverageReportUrlProvider.GetCoverageUri(build, coverage);
                    Debug.WriteLine(coverageFileUrl);
                    urls.Add(coverageFileUrl);
                }
            }

            logger.LogDebug(Resources.URL_DIAG_Finished);
            return urls;
        }
        /// <summary>
        /// Add or updates arbitrary storage configuration for a tenant.
        /// </summary>
        /// <param name="tenantStore">The tenant store.</param>
        /// <param name="tenant">The tenant to enroll.</param>
        /// <param name="configurationItems">Configuration to add.</param>
        /// <param name="logger">Optional logger.</param>
        /// <returns>A task which completes when the configuration has been added.</returns>
        public static async Task AddOrUpdateStorageConfigurationAsync(this ITenantStore tenantStore, ITenant tenant, ConfigurationItem[] configurationItems, ILogger?logger = null)
        {
            if (tenant == null)
            {
                throw new ArgumentNullException(nameof(tenant));
            }

            tenant.EnsureTenantIsOfType(MarainTenantType.Client);

            if (configurationItems == null)
            {
                throw new ArgumentNullException(nameof(configurationItems));
            }

            logger?.LogDebug(
                "Add configuration for tenant '{tenantName}' with Id '{tenantId}'",
                tenant.Name,
                tenant.Id);

            configurationItems.ValidateAndThrow();

            IEnumerable <KeyValuePair <string, object> > propertiesToAddToTenant = PropertyBagValues.Empty;

            foreach (ConfigurationItem configurationItem in configurationItems)
            {
                logger?.LogDebug(
                    "Adding configuration entry to tenant '{tenantName}' with Id '{tenantId}'",
                    tenant.Name,
                    tenant.Id);

                propertiesToAddToTenant = configurationItem.AddConfiguration(propertiesToAddToTenant);
            }

            logger?.LogDebug(
                "Updating tenant '{tenantName}' with Id '{tenantId}'",
                tenant.Name,
                tenant.Id);

            tenant = await tenantStore.UpdateTenantAsync(
                tenant.Id,
                propertiesToSetOrAdd : propertiesToAddToTenant)
                     .ConfigureAwait(false);

            logger?.LogInformation(
                "Successfully added configuration to tenant '{tenantName}' with Id '{tenantId}'",
                tenant.Name,
                tenant.Id);
        }
        private static bool TryCreateRuleset(ISonarQubeServer server, TeamBuildSettings settings, string projectKey, ILogger logger)
        {
            logger.LogDebug(Resources.SLAP_FetchingSonarLintRuleset);

            string rulesetContent;
            string parametersContent;
            if (TryGetProfileExportForProject(server, projectKey, logger, out rulesetContent, out parametersContent))
            {
                if (IsValidRuleset(rulesetContent))
                {
                    string ruleSetFilePath = GetRulesetFilePath(settings);
                    logger.LogDebug(Resources.SLAP_SonarLintRulesetCreated, ruleSetFilePath);
                    File.WriteAllText(ruleSetFilePath, rulesetContent);

                    string parametersFilePath = GetParametersFilePath(settings);
                    logger.LogDebug(Resources.SLAP_SonarLintParametersCreated, parametersFilePath);
                    File.WriteAllText(parametersFilePath, parametersContent);

                    return true;
                }
                else
                {
                    logger.LogError(Resources.SLAP_InvalidRulesetReturned);
                }
            }
            return false;
        }
Exemple #11
0
        public async Task HandleEvent(object evt, long?position)
        {
            var updateTask = GetUpdate(evt);
            var update     = updateTask == NoOp ? null : await updateTask;

            if (update == null)
            {
                _log?.LogDebug("No handler for {Event}", evt.GetType().Name);
                return;
            }

            update.Update.Set(x => x.Position, position);

            _log?.LogDebug("Projecting {Event}", evt);
            await _collection.UpdateOneAsync(update.Filter, update.Update, new UpdateOptions { IsUpsert = true });
        }
Exemple #12
0
 public BundleService(IApplicationEnvironment appEnvironment, ILogger<BundleService> logger)
 {
   _appEnvironment = appEnvironment;
   _logger = logger;
   _logger.LogDebug("Application base path: \"{0}\"", _appEnvironment.ApplicationBasePath);
   _logger.LogInformation("BundleService created");
 }
 public RequestPathAuthenticationPolicy(WebsiteSettings settings, ILogger logger)
 {
     _settings = settings;
     _logger = logger;
     var ignoredFilesSetting = _settings.AnonymousAccessFileExtensions;
     if (ignoredFilesSetting.IsEmpty())
     {
         _logger.LogDebug("Whitelisting authentication for default file extensions: {0}", DefaultExtensionWhiteList);
         ignoredFilesSetting = DefaultExtensionWhiteList;
     }
     else
     {
         _logger.LogDebug("Whitelisting authentication for file extensions from settings : {0}", ignoredFilesSetting);
     }
     _whiteListExtensions = new HashSet<string>(GetWhiteListedExtensions(ignoredFilesSetting), StringComparer.OrdinalIgnoreCase);
 }
        /// <summary>
        /// Sets up the client to run the SonarLint analyzer as part of the build
        /// i.e. creates the Rolsyn ruleset and provisions the analyzer assemblies
        /// </summary>
        public static void SetupAnalyzers(ISonarQubeServer server, TeamBuildSettings settings, string projectKey, ILogger logger)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (string.IsNullOrWhiteSpace(projectKey))
            {
                throw new ArgumentNullException("projectKey");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            if (IsCSharpPluginInstalled(server))
            {
                if (TryCreateRuleset(server, settings, projectKey, logger))
                {
                    FetchBinaries(server, settings, logger);
                }
            }
            else
            {
                logger.LogDebug(Resources.SLAP_CSharpPluginNotInstalled);
            }
        }
        private void OnBasicReturn(object?model, BasicReturnEventArgs args)
        {
            if (_logTraceEnabled)
            {
                _logger?.LogDebug(
                    "BasicReturn: {ReplyCode}-{ReplyText} {MessageId}",
                    args.ReplyCode,
                    args.ReplyText,
                    args.BasicProperties.MessageId
                    );
            }

            if (args.BasicProperties != null &&
                args.BasicProperties.Headers.TryGetValue("publishTag", out var value) &&
                value is byte[] bytes)
            {
                if (!ulong.TryParse(Encoding.UTF8.GetString(bytes), out var id))
                {
                    return;
                }

                if (_publishTasks.TryRemove(id, out var published))
                {
                    _logger?.LogWarning("returned! with {PublishTag}", id);

                    published.PublishReturned(args.ReplyCode, args.ReplyText);
                }
            }
        }
        private static void CopyIfDifferent(string sourcePath, IEnumerable<string> destinationDirs, ILogger logger)
        {
            string sourceContent = GetReadOnlyFileContent(sourcePath);
            string fileName = Path.GetFileName(sourcePath);

            foreach (string destinationDir in destinationDirs)
            {
                string destinationPath = Path.Combine(destinationDir, fileName);

                if (!File.Exists(destinationPath))
                {
                    Directory.CreateDirectory(destinationDir); // creates all the directories in the path if needed
                    File.Copy(sourcePath, destinationPath, overwrite: false);
                    logger.LogDebug(Resources.MSG_InstallTargets_Copy, fileName, destinationDir);
                }
                else
                {
                    string destinationContent = GetReadOnlyFileContent(destinationPath);

                    if (!String.Equals(sourceContent, destinationContent, StringComparison.Ordinal))
                    {
                        File.Copy(sourcePath, destinationPath, overwrite: true);
                        logger.LogDebug(Resources.MSG_InstallTargets_Overwrite, fileName, destinationDir);
                    }
                    else
                    {
                        logger.LogDebug(Resources.MSG_InstallTargets_UpToDate, fileName, destinationDir);
                    }
                }
            }
        }
        /// <summary>
        /// Gets a zip file containing the pre/post processors from the server
        /// </summary>
        /// <param name="hostUrl">The server Url</param>
        public bool TryUpdate(string hostUrl, string targetDir, ILogger logger)
        {
            if (string.IsNullOrWhiteSpace(hostUrl))
            {
                throw new ArgumentNullException("hostUrl");
            }
            if (string.IsNullOrWhiteSpace(targetDir))
            {
                throw new ArgumentNullException("targetDir");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string integrationUrl = GetDownloadZipUrl(hostUrl);
            string downloadedZipFilePath = Path.Combine(targetDir, BootstrapperSettings.SonarQubeIntegrationFilename);

            // SONARMSBRU-169 Support TLS versions 1.0, 1.1 and 1.2
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            using (WebClient client = new WebClient())
            {
                try
                {
                    logger.LogDebug(Resources.MSG_DownloadingZip, BootstrapperSettings.SonarQubeIntegrationFilename, integrationUrl, downloadedZipFilePath);
                    client.DownloadFile(integrationUrl, downloadedZipFilePath);
                }
                catch (WebException ex)
                {
                    if (Utilities.HandleHostUrlWebException(ex, hostUrl, logger))
                    {
                        return false;
                    }
                    logger.LogError(Resources.ERROR_FailedToUpdateRunnerBinaries, ex);
                    return false;
                }

                logger.LogDebug(Resources.MSG_ExtractingFiles, targetDir);
                ZipFile.ExtractToDirectory(downloadedZipFilePath, targetDir);
                return true;
            }
        }
        /// <summary>
        /// Ensures that the specified directory exists and is empty
        /// </summary>
        public static void EnsureEmptyDirectory(string directory, ILogger logger)
        {
            if (string.IsNullOrWhiteSpace(directory))
            {
                throw new ArgumentNullException("directory");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            if (Directory.Exists(directory))
            {
                logger.LogDebug(Resources.MSG_DeletingDirectory, directory);
                Directory.Delete(directory, true);
            }
            logger.LogDebug(Resources.MSG_CreatingDirectory, directory);
            Directory.CreateDirectory(directory);
        }
        /// <summary>
        /// Retries the specified operation until the specified timeout period expires
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="op">The operation to perform. Should return true if the operation succeeded, otherwise false.</param>
        /// <returns>True if the operation succeed, otherwise false</returns>
        public static bool Retry(int timeoutInMilliseconds, int pauseBetweenTriesInMilliseconds, ILogger logger, Func<bool> op)
        {
            if(timeoutInMilliseconds < 1)
            {
                throw new ArgumentOutOfRangeException("timeoutInMilliseconds");
            }
            if (pauseBetweenTriesInMilliseconds < 1)
            {
                throw new ArgumentOutOfRangeException("pauseBetweenTriesInMilliseconds");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            if (op == null)
            {
                throw new ArgumentNullException("op");
            }
            
            logger.LogDebug(Resources.MSG_BeginningRetry, timeoutInMilliseconds, pauseBetweenTriesInMilliseconds);

            Stopwatch timer = Stopwatch.StartNew();
            bool succeeded = op();

            while (!succeeded && timer.ElapsedMilliseconds < timeoutInMilliseconds)
            {
                logger.LogDebug(Resources.MSG_RetryingOperation);
                System.Threading.Thread.Sleep(pauseBetweenTriesInMilliseconds);
                succeeded = op();
            }

            timer.Stop();

            if (succeeded)
            {
                logger.LogDebug(Resources.MSG_RetryOperationSucceeded, timer.ElapsedMilliseconds);
            }
            else
            {
                logger.LogDebug(Resources.MSG_RetryOperationFailed, timer.ElapsedMilliseconds);
            }
            return succeeded;
        }
        /// <summary>
        /// Starts the hosted service and initializes the consumer or producer by either setting up the consumption of
        /// messages or by starting the producer's message queueing functionality.
        ///
        /// For details on the default implementations of consumers and producers, see <see cref="RabbitMqConsumer{T}"/>
        /// and <see cref="RabbitMqProducer{T}"/>.
        /// </summary>
        /// <param name="cancellationToken"/>
        /// <returns/>
        public virtual Task StartAsync(CancellationToken cancellationToken)
        {
            Debug.Assert(
                _isProperlyInitialized,
                $"This {nameof(RabbitMqService<T>)} instance should have been created through a call to " +
                $"{nameof(RabbitMqService<T>)}.{nameof(Create)}.");

            _logger?.LogInformation($"RabbitMqService {_rmqConfig.Id} is starting.");

            if (Bus.IsConnected)
            {
                _logger?.LogDebug($"Connected to RabbitMQ with configuration {_rmqConfig.Id}.");
            }

            Bus.Connected += (sender, args) =>
                             _logger?.LogDebug($"Connected to RabbitMQ with configuration {_rmqConfig.Id}.");

            Bus.Disconnected += (sender, args) =>
                                _logger?.LogDebug($"Disconnected from RabbitMQ with configuration {_rmqConfig.Id}.");

            // run the setup callbacks on connection

            if (Bus.IsConnected)
            {
                _onConnected.ForEach(callback =>
                                     HandleCallbackError(callback)(Bus, _rmqConfig, cancellationToken, _logger));
            }

            _onConnected.ForEach(callback => Bus.Connected += (sender, args) =>
                                                              HandleCallbackError(callback)(Bus, _rmqConfig, cancellationToken, _logger));

            if (_isConsumer)
            {
                InitializeConsumer(cancellationToken);
            }
            else
            {
                InitializeProducer(cancellationToken);
            }

            return(Task.CompletedTask);
        }
Exemple #21
0
        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            base.OnEventWritten(eventData);

            if (!IsHttpEventSource(eventData.EventSource))
            {
                return;
            }

            string message;

            lock (_messageBuilder)
            {
                _messageBuilder.Append("<- Event ");
                _messageBuilder.Append(eventData.EventSource.Name);
                _messageBuilder.Append(" - ");
                _messageBuilder.Append(eventData.EventName);
                _messageBuilder.Append(" : ");
#if !NET472
                _messageBuilder.AppendJoin(',', eventData.Payload !);
#else
                _messageBuilder.Append(string.Join(",", eventData.Payload !.ToArray()));
#endif
                _messageBuilder.Append(" ->");
                message = _messageBuilder.ToString();
                _messageBuilder.Clear();
            }

            // We don't know the state of the logger after dispose.
            // Ensure that any messages written in the background aren't
            // logged after the listener has been disposed in the test.
            lock (_lock)
            {
                if (!_disposed)
                {
                    // EventListener base constructor subscribes to events.
                    // It is possible to start getting events before the
                    // super constructor is run and logger is assigned.
                    _logger?.LogDebug(message);
                }
            }
        }
        /// <summary>
        /// Creates a new tenant representing a Marain service that tenants can enroll to use.
        /// </summary>
        /// <param name="tenantStore">The tenant store.</param>
        /// <param name="manifest">
        /// The manifest for the service. The service name in the manifest must be unique across all service tenants.
        /// </param>
        /// <param name="logger">Optional logger.</param>
        /// <returns>The new tenant.</returns>
        public static async Task <ITenant> CreateServiceTenantAsync(this ITenantStore tenantStore, ServiceManifest manifest, ILogger?logger = null)
        {
            if (manifest == null)
            {
                throw new ArgumentNullException(nameof(manifest));
            }

            logger?.LogDebug("Validating service manifest for service creation.");

            await manifest.ValidateAndThrowAsync(tenantStore).ConfigureAwait(false);

            ITenant parent = await tenantStore.GetServiceTenantParentAsync().ConfigureAwait(false);

            logger?.LogDebug(
                "Creating new service tenant '{serviceName}' with well-known GUID '{wellKnownGuid}'",
                manifest.ServiceName,
                manifest.WellKnownTenantGuid);

            ITenant newTenant = await tenantStore.CreateWellKnownChildTenantAsync(
                parent.Id,
                manifest.WellKnownTenantGuid,
                manifest.ServiceName).ConfigureAwait(false);

            logger?.LogDebug(
                "New service tenant '{serviceName}' created with Id '{tenantId}'; updating tenant type and manifest.",
                newTenant.Name,
                newTenant.Id);

            IEnumerable <KeyValuePair <string, object> > properties = PropertyBagValues.Build(p => p
                                                                                              .AddServiceManifest(manifest)
                                                                                              .AddMarainTenantType(MarainTenantType.Service));

            await tenantStore.UpdateTenantAsync(
                newTenant.Id,
                propertiesToSetOrAdd : properties).ConfigureAwait(false);

            logger?.LogInformation(
                "Created new service tenant '{serviceName}' with Id '{tenantId}'.",
                newTenant.Name,
                newTenant.Id);
            return(newTenant);
        }
        public /* for test */ static ProjectInfoAnalysisResult GenerateFile(AnalysisConfig config, ILogger logger, IRoslynV1SarifFixer fixer)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string fileName = Path.Combine(config.SonarOutputDir, ProjectPropertiesFileName);
            logger.LogDebug(Resources.MSG_GeneratingProjectProperties, fileName);

            IEnumerable<ProjectInfo> projects = ProjectLoader.LoadFrom(config.SonarOutputDir);
            if (projects == null || !projects.Any())
            {
                logger.LogError(Resources.ERR_NoProjectInfoFilesFound);
                return new ProjectInfoAnalysisResult();
            }

            FixSarifReport(logger, projects, fixer);

            PropertiesWriter writer = new PropertiesWriter(config);

            ProjectInfoAnalysisResult result = ProcessProjectInfoFiles(projects, writer, logger);

            IEnumerable<ProjectInfo> validProjects = result.GetProjectsByStatus(ProjectInfoValidity.Valid);

            if (validProjects.Any())
            {
                // Handle global settings
                AnalysisProperties properties = GetAnalysisPropertiesToWrite(config, logger);
                writer.WriteGlobalSettings(properties);

                string contents = writer.Flush();

                result.FullPropertiesFilePath = fileName;
                File.WriteAllText(result.FullPropertiesFilePath, contents, Encoding.ASCII);
            }
            else
            {
                // if the user tries to build multiple configurations at once there will be duplicate projects
                if (result.GetProjectsByStatus(ProjectInfoValidity.DuplicateGuid).Any())
                {
                    logger.LogError(Resources.ERR_NoValidButDuplicateProjects);
                }
                else
                {
                    logger.LogError(Resources.ERR_NoValidProjectInfoFiles);
                }
            }
            return result;
        }
Exemple #24
0
        public async Task <string?> TryGetEncryptedSeed()
        {
            if (!File.Exists(SeedFilePath))
            {
                return(null);
            }
            _logger?.LogDebug($"reading seed from {SeedFilePath}");
            var encryptedSeed = await File.ReadAllTextAsync(SeedFilePath);

            return(string.IsNullOrEmpty(encryptedSeed) ? null : encryptedSeed);
        }
        public static void ExecuteAndVerifyResult(this Process process, ILogger logger, ResultExpectation resultExpectation = ResultExpectation.MustNotFail)
        {
            Guard.That(process).IsNotNull();
            Guard.That(resultExpectation).IsValidValue();
            Guard.That(logger).IsNotNull();

            logger.LogDebug("Running process \"{0}\"", process.Options.CommandLine);
            ProcessResult result = process.Run();

            VerifyProcessRan(process, result);
            VerifyExitCode(process, result, resultExpectation, logger);
        }
        public async Task PullImageAsync(string imageName, string tag, CancellationToken cancellationToken = default)
        {
            var images = await _dockerClient.Images.ListImagesAsync(
                new ImagesListParameters
            {
                All     = true,
                Filters = new Dictionary <string, IDictionary <string, bool> >
                {
                    ["reference"] = new Dictionary <string, bool> {
                        [$"{imageName}:{tag}"] = true
                    }
                }
            },
                cancellationToken);

            if (!images.Any())
            {
                _logger?.LogInformation($"Pulling the image {imageName}:{tag}");

                // Pull the image.
                try
                {
                    await _dockerClient.Images.CreateImageAsync(
                        new ImagesCreateParameters
                    {
                        FromImage = imageName,
                        Tag       = tag
                    },
                        null,
                        new Progress <JSONMessage>(m => _logger?.LogDebug($"Pulling image {imageName}:{tag}:\n{m.ProgressMessage}")),
                        cancellationToken);
                }
                catch (Exception exc)
                {
                    _logger?.LogError(exc, $"Unable to pull the image {imageName}:{tag}");
                    throw;
                }
            }
        }
        /// <summary>
        /// Creates a new tenant representing a client, using a well known Guid.
        /// </summary>
        /// <param name="tenantStore">The tenant store.</param>
        /// <param name="wellKnownGuid">The well known Guid to use when creating the tenant.</param>
        /// <param name="clientName">The name of the new tenant.</param>
        /// <param name="parentId">Optional ID of parent Client tenant.</param>
        /// <param name="logger">Optional logger.</param>
        /// <returns>The new tenant.</returns>
        public static async Task <ITenant> CreateClientTenantWithWellKnownGuidAsync(this ITenantStore tenantStore, Guid wellKnownGuid, string clientName, string?parentId = null, ILogger?logger = null)
        {
            if (string.IsNullOrWhiteSpace(clientName))
            {
                throw new ArgumentException(nameof(clientName));
            }

            ITenant parent;

            if (!string.IsNullOrEmpty(parentId))
            {
                parent = await tenantStore.GetTenantOfTypeAsync(parentId, MarainTenantType.Client).ConfigureAwait(false);
            }
            else
            {
                parent = await tenantStore.GetClientTenantParentAsync().ConfigureAwait(false);
            }

            logger?.LogDebug("Creating new client tenant '{clientName}' with GUID '{wellKnownGuid}'", clientName, wellKnownGuid);
            ITenant newTenant = await tenantStore.CreateWellKnownChildTenantAsync(
                parent.Id,
                wellKnownGuid,
                clientName).ConfigureAwait(false);

            logger?.LogDebug(
                "New client tenant '{clientName}' created with Id '{tenantId}'; updating tenant type.",
                newTenant.Name,
                newTenant.Id);

            await tenantStore.UpdateTenantAsync(
                newTenant.Id,
                propertiesToSetOrAdd : PropertyBagValues.Build(p => p.AddMarainTenantType(MarainTenantType.Client))).ConfigureAwait(false);

            logger?.LogInformation(
                "Created new client tenant '{clientName}' with Id '{tenantId}'.",
                newTenant.Name,
                newTenant.Id);
            return(newTenant);
        }
        public static X509Certificate2 GetCredentialFromConfig(IConfigurationSection options, ILogger?logger)
        {
            string keyType = options.GetValue <string>(KeyType);

            logger?.LogDebug($"CredentialsHelper keyType is {keyType}");

            switch (keyType)
            {
            case KeyTypeTemporary:
                logger?.LogDebug($"CredentialsHelper adding Temporary Signing Credential");
                //return GetCertificateTemporary();
                // TODO
                break;

            case KeyTypeKeyFile:
                return(GetCertificateFromFile(options, logger));

            case KeyTypeKeyStore:
                return(GetCertificateFromStore(options, logger));
            }

            throw new Exception($"keyType {keyType} not found");
        }
        private static async Task <ITenant> CreateDelegatedTenant(this ITenantStore tenantStore, ITenant accessingTenant, ITenant serviceTenant, ILogger?logger = null)
        {
            string delegatedTenantName = TenantNames.DelegatedTenant(serviceTenant.Name, accessingTenant.Name);

            logger?.LogDebug("Creating new delegated tenant '{delegatedTenantName}'", delegatedTenantName);
            ITenant delegatedTenant = await tenantStore.CreateChildTenantAsync(serviceTenant.Id, delegatedTenantName).ConfigureAwait(false);

            logger?.LogDebug(
                "New delegated tenant '{delegatedTenantName}' created with Id '{tenantId}'; updating tenant type.",
                delegatedTenant.Name,
                delegatedTenant.Id);

            delegatedTenant = await tenantStore.UpdateTenantAsync(
                delegatedTenant.Id,
                propertiesToSetOrAdd : PropertyBagValues.Build(p => p.AddMarainTenantType(MarainTenantType.Delegated)))
                              .ConfigureAwait(false);

            logger?.LogInformation(
                "Created new delegated tenant '{delegatedTenantName}' with Id '{tenantId}'.",
                delegatedTenant.Name,
                delegatedTenant.Id);
            return(delegatedTenant);
        }
        public async Task <ContainerRuntimeInfo> RunContainerAsync(ContainerParameters containerParameters, CancellationToken cancellationToken = default)
        {
            var(name, reusable) = (containerParameters.Name, containerParameters.Reusable);

            // Try to find container in docker session
            var startedContainer = await GetContainerAsync(name, cancellationToken);

            // If container already exist - remove that
            if (startedContainer != null)
            {
                // TODO: check status and network
                if (!reusable)
                {
                    await _dockerClient.Containers.RemoveContainerAsync(
                        startedContainer.ID,
                        new ContainerRemoveParameters { Force = true },
                        cancellationToken);

                    startedContainer = await CreateContainer(containerParameters, cancellationToken);
                }
            }
            else
            {
                startedContainer = await CreateContainer(containerParameters, cancellationToken);
            }

            _logger?.LogInformation($"Container '{name}' has been run.");
            _logger?.LogDebug($"Container state: {startedContainer.State}");
            _logger?.LogDebug($"Container status: {startedContainer.Status}");
            _logger?.LogDebug(
                $"Container IPAddress: {startedContainer.NetworkSettings.Networks.FirstOrDefault().Key} - {startedContainer.NetworkSettings.Networks.FirstOrDefault().Value.IPAddress}");

            var ipAddress = startedContainer.NetworkSettings.Networks.FirstOrDefault().Value.IPAddress;
            var ports     = startedContainer.Ports.DistinctBy(p => p.PrivatePort).ToDictionary(p => p.PrivatePort, p => p.PublicPort);

            return(new(startedContainer.ID, ipAddress, ports));
        }
Exemple #31
0
        /// <summary>
        ///     id is not null, valueSubscription is not null
        /// </summary>
        /// <param name="id"></param>
        /// <param name="clientObj"></param>
        public void AddItem(string id, object clientObj)
        {
            Logger?.LogDebug("XiListItemsManager.AddItem() " + id);

            ClientObjectInfo?modelItem;

            if (!_clientObjectInfosDictionary.TryGetValue(clientObj, out modelItem))
            {
                modelItem = new ClientObjectInfo(id);
                _clientObjectInfosDictionary.Add(clientObj, modelItem);
                modelItem.ClientObj = clientObj;

                _xiItemsMustBeAddedOrRemoved = true;
            }
        }
Exemple #32
0
        private static ContractDescription CreateDescription(Type serviceType, ILogger?logger)
        {
            var contractDescription = new ContractDescription(serviceType);

            foreach (var interfaceDescription in contractDescription.Interfaces)
            {
                logger?.LogDebug("{0}: {1} is not service contract.", serviceType.FullName, interfaceDescription.InterfaceType.FullName);
            }

            foreach (var interfaceDescription in contractDescription.Services)
            {
                foreach (var method in interfaceDescription.Methods)
                {
                    logger?.LogDebug("{0}: {1}", serviceType.FullName, method.Error);
                }

                foreach (var method in interfaceDescription.NotSupportedOperations)
                {
                    logger?.LogError("{0}: {1}", serviceType.FullName, method.Error);
                }
            }

            return(contractDescription);
        }
        internal static IPrintService Create(IConfigService configService, ILogger logger)
        {
            IPrintService printService = null;
            PrintServiceConfig printServiceConfig = configService.Get<PrintServiceConfig>("PrintManager", "ServiceConfig", null);
            if (null == printServiceConfig)
            {
                printService = new PrintServiceNull();
                logger.LogDebug("PrintService", "Print Service not configured. All request to print will throw exception");
            }
            else
            {
                printService = new PrintService(printServiceConfig, logger);
            }

            return printService;
        }
        private IEnumerable <ComparisonResult> CompareMatchingItems(ItemMatch <T> match, ComparerOptions options)
        {
            var results = EvaluateMatch(match, options);

            foreach (var result in results)
            {
                _logger?.LogDebug(result.Message);

                if (result.ChangeType == SemVerChangeType.None)
                {
                    // Don't add comparison results to the outcome where it looks like there is no change
                    continue;
                }

                yield return(result);
            }
        }
        /// <summary>
        /// Start all listeners.
        /// </summary>
        /// <returns>the task.</returns>
        public async Task StartAsync()
        {
            _logger?.LogDebug("Server configured for listening on {address}:{port}", _address, _port);

            List <IPAddress> addresses;

            if (string.IsNullOrEmpty(_address) || _address == IPAddress.Any.ToString())
            {
                // "0.0.0.0"
                addresses = new List <IPAddress> {
                    IPAddress.Any
                };
            }
            else if (_address == IPAddress.IPv6Any.ToString())
            {
                // "::"
                addresses = new List <IPAddress> {
                    IPAddress.IPv6Any
                };
            }
            else if (_address == "*")
            {
                addresses = new List <IPAddress> {
                    IPAddress.Any, IPAddress.IPv6Any
                };
            }
            else
            {
                var dnsAddresses = await Dns.GetHostAddressesAsync(_address).ConfigureAwait(false);

                addresses = dnsAddresses
                            .Where(x => x.AddressFamily == AddressFamily.InterNetwork ||
                                   x.AddressFamily == AddressFamily.InterNetworkV6)
                            .ToList();
            }

            try
            {
                Port = StartListening(addresses, _port);
            }
            catch
            {
                Stop();
                throw;
            }
        }
Exemple #36
0
    /// <summary>
    /// Registers the routes.
    /// </summary>
    /// <param name="viewRoutes">The view routes.</param>
    /// <param name="apiRoutes">The API routes.</param>
    /// <param name="logger">The logger.</param>
    public static void RegisterRoutes(RouteCollection viewRoutes, HttpRouteCollection apiRoutes, ILogger logger)
    {

      logger.LogDebug("START: ModuleConfig.RegisterRoutes");
      try
      {
        logger.Indent();

        logger.LogDebug("GetViewModules");
        var vModules = MEFConfig.Container.GetExports<IViewModule>();
        logger.LogDebug("GetServiceModules");
        var sModules = MEFConfig.Container.GetExports<IServiceModule>();

        logger.LogDebug("Iterating ViewModules");
        logger.Indent();
        foreach (var module in vModules)
        {
          var mod = module.Value;
          mod.RegisterRoutes(viewRoutes);

          logger.LogDebug(mod.GetType().FullName);
        }
        logger.UnIndent();

        logger.LogDebug("Iterating ServiceModules");
        logger.Indent();
        foreach (var module in sModules)
        {
          var mod = module.Value;
          mod.RegisterRoutes(apiRoutes);

          logger.LogDebug(mod.GetType().FullName);
        }
        logger.UnIndent();
      }
      finally
      {
        logger.UnIndent();
        logger.LogDebug("END: ModuleConfig.RegisterRoutes");
      }
    }
 private void Connect()
 {
     try
     {
         var res = base.ConnectServer();
         if (IsConnected)
         {
             _Logger?.LogDebug("Server \"{ServerName}\" with address \"{ServerAddress}\" connected.", _PortName, ServerAddress);
         }
         else
         {
             _Logger?.LogWarning("Could not connect server \"{ServerName}\" with address \"{ServerAddress}\".", _PortName, ServerAddress);
         }
     }
     catch (AdsException ex)
     {
         _Logger?.LogError(ex, "Could not register server \"{ServerName}\".", _PortName);
     }
 }
        private static int PreProcess(IBuildAgentUpdater updater, IBootstrapperSettings settings, ILogger logger)
        {
            string downloadBinPath = settings.DownloadDirectory;

            logger.LogInfo(Resources.MSG_PreparingDirectories);
            if (!Utilities.TryEnsureEmptyDirectories(logger,
                settings.TempDirectory,
                downloadBinPath))
            {
                return ErrorCode;
            }

            string server = settings.SonarQubeUrl;
            Debug.Assert(!string.IsNullOrWhiteSpace(server), "Not expecting the server url to be null/empty");
            logger.LogDebug(Resources.MSG_ServerUrl, server);

            logger.LogInfo(Resources.MSG_CheckingForUpdates);
            if (!updater.TryUpdate(server, downloadBinPath, logger))
            {
                logger.LogError(Resources.ERROR_FailedToUpdateRunnerBinaries);
                return ErrorCode;
            }

            if (!updater.CheckBootstrapperApiVersion(settings.SupportedBootstrapperVersionsFilePath, settings.BootstrapperVersion))
            {
                logger.LogError(Resources.ERROR_VersionMismatch);
                return ErrorCode;
            }

            var preprocessorFilePath = settings.PreProcessorFilePath;

            ProcessRunnerArguments runnerArgs = new ProcessRunnerArguments(preprocessorFilePath, logger)
            {
                CmdLineArgs = settings.ChildCmdLineArgs,
                WorkingDirectory = settings.TempDirectory,
            };
            ProcessRunner runner = new ProcessRunner();
            runner.Execute(runnerArgs);

            return runner.ExitCode;
        }
Exemple #39
0
 private async void HoldSubscription()
 {
     while (workingTaskCancellationTokenSource != null && !workingTaskCancellationTokenSource.Token.IsCancellationRequested)
     {
         try
         {
             subscription         = _subscriptionFactory.Invoke();
             subscriptionListener = new ServerToClientStreamListener <TReceivedEvent>(subscription);
             subscriptionListener.ServerEventReceived += _eventHandler.Invoke;
             _logger?.LogDebug($"Subscription of type {nameof(TReceivedEvent)} prepared. Beginning to listen...");
             await subscriptionListener.ListenAsync();
         }
         catch (RpcException)
         {
             _logger?.LogWarning($"Encountered a RpcException while trying to configure the {nameof(TReceivedEvent)} subscription. Retrying in {retryTimeoutMilliseconds / 1000} seconds...");
             await Task.Delay(retryTimeoutMilliseconds);
         }
         catch (Exception ex)
         {
             _logger?.LogError($"Encountered an unexpected exception while trying to configure the {nameof(TReceivedEvent)} subscription: {ex} ({ex.Message}). Retrying in {retryTimeoutMilliseconds / 1000} seconds...");
             await Task.Delay(retryTimeoutMilliseconds);
         }
     }
 }
        private static void SetEnvironmentVariables(ProcessStartInfo psi, IDictionary<string, string> envVariables, ILogger logger)
        {
            if (envVariables == null)
            {
                return;
            }

            foreach (KeyValuePair<string, string> envVariable in envVariables)
            {
                Debug.Assert(!String.IsNullOrEmpty(envVariable.Key), "Env variable name cannot be null or empty");

                if (psi.EnvironmentVariables.ContainsKey(envVariable.Key))
                {
                    logger.LogDebug(Resources.MSG_Runner_OverwritingEnvVar, envVariable.Key, psi.EnvironmentVariables[envVariable.Key], envVariable.Value);
                }
                else
                {
                    logger.LogDebug(Resources.MSG_Runner_SettingEnvVar, envVariable.Key, envVariable.Value);
                }
                psi.EnvironmentVariables[envVariable.Key] = envVariable.Value;
            }
        }
        private static string TryGetDefaultPropertiesFilePath(string defaultDirectory, ILogger logger)
        {
            string fullPath = Path.Combine(defaultDirectory, DefaultFileName);
            if (File.Exists(fullPath))
            {
                logger.LogDebug(Resources.MSG_Properties_DefaultPropertiesFileFound, fullPath);
                return fullPath;
            }
            else
            {
                logger.LogDebug(Resources.MSG_Properties_DefaultPropertiesFileNotFound, fullPath);

                return null;
            }
        }
        /// <summary>
        /// Attempt to find a properties file - either the one specified by the user, or the default properties file.
        /// Returns true if the path to a file could be resolved, othewise false.
        /// </summary>
        private static bool ResolveFilePath(string propertiesFilePath, string defaultPropertiesFileDirectory, ILogger logger, out AnalysisProperties properties)
        {
            properties = null;
            bool isValid = true;

            string resolvedPath = propertiesFilePath ?? TryGetDefaultPropertiesFilePath(defaultPropertiesFileDirectory, logger);

            if (resolvedPath != null)
            {
                if (File.Exists(resolvedPath))
                {
                    try
                    {
                        logger.LogDebug(Resources.MSG_Properties_LoadingPropertiesFromFile, resolvedPath);
                        properties = AnalysisProperties.Load(resolvedPath);
                    }
                    catch (InvalidOperationException)
                    {
                        logger.LogError(Resources.ERROR_Properties_InvalidPropertiesFile, resolvedPath);
                        isValid = false;
                    }
                }
                else
                {
                    logger.LogError(Resources.ERROR_Properties_GlobalPropertiesFileDoesNotExist, resolvedPath);
                    isValid = false;
                }
            }
            return isValid;
        }
Exemple #43
0
        public void Bind(IServiceMethodBinder <TService> binder)
        {
            var contract        = EmitContractBuilder.CreateFactory(_contractType)(binder.MarshallerFactory);
            var channelInstance = EmitServiceEndpointBuilder.CreateFactory(_channelType)();
            var serviceType     = typeof(TService);

            foreach (var interfaceDescription in _description.Services)
            {
                foreach (var operation in interfaceDescription.Operations)
                {
                    var message          = operation.Message;
                    var channelMethod    = _channelType.InstanceMethod(operation.OperationName);
                    var metadata         = TryGetMethodMetadata(interfaceDescription.InterfaceType, message.Operation);
                    var grpcMethodMethod = (IMethod)_contractType.InstanceFiled(operation.GrpcMethodName).GetValue(contract);

                    object?requestHeaderMarshaller = null;
                    if (message.HeaderRequestType != null)
                    {
                        requestHeaderMarshaller = _contractType.InstanceFiled(operation.GrpcMethodInputHeaderName).GetValue(contract);
                    }

                    object?responseHeaderMarshaller = null;
                    if (message.HeaderResponseType != null)
                    {
                        responseHeaderMarshaller = _contractType.InstanceFiled(operation.GrpcMethodOutputHeaderName).GetValue(contract);
                    }

                    _logger?.LogDebug("Bind service method {0}.{1}.", serviceType.FullName, message.Operation.Name);
                    if (grpcMethodMethod.Type == MethodType.Unary)
                    {
                        var addMethod = _serviceBinderAddUnaryMethod
                                        .MakeGenericMethod(message.RequestType, message.ResponseType)
                                        .CreateDelegate <Action <IServiceMethodBinder <TService>, IMethod, MethodInfo, IList <object>, MethodInfo, object> >();
                        addMethod(binder, grpcMethodMethod, message.Operation, metadata, channelMethod, channelInstance);
                    }
                    else if (grpcMethodMethod.Type == MethodType.ClientStreaming)
                    {
                        var addMethod = _serviceBinderAddClientStreamingMethod
                                        .MakeGenericMethod(
                            message.HeaderRequestType ?? typeof(Message),
                            message.RequestType.GenericTypeArguments[0],
                            message.ResponseType)
                                        .CreateDelegate <Action <IServiceMethodBinder <TService>, IMethod, MethodInfo, object?, IList <object>, MethodInfo, object> >();
                        addMethod(binder, grpcMethodMethod, message.Operation, requestHeaderMarshaller, metadata, channelMethod, channelInstance);
                    }
                    else if (grpcMethodMethod.Type == MethodType.ServerStreaming)
                    {
                        var addMethod = _serviceBinderAddServerStreamingMethod
                                        .MakeGenericMethod(
                            message.RequestType,
                            message.HeaderResponseType ?? typeof(Message),
                            message.ResponseType.GenericTypeArguments[0])
                                        .CreateDelegate <Action <IServiceMethodBinder <TService>, IMethod, MethodInfo, object?, IList <object>, MethodInfo, object> >();
                        addMethod(binder, grpcMethodMethod, message.Operation, responseHeaderMarshaller, metadata, channelMethod, channelInstance);
                    }
                    else if (grpcMethodMethod.Type == MethodType.DuplexStreaming)
                    {
                        var addMethod = _serviceBinderAddDuplexStreamingMethod
                                        .MakeGenericMethod(
                            message.HeaderRequestType ?? typeof(Message),
                            message.RequestType.GenericTypeArguments[0],
                            message.HeaderResponseType ?? typeof(Message),
                            message.ResponseType.GenericTypeArguments[0])
                                        .CreateDelegate <Action <IServiceMethodBinder <TService>, IMethod, MethodInfo, object?, object?, IList <object>, MethodInfo, object> >();
                        addMethod(binder, grpcMethodMethod, message.Operation, requestHeaderMarshaller, responseHeaderMarshaller, metadata, channelMethod, channelInstance);
                    }
                    else
                    {
                        throw new NotImplementedException("{0} operation is not implemented.".FormatWith(grpcMethodMethod.Type));
                    }
                }
            }
        }
        public IActionResult getUsers([FromQuery] string filter, [RequiredFromQuery] int startIndex, [RequiredFromQuery] int count)
        {
            _logger.LogDebug("Enter getAllUsers by Filter ");
            SCIMFilter myFilter = null;

            if (!string.IsNullOrEmpty(filter))
            {
                myFilter = SCIMFilter.TryParse(filter);
            }


            PaginationProperties pp = new PaginationProperties(count, startIndex);

            try
            {
                cvs_SCIM20.Okta.SCIM.Models.SCIMUserQueryResponse rGetUsers = _connector.getUsers(pp, myFilter);
                if (rGetUsers == null)
                {
                    _logger.LogDebug("Exit no users not found");
                    return(NotFound());
                }
                else
                {
                    _logger.LogDebug("Exit Successfully user found ");
                    return(Ok(rGetUsers));
                }
            }
            catch (EntityNotFoundException e)
            {
                _logger.LogDebug("Exit entity not found trying to get user");
                return(NotFound());
            }
            catch (Exception e)
            {
                _logger.LogDebug("Exit Error at getUser  ");
                _logger.LogError(e.ToString());
                return(StatusCode(StatusCodes.Status500InternalServerError, e));
            }
        }
        /// <summary>
        /// Enrolls the specified tenant in the service.
        /// </summary>
        /// <param name="tenantStore">The tenant store.</param>
        /// <param name="enrollingTenant">The tenant to enroll.</param>
        /// <param name="serviceTenant">The service to enroll in.</param>
        /// <param name="configurationItems">Configuration for the enrollment.</param>
        /// <param name="logger">Optional logger.</param>
        /// <returns>A task which completes when the enrollment has finished.</returns>
        public static async Task EnrollInServiceAsync(
            this ITenantStore tenantStore,
            ITenant enrollingTenant,
            ITenant serviceTenant,
            EnrollmentConfigurationItem[] configurationItems,
            ILogger?logger = null)
        {
            if (enrollingTenant == null)
            {
                throw new ArgumentNullException(nameof(enrollingTenant));
            }

            enrollingTenant.EnsureTenantIsOfType(MarainTenantType.Client, MarainTenantType.Delegated);

            if (serviceTenant == null)
            {
                throw new ArgumentNullException(nameof(serviceTenant));
            }

            serviceTenant.EnsureTenantIsOfType(MarainTenantType.Service);

            if (configurationItems == null)
            {
                throw new ArgumentNullException(nameof(configurationItems));
            }

            logger?.LogDebug(
                "Enrolling tenant '{enrollingTenantName}' with Id '{enrollingTenantId}' from service '{serviceTenantName}' with Id '{serviceTenantId}'",
                enrollingTenant.Name,
                enrollingTenant.Id,
                serviceTenant.Name,
                serviceTenant.Id);

            // First we need to ensure that all the required config items for both the service being enrolled in,
            // as well as any dependent services is provided.
            ServiceManifestRequiredConfigurationEntry[] requiredConfig = await tenantStore.GetServiceEnrollmentConfigurationRequirementsAsync(serviceTenant).ConfigureAwait(false);

            logger?.LogDebug("Validating supplied configuration against required config.");
            configurationItems.ValidateAndThrow(requiredConfig);

            ServiceManifest manifest = serviceTenant.GetServiceManifest();

            // Now, match up the required config items for this service to the relevent supplied config (we may
            // have been supplied with config for dependent services as well, so we can't just attach all
            // of the supplied config items to the enrolling tenant - some of it could belong on delegated
            // tenants.
            logger?.LogDebug(
                "Attaching required configuration items to tenant '{serviceTenantName}' with Id '{serviceTenantId}'",
                serviceTenant.Name,
                serviceTenant.Id);

            IEnumerable <(ServiceManifestRequiredConfigurationEntry RequiredConfigurationEntry, EnrollmentConfigurationItem ProvidedConfigurationItem)> matchedConfigItems =
                manifest.RequiredConfigurationEntries.Select(
                    requiredConfigItem =>
                    (requiredConfigItem, configurationItems.Single(item => item.Key == requiredConfigItem.Key)));

            IEnumerable <KeyValuePair <string, object> > propertiesToAddToEnrollingTenant = PropertyBagValues.Empty;

            foreach ((ServiceManifestRequiredConfigurationEntry RequiredConfigurationEntry, EnrollmentConfigurationItem ProvidedConfigurationItem)current in matchedConfigItems)
            {
                logger?.LogDebug(
                    "Adding configuration entry '{requiredConfigurationEntryKey}' to tenant '{serviceTenantName}' with Id '{serviceTenantId}'",
                    current.RequiredConfigurationEntry.Key,
                    serviceTenant.Name,
                    serviceTenant.Id);

                propertiesToAddToEnrollingTenant = current.RequiredConfigurationEntry.AddToTenantProperties(
                    propertiesToAddToEnrollingTenant, current.ProvidedConfigurationItem);
            }

            // Add an enrollment entry to the tenant.
            logger?.LogDebug(
                "Adding service enrollment to tenant '{serviceTenantName}' with Id '{serviceTenantId}'",
                serviceTenant.Name,
                serviceTenant.Id);

            propertiesToAddToEnrollingTenant = propertiesToAddToEnrollingTenant.AddServiceEnrollment(
                enrollingTenant, serviceTenant.Id);

            // Update the tenant now, so that the tenant type is correctly set - otherwise
            // recursive enrollments will fail
            logger?.LogDebug(
                "Updating tenant '{enrollingTenantName}' with Id '{enrollingTenantId}'",
                enrollingTenant.Name,
                enrollingTenant.Id);

            enrollingTenant = await tenantStore.UpdateTenantAsync(
                enrollingTenant.Id,
                propertiesToSetOrAdd : propertiesToAddToEnrollingTenant)
                              .ConfigureAwait(false);

            propertiesToAddToEnrollingTenant = PropertyBagValues.Empty;

            // If this service has dependencies, we need to create a new delegated tenant for the service to use when
            // accessing those dependencies.
            if (manifest.DependsOnServiceTenants.Count > 0)
            {
                logger?.LogDebug(
                    "Service '{serviceTenantName}' has dependencies. Creating delegated tenant for enrollment.",
                    serviceTenant.Name);

                ITenant delegatedTenant = await tenantStore.CreateDelegatedTenant(enrollingTenant, serviceTenant).ConfigureAwait(false);

                // Now enroll the new delegated tenant for all of the dependent services.
                await Task.WhenAll(manifest.DependsOnServiceTenants.Select(
                                       dependsOnService => tenantStore.EnrollInServiceAsync(
                                           delegatedTenant,
                                           dependsOnService.Id,
                                           configurationItems))).ConfigureAwait(false);

                // Add the delegated tenant Id to the enrolling tenant
                logger?.LogDebug(
                    "Setting delegated tenant for client '{enrollingTenantName}' with Id '{enrollingTenantId}' in service '{serviceTenantName}' with Id '{serviceTenantId}' to new tenant '{delegatedTenantName}' with Id '{delegatedTenantId}'.",
                    enrollingTenant.Name,
                    enrollingTenant.Id,
                    serviceTenant.Name,
                    serviceTenant.Id,
                    delegatedTenant.Name,
                    delegatedTenant.Id);

                propertiesToAddToEnrollingTenant = propertiesToAddToEnrollingTenant.SetDelegatedTenantForService(
                    enrollingTenant, serviceTenant, delegatedTenant);

                logger?.LogDebug(
                    "Updating tenant '{enrollingTenantName}' with Id '{enrollingTenantId}'",
                    enrollingTenant.Name,
                    enrollingTenant.Id);

                await tenantStore.UpdateTenantAsync(
                    enrollingTenant.Id,
                    propertiesToSetOrAdd : propertiesToAddToEnrollingTenant)
                .ConfigureAwait(false);
            }

            logger?.LogInformation(
                "Successfully enrolled tenant '{enrollingTenantName}' with Id '{enrollingTenant.Id}' for service '{serviceTenantName}' with Id '{serviceTenantId}'",
                enrollingTenant.Name,
                enrollingTenant.Id,
                serviceTenant.Name,
                serviceTenant.Id);
        }
        /// <summary>
        /// Unenrolls the specified tenant from the service.
        /// </summary>
        /// <param name="tenantStore">The tenant store.</param>
        /// <param name="enrolledTenant">The tenant that is currently enrolled.</param>
        /// <param name="serviceTenant">The service they need to be unenrolled from.</param>
        /// <param name="logger">Optional logger.</param>
        /// <returns>A task which completes when the unenrollment has finished.</returns>
        public static async Task UnenrollFromServiceAsync(
            this ITenantStore tenantStore,
            ITenant enrolledTenant,
            ITenant serviceTenant,
            ILogger?logger = null)
        {
            if (!enrolledTenant.IsEnrolledForService(serviceTenant.Id))
            {
                throw new InvalidOperationException(
                          $"Cannot unenroll tenant '{enrolledTenant.Name}' with Id '{enrolledTenant.Id}' from service with Id '{serviceTenant.Id}' because it is not currently enrolled");
            }

            logger?.LogDebug(
                "Unenrolling tenant '{enrolledTenantName}' with Id '{enrolledTenantId}' from service '{serviceTenantName}' with Id '{serviceTenantId}'",
                enrolledTenant.Name,
                enrolledTenant.Id,
                serviceTenant.Name,
                serviceTenant.Id);

            var propertiesToRemove = new List <string>();

            ServiceManifest manifest = serviceTenant.GetServiceManifest();

            // If there are dependencies, we first need to unenroll from each of those and then remove the delegated tenant.
            if (manifest.DependsOnServiceTenants.Count > 0)
            {
                logger?.LogDebug(
                    "Service '{serviceTenantName}' has dependencies. Retrieving delegated tenant for unenrollment.",
                    serviceTenant.Name);

                string delegatedTenantId = enrolledTenant.GetDelegatedTenantIdForServiceId(serviceTenant.Id);

                logger?.LogDebug(
                    "Retrieved delegated tenant with Id '{delegatedTenantId}. Unenrolling from dependencies.",
                    delegatedTenantId);

                foreach (ServiceDependency current in manifest.DependsOnServiceTenants)
                {
                    await tenantStore.UnenrollFromServiceAsync(delegatedTenantId, current.Id).ConfigureAwait(false);
                }

                // Now delete the delegated tenant.
                logger?.LogDebug(
                    "Deleting delegated tenant with Id '{delegatedTenantId}'.",
                    delegatedTenantId);
                await tenantStore.DeleteTenantAsync(delegatedTenantId).ConfigureAwait(false);

                propertiesToRemove.AddRange(enrolledTenant.GetPropertiesToRemoveDelegatedTenantForService(serviceTenant));
            }

            if (manifest.RequiredConfigurationEntries.Count > 0)
            {
                // Now remove any config for the service that's being unenrolled from.
                logger?.LogDebug(
                    "Removing configuration for service '{serviceTenantName}' from '{enrolledTenantName}'",
                    serviceTenant.Name,
                    enrolledTenant.Name);

                foreach (ServiceManifestRequiredConfigurationEntry current in manifest.RequiredConfigurationEntries)
                {
                    logger?.LogDebug(
                        "Removing configuration item '{requiredConfigurationEntryKey}' for service '{serviceTenantName}' from '{enrolledTenantName}'",
                        current.Key,
                        serviceTenant.Name,
                        enrolledTenant.Name);
                    propertiesToRemove.AddRange(current.GetPropertiesToRemoveFromTenant(enrolledTenant));
                }
            }

            // Finally, remove the enrollment entry for the service.
            logger?.LogDebug(
                "Removing enrollment entry for service '{serviceTenantName}' from '{enrolledTenantName}'",
                serviceTenant.Name,
                enrolledTenant.Name);

            IEnumerable <KeyValuePair <string, object> > propertiesToChange =
                enrolledTenant.GetPropertyUpdatesToRemoveServiceEnrollment(serviceTenant.Id);

            logger?.LogDebug(
                "Updating tenant '{enrolledTenantName}'",
                enrolledTenant.Name);

            await tenantStore.UpdateTenantAsync(
                enrolledTenant.Id,
                propertiesToSetOrAdd : propertiesToChange,
                propertiesToRemove : propertiesToRemove).ConfigureAwait(false);

            logger?.LogInformation(
                "Successfully unenrolled tenant '{enrolledTenantName}' with Id '{enrolledTenantId}' from service '{serviceTenantName}' with Id '{serviceTenantId}'",
                enrolledTenant.Name,
                enrolledTenant.Id,
                serviceTenant.Name,
                serviceTenant.Id);
        }
Exemple #47
0
        /// <inheritdoc />
#pragma warning disable CA1502 // TODO: Decomplexify
#pragma warning disable CA1506
        public async Task RunAsync(bool runConfigure, string[] args, CancellationToken cancellationToken)
        {
            logger.LogInformation("Host watchdog starting...");
            logger.LogDebug("PID: {0}", Process.GetCurrentProcess().Id);
            string updateDirectory = null;

            try
            {
                var isWindows  = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                var dotnetPath = GetDotnetPath(isWindows);
                if (dotnetPath == default)
                {
                    logger.LogCritical("Unable to locate dotnet executable in PATH! Please ensure the .NET Core runtime is installed and is in your PATH!");
                    return;
                }

                logger.LogInformation("Detected dotnet executable at {0}", dotnetPath);

                var executingAssembly = Assembly.GetExecutingAssembly();
                var rootLocation      = Path.GetDirectoryName(executingAssembly.Location);

                var assemblyStoragePath = Path.Combine(rootLocation, "lib");                 // always always next to watchdog

                var defaultAssemblyPath = Path.GetFullPath(Path.Combine(assemblyStoragePath, "Default"));

                if (Debugger.IsAttached)
                {
                    // VS special tactics
                    // just copy the shit where it belongs
                    Directory.Delete(assemblyStoragePath, true);
                    Directory.CreateDirectory(defaultAssemblyPath);

                    var sourcePath = "../../../../Tgstation.Server.Host/bin/Debug/netcoreapp3.1";
                    foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
                    {
                        Directory.CreateDirectory(dirPath.Replace(sourcePath, defaultAssemblyPath));
                    }

                    foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))
                    {
                        File.Copy(newPath, newPath.Replace(sourcePath, defaultAssemblyPath), true);
                    }

                    const string AppSettingsYaml = "appsettings.yml";
                    var          rootYaml        = Path.Combine(rootLocation, AppSettingsYaml);
                    File.Delete(rootYaml);
                    File.Move(Path.Combine(defaultAssemblyPath, AppSettingsYaml), rootYaml);
                }
                else
                {
                    Directory.CreateDirectory(assemblyStoragePath);
                }

                var assemblyName = String.Join(".", nameof(Tgstation), nameof(Server), nameof(Host), "dll");
                var assemblyPath = Path.Combine(defaultAssemblyPath, assemblyName);

                if (assemblyPath.Contains("\""))
                {
                    logger.LogCritical("Running from paths with \"'s in the name is not supported!");
                    return;
                }

                if (!File.Exists(assemblyPath))
                {
                    logger.LogCritical("Unable to locate host assembly!");
                    return;
                }

                string watchdogVersion = executingAssembly.GetName().Version.ToString();

                while (!cancellationToken.IsCancellationRequested)
                {
                    using (logger.BeginScope("Host invocation"))
                    {
                        updateDirectory = Path.GetFullPath(Path.Combine(assemblyStoragePath, Guid.NewGuid().ToString()));
                        logger.LogInformation("Update path set to {0}", updateDirectory);
                        using (var process = new Process())
                        {
                            process.StartInfo.FileName         = dotnetPath;
                            process.StartInfo.WorkingDirectory = rootLocation;                              // for appsettings

                            var arguments = new List <string>
                            {
                                $"\"{assemblyPath}\"",
                                $"\"{updateDirectory}\"",
                                $"\"{watchdogVersion}\"",
                            };

                            if (args.Any(x => x.Equals("--attach-host-debugger", StringComparison.OrdinalIgnoreCase)))
                            {
                                arguments.Add("--attach-debugger");
                            }

                            if (runConfigure)
                            {
                                logger.LogInformation("Running configuration check and wizard if necessary...");
                                arguments.Add("General:SetupWizardMode=Only");
                            }

                            arguments.AddRange(args);

                            process.StartInfo.Arguments = String.Join(" ", arguments);

                            process.StartInfo.UseShellExecute = false;                             // runs in the same console

                            var tcs = new TaskCompletionSource <object>();
                            process.Exited += (a, b) =>
                            {
                                tcs.TrySetResult(null);
                            };
                            process.EnableRaisingEvents = true;

                            logger.LogInformation("Launching host...");

                            var killedHostProcess = false;
                            try
                            {
                                process.Start();

                                using (var processCts = new CancellationTokenSource())
                                    using (processCts.Token.Register(() => tcs.TrySetResult(null)))
                                        using (cancellationToken.Register(() =>
                                        {
                                            if (!Directory.Exists(updateDirectory))
                                            {
                                                logger.LogInformation("Cancellation requested! Writing shutdown lock file...");
                                                File.WriteAllBytes(updateDirectory, Array.Empty <byte>());
                                            }
                                            else
                                            {
                                                logger.LogWarning("Cancellation requested while update directory exists!");
                                            }

                                            logger.LogInformation("Will force close host process if it doesn't exit in 10 seconds...");

                                            try
                                            {
                                                processCts.CancelAfter(TimeSpan.FromSeconds(10));
                                            }
                                            catch (ObjectDisposedException)
                                            {
                                                // race conditions
                                            }
                                        }))
                                            await tcs.Task.ConfigureAwait(false);
                            }
                            catch (InvalidOperationException)
                            {
                            }
                            finally
                            {
                                try
                                {
                                    if (!process.HasExited)
                                    {
                                        killedHostProcess = true;
                                        process.Kill();
                                        process.WaitForExit();
                                    }
                                }
                                catch (InvalidOperationException)
                                {
                                }

                                logger.LogInformation("Host exited!");
                            }

                            if (runConfigure)
                            {
                                logger.LogInformation("Exiting due to configuration check...");
                                return;
                            }

                            switch (process.ExitCode)
                            {
                            case 0:
                                return;

                            case 1:
                                if (!cancellationToken.IsCancellationRequested)
                                {
                                    logger.LogInformation("Watchdog will restart host...");                                             // just a restart
                                }
                                else
                                {
                                    logger.LogWarning("Host requested restart but watchdog shutdown is in progress!");
                                }
                                break;

                            case 2:
                                // update path is now an exception document
                                logger.LogCritical("Host crashed, propagating exception dump...");
                                var data = File.ReadAllText(updateDirectory);
                                try
                                {
                                    File.Delete(updateDirectory);
                                }
                                catch (Exception e)
                                {
                                    logger.LogWarning(e, "Unable to delete exception dump file at {0}!", updateDirectory);
                                }

#pragma warning disable CA2201 // Do not raise reserved exception types
                                throw new Exception(String.Format(CultureInfo.InvariantCulture, "Host propagated exception: {0}", data));

#pragma warning restore CA2201 // Do not raise reserved exception types
                            default:
                                if (killedHostProcess)
                                {
                                    logger.LogWarning("Watchdog forced to kill host process!");
                                    cancellationToken.ThrowIfCancellationRequested();
                                }

#pragma warning disable CA2201 // Do not raise reserved exception types
                                throw new Exception(String.Format(CultureInfo.InvariantCulture, "Host crashed with exit code {0}!", process.ExitCode));
#pragma warning restore CA2201 // Do not raise reserved exception types
                            }
                        }

                        // HEY YOU
                        // BE WARNED THAT IF YOU DEBUGGED THE HOST PROCESS THAT JUST LAUNCHED THE DEBUGGER WILL HOLD A LOCK ON THE DIRECTORY
                        // THIS MEANS THE FIRST DIRECTORY.MOVE WILL THROW
                        if (Directory.Exists(updateDirectory))
                        {
                            logger.LogInformation("Applying server update...");
                            if (isWindows)
                            {
                                // windows dick sucking resource unlocking
                                GC.Collect(Int32.MaxValue, GCCollectionMode.Default, true);
                                await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken).ConfigureAwait(false);
                            }

                            var tempPath = Path.Combine(assemblyStoragePath, Guid.NewGuid().ToString());
                            try
                            {
                                Directory.Move(defaultAssemblyPath, tempPath);
                                try
                                {
                                    Directory.Move(updateDirectory, defaultAssemblyPath);
                                    logger.LogInformation("Server update complete, deleting old server...");
                                    try
                                    {
                                        Directory.Delete(tempPath, true);
                                    }
                                    catch (Exception e)
                                    {
                                        logger.LogWarning(e, "Error deleting old server at {0}!", tempPath);
                                    }
                                }
                                catch (Exception e)
                                {
                                    logger.LogError(e, "Error moving updated server directory, attempting revert!");
                                    Directory.Delete(defaultAssemblyPath, true);
                                    Directory.Move(tempPath, defaultAssemblyPath);
                                    logger.LogInformation("Revert successful!");
                                }
                            }
                            catch (Exception e)
                            {
                                logger.LogWarning(e, "Failed to move out active host assembly!");
                            }
                        }
                    }
                }
            }
            catch (OperationCanceledException ex)
            {
                logger.LogDebug(ex, "Exiting due to cancellation...");
                if (!Directory.Exists(updateDirectory))
                {
                    File.Delete(updateDirectory);
                }
                else
                {
                    Directory.Delete(updateDirectory, true);
                }
            }
            catch (Exception ex)
            {
                logger.LogCritical(ex, "Host watchdog error!");
            }
            finally
            {
                logger.LogInformation("Host watchdog exiting...");
            }
        }
        private bool DoExecute(ProcessedArgs args, ILogger logger)
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            logger.Verbosity = VerbosityCalculator.ComputeVerbosity(args.AggregateProperties, logger);

            InstallLoaderTargets(args, logger);

            TeamBuildSettings teamBuildSettings = TeamBuildSettings.GetSettingsFromEnvironment(logger);

            // We're checking the args and environment variables so we can report all
            // config errors to the user at once
            if (teamBuildSettings == null)
            {
                logger.LogError(Resources.ERROR_CannotPerformProcessing);
                return false;
            }

            // Create the directories
            logger.LogDebug(Resources.MSG_CreatingFolders);
            if (!Utilities.TryEnsureEmptyDirectories(logger,
                teamBuildSettings.SonarConfigDirectory,
                teamBuildSettings.SonarOutputDirectory))
            {
                return false;
            }

            IDictionary<string, string> serverSettings;
            if (!FetchArgumentsAndRulesets(args, teamBuildSettings.SonarConfigDirectory, logger, out serverSettings))
            {
                return false;
            }

            AnalysisConfigGenerator.GenerateFile(args, teamBuildSettings, serverSettings, logger);

            return true;
        }
 private void InstallLoaderTargets(ProcessedArgs args, ILogger logger)
 {
     if (args.InstallLoaderTargets)
     {
         this.targetInstaller.InstallLoaderTargets(logger);
     }
     else
     {
         logger.LogDebug(Resources.MSG_NotCopyingTargets);
     }
 }
        public IDictionary<string, string> GetProperties(string projectKey, ILogger logger)
        {
            if (string.IsNullOrWhiteSpace(projectKey))
            {
                throw new ArgumentNullException("projectKey");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string ws = GetUrl("/api/properties?resource={0}", projectKey);
            logger.LogDebug(Resources.MSG_FetchingProjectProperties, projectKey, ws);
            var contents = this.downloader.Download(ws);

            var properties = JArray.Parse(contents);
            var result = properties.ToDictionary(p => p["key"].ToString(), p => p["value"].ToString());

            // http://jira.sonarsource.com/browse/SONAR-5891
            if (!result.ContainsKey("sonar.cs.msbuild.testProjectPattern"))
            {
                result["sonar.cs.msbuild.testProjectPattern"] = SonarProperties.DefaultTestProjectPattern;
            }

            return result;
        }
Exemple #51
0
        public async Task <ICommandContext> ExecuteAsync(ICommandActor actor, string[] args, string prefix)
        {
            if (args == null || args.Length == 0)
            {
                throw new Exception("Can not execute command with null or empty args");
            }

            m_Logger.LogInformation($"Actor {actor.Type}/{actor.DisplayName} ({actor.Id}) has executed command \"{string.Join(" ", args)}\".");

            var currentCommandAccessor = m_LifetimeScope.Resolve <ICurrentCommandContextAccessor>();
            var commandContextBuilder  = m_LifetimeScope.Resolve <ICommandContextBuilder>();
            var stringLocalizer        = m_LifetimeScope.Resolve <IOpenModStringLocalizer>();

            var commandsRegistrations = await m_CommandStore.GetCommandsAsync();

            var commandContext        = commandContextBuilder.CreateContext(actor, args, prefix, commandsRegistrations);
            var commandExecutingEvent = new CommandExecutingEvent(actor, commandContext);
            await m_EventBus.EmitAsync(m_Runtime, this, commandExecutingEvent);

            if (commandExecutingEvent.IsCancelled)
            {
                return(commandExecutingEvent.CommandContext);
            }

            try
            {
                if (commandContext.Exception != null)
                {
                    throw commandContext.Exception;
                }

                currentCommandAccessor.Context = commandContext;

                var permission        = m_CommandPermissionBuilder.GetPermission(commandContext.CommandRegistration);
                var permissionChecker = m_Runtime.Host.Services.GetRequiredService <IPermissionChecker>();

                if (!string.IsNullOrWhiteSpace(permission) && await permissionChecker.CheckPermissionAsync(actor, permission) != PermissionGrantResult.Grant)
                {
                    throw new NotEnoughPermissionException(stringLocalizer, permission);
                }

                Stopwatch sw = new Stopwatch();
                sw.Start();
                var command = commandContext.CommandRegistration.Instantiate(commandContext.ServiceProvider);
                await command.ExecuteAsync();

                m_Logger.LogDebug($"Command \"{string.Join(" ", args)}\" executed in {sw.ElapsedMilliseconds}ms");
                sw.Reset();

                currentCommandAccessor.Context = null;
            }
            catch (UserFriendlyException ex)
            {
                commandContext.Exception = ex;
            }
            catch (Exception ex)
            {
                commandContext.Exception = ex;
            }
            finally
            {
                var commandExecutedEvent = new CommandExecutedEvent(actor, commandContext);
                await m_EventBus.EmitAsync(m_Runtime, this, commandExecutedEvent);

                if (commandContext.Exception != null && !commandExecutedEvent.ExceptionHandled)
                {
                    if (commandContext.Exception is UserFriendlyException)
                    {
                        await actor.PrintMessageAsync(commandContext.Exception.Message, Color.DarkRed);
                    }
                    else
                    {
                        await actor.PrintMessageAsync("An internal error occured during the command execution.", Color.DarkRed);

                        m_Logger.LogError(commandContext.Exception, $"Exception occured on command \"{string.Join(" ", args)}\" by actor {actor.Type}/{actor.DisplayName} ({actor.Id})");
                    }
                }

                await commandContext.DisposeAsync();
            }

            return(commandContext);
        }
Exemple #52
0
        private void Inspect(QuizContext quizContext)
        {
            var ids = string.Join(", ", quizContext.Questions.Select(x => x.Id));

            _logger.LogDebug($"***DB*** has now: {ids} question");
        }
 public CarsContext(ILoggerFactory loggerFactory)
 {
     _logger = loggerFactory.CreateLogger<CarsContext>();
     _logger.LogDebug("Constructing CarsContext");
 }
Exemple #54
0
        public ClientManager(IMessageHandler messageHandler, IReactionHandler reactionHandler, ILogger <ClientManager> logger, IDiscordClient client, TwitchClient twitchClient)
        {
            _logger       = logger;
            _client       = client;
            _twitchClient = twitchClient;
            switch (_client)
            {
            case DiscordSocketClient discordSocketClient:
                // Create and attach restart service
                _reliabilityService = new ReliabilityService(discordSocketClient, true, Config.ServiceProvider.GetService <ILogger <ReliabilityService> >());
                _reliabilityService.Attach();

                // Attach event handlers
                discordSocketClient.MessageReceived += messageHandler.HandleAsync;
                discordSocketClient.ReactionAdded   += reactionHandler.HandleAsync;
                discordSocketClient.UserJoined      += OnUserJoinAsync;
                discordSocketClient.UserLeft        += OnUserLeaveAsync;
                discordSocketClient.UserBanned      += OnUserBanAsync;

                discordSocketClient.Ready += () =>
                {
                    _ready = true;
                    return(Task.CompletedTask);
                };

                // Add logging
                discordSocketClient.Log += logMessage =>
                {
                    switch (logMessage.Severity)
                    {
                    case LogSeverity.Critical:
                        _logger.LogCritical(logMessage.Exception, logMessage.Message);
                        break;

                    case LogSeverity.Error:
                        _logger.LogError(logMessage.Exception, logMessage.Message);
                        break;

                    case LogSeverity.Warning:
                        _logger.LogWarning(logMessage.Exception, logMessage.Message);
                        break;

                    case LogSeverity.Info:
                        _logger.LogInformation(logMessage.Exception, logMessage.Message);
                        break;

                    case LogSeverity.Verbose:
                        _logger.LogDebug(logMessage.Exception, logMessage.Message);
                        break;

                    case LogSeverity.Debug:
                        _logger.LogTrace(logMessage.Exception, logMessage.Message);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    return(Task.CompletedTask);
                };
                break;
            }
        }
 private static void GenerateFxCopRuleset(ISonarQubeServer server, string projectKey, string requiredPluginKey, string language, string repository, string path, ILogger logger)
 {
     logger.LogDebug(Resources.MSG_GeneratingRuleset, path);
     RulesetGenerator.Generate(server, requiredPluginKey, language, repository, projectKey, path);
 }
Exemple #56
0
        private ICollection <IMigration> GetMigrations(
            IEnumerable <string> fileNames,
            Func <string, string> sqlScriptReadFunc,
            IDbProvider dbProvider,
            string?prefix,
            IReadOnlyDictionary <string, string> variables,
            ILogger?migrationLogger)
        {
            if (fileNames == null)
            {
                throw new ArgumentNullException(nameof(fileNames));
            }
            if (sqlScriptReadFunc == null)
            {
                throw new ArgumentNullException(nameof(sqlScriptReadFunc));
            }
            if (dbProvider == null)
            {
                throw new ArgumentNullException(nameof(dbProvider));
            }

            var scripts = new Dictionary <DbVersion, ScriptInfo>();

            var regex = String.IsNullOrWhiteSpace(prefix)
                ? new Regex($"{MigrationConstants.MigrationFileNamePattern}", RegexOptions.IgnoreCase)
                : new Regex($"{prefix}{MigrationConstants.MigrationFileNamePattern}", RegexOptions.IgnoreCase);

            foreach (var fileName in fileNames)
            {
                var match = regex.Match(fileName);
                if (!match.Success)
                {
                    // it's normal that some files doesn't match a regex, but we log, it's safer
                    migrationLogger?.LogDebug($"\"{fileName}\" has incorrect name for script migration.");
                    continue;
                }

                if (!DbVersion.TryParse(match.Groups[1].Value, out var version))
                {
                    migrationLogger?.LogWarning($"\"{fileName}\" has incorrect version migration.");
                    continue;
                }

                if (!scripts.ContainsKey(version))
                {
                    scripts[version] = new ScriptInfo(version);
                }

                var scriptInfo = scripts[version];

                var script = sqlScriptReadFunc.Invoke(fileName);

                // extract options for current migration
                scriptInfo.Options = ExtractMigrationOptions(script);

                // split into batches
                var batches        = new List <ScriptMigrationBatch>();
                var batchNameRegex = new Regex(@"--\s*BATCH:\s*(.*)\s*\n(.*)", RegexOptions.IgnoreCase);
                var batchIndex     = 0;

                // Use positive lookahead to split script into batches.
                foreach (var batch in Regex.Split(script, @"(?=--\s*BATCH:)"))
                {
                    if (String.IsNullOrWhiteSpace(batch))
                    {
                        continue;
                    }

                    var batchNameMatch = batchNameRegex.Match(batch);
                    batches.Add(new ScriptMigrationBatch(
                                    batchIndex++,
                                    batchNameMatch.Success ? batchNameMatch.Groups[1].Value : null,
                                    batch));
                }

                if (match.Groups[6].Success)
                {
                    if (scriptInfo.DownScript.Count > 0)
                    {
                        throw new InvalidOperationException(
                                  $"There is more than one downgrade script with version {version}");
                    }

                    scriptInfo.DownScript.AddRange(batches);
                }
                else
                {
                    if (scriptInfo.UpScript.Count > 0)
                    {
                        throw new InvalidOperationException(
                                  $"There is more than one upgrade script with version {version}");
                    }

                    scriptInfo.UpScript.AddRange(batches);
                }

                var comment = match.Groups[9];
                scriptInfo.Comment = comment.Success
                    ? comment.Value
                    : null;
            }

            return(scripts
                   .Select(scriptInfo =>
                           CreateScriptMigration(
                               scriptInfo.Key,
                               scriptInfo.Value,
                               dbProvider,
                               variables,
                               migrationLogger))
                   .ToArray());
        }
 private static void AddOrSetProperty(string key, string value, AnalysisProperties properties, ILogger logger)
 {
     Property property;
     Property.TryGetProperty(key, properties, out property);
     if (property == null)
     {
         logger.LogDebug(Resources.MSG_SettingAnalysisProperty, key, value);
         property = new Property() { Id = key, Value = value };
         properties.Add(property);
     }
     else
     {
         if (string.Equals(property.Value, value, StringComparison.InvariantCulture))
         {
             logger.LogDebug(Resources.MSG_MandatorySettingIsCorrectlySpecified, key, value);
         }
         else
         {
             logger.LogWarning(Resources.WARN_OverridingAnalysisProperty, key, value);
             property.Value = value;
         }
     }
 }
 public static void OnHalfOpenDefault(ILogger <AgonesCircuitDelegate> logger)
 {
     logger.LogDebug("OnHalfOpen: Circuit in test mode, one request will be allowed.");
 }
Exemple #59
0
        private static bool MonitorHostProcess(CommandOption host, ILogger logger)
        {
            if (!host.HasValue())
            {
                logger.LogError($"Option \"{host.LongName}\" is missing.");
                return false;
            }

            int hostPID;
            if (int.TryParse(host.Value(), out hostPID))
            {
                var hostProcess = Process.GetProcessById(hostPID);
                hostProcess.EnableRaisingEvents = true;
                hostProcess.Exited += (s, e) =>
                {
                    Process.GetCurrentProcess().Kill();
                };

                logger.LogDebug($"Server will exit when process {hostPID} exits.");
                return true;
            }
            else
            {
                logger.LogError($"Option \"{host.LongName}\" is not a valid Int32 value.");
                return false;
            }
        }
        private async Task <Response> DoSendAsync(Command command, CancellationToken cancellationToken)
        {
            try
            {
                var stream = _stream ?? throw new ObjectDisposedException(nameof(TcpViscaTransport));
                var buffer = _buffer ?? throw new ObjectDisposedException(nameof(TcpViscaTransport));

                var messageSize  = command.MessageSize;
                var bufferLength = buffer.Length;
                if (messageSize > bufferLength)
                {
                    var currentBuffer = Interlocked.CompareExchange(ref _buffer, null !, buffer);

                    // Already disposed
                    if (currentBuffer is null)
                    {
                        throw new ObjectDisposedException(nameof(TcpViscaTransport));
                    }

                    // Return buffer
                    ArrayPool <byte> .Shared.Return(buffer);

                    // Get a bigger buffer!
                    buffer = ArrayPool <byte> .Shared.Rent(messageSize);

                    Interlocked.Exchange(ref _buffer, buffer);

                    _logger.LogWarning(
                        $"The '{command.Name} command requested a message size of '{messageSize}' which exceeded the current buffer's size '{bufferLength}', so a new buffer of size '{buffer.Length}' was created.  This is unexpected and exceeds the current VISCA specification so may cause problems on some devices!");
                }

                // Write the message into our current buffer.
                command.WriteMessage(buffer.AsSpan(0, messageSize), DeviceId);
                _logger?.LogDebug(
                    $"Sending '{command.Name}' data to '{EndPoint}': {buffer.Take(messageSize).ToHex()}");
                await stream.WriteAsync(buffer, 0, messageSize, cancellationToken)
                .ConfigureAwait(false);

                int      read;
                Response response;
                var      socket = -1;
                if (command.Type == CommandType.Command)
                {
                    // We expect an ACK
                    read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);

                    if (read < 1)
                    {
                        _logger?.LogError($"No data returned from '{EndPoint}' whilst executing '{command.Name}'.");
                        return(command.UnknownResponse);
                    }

                    response = command.GetResponse(buffer.AsSpan(0, read), _logger);
                    _logger?.LogDebug(
                        $"Received '{response.Type}' response to '{command.Name}' from '{EndPoint}': {buffer.Take(read).ToHex()}");
                    if (response.Type != ResponseType.ACK)
                    {
                        // The IFClear returns a completion without an ACK (as per spec.)
                        if (command != ViscaCommands.IFClear && response.Type != ResponseType.Completion)
                        {
                            _logger?.LogWarning(
                                $"Received a '{response.Type}' response from '{EndPoint}' whilst executing '{command.Name}' instead of an '{nameof(ResponseType.ACK)}' response.");
                        }

                        return(response);
                    }

                    if (response.DeviceId != DeviceId)
                    {
                    }

                    socket = response.Socket;
                    // Continue to wait for completion response
                }

                read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);

                if (read < 1)
                {
                    _logger?.LogError($"No data returned from '{EndPoint}' whilst executing '{command.Name}'.");
                    return(command.UnknownResponse);
                }

                response = command.GetResponse(buffer.AsSpan(0, read), _logger);
                _logger?.LogDebug(
                    $"Received '{response.Type}' response to '{command.Name}' from '{EndPoint}': {buffer.Take(read).ToHex()}");

                if (response.DeviceId != DeviceId)
                {
                    _logger?.LogWarning(
                        $"The device Id '{response.DeviceId}' in the '{response.Type}' response from '{EndPoint}' whilst executing '{command.Name}' did not match the expected device Id '{DeviceId}'.");
                }

                if (socket > -1 && response.Socket != socket)
                {
                    _logger?.LogWarning(
                        $"The socket '{response.Socket}' in the '{response.Type}' response from '{EndPoint}' whilst executing '{command.Name}' did not match the socket '{socket}' returned from the '{nameof(ResponseType.ACK)}' response.");
                }

                return(response);
            }
            catch (Exception exception)
            {
                _logger?.LogError(exception, $"Failed to send '{command.Name}' to '{EndPoint}'.");
                return(command.UnknownResponse);
            }
        }