Exemple #1
0
        /// <summary>
        /// Runs specified action in a background.
        /// </summary>
        /// <param name="action">Action to run.</param>
        /// <param name="exceptionHandler">Exception handler</param>
        /// <param name="isLongRunning">Is action long running.</param>
        public static void Run(Action action, Action <Exception> exceptionHandler, bool isLongRunning = false)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }
            if (exceptionHandler == null)
            {
                throw new ArgumentNullException(nameof(exceptionHandler));
            }

            var task = isLongRunning ? new Task(action, TaskCreationOptions.LongRunning) : new Task(action);

            task.ContinueWith(
                t =>
            {
                // faulted - unhandled exception, cancelled - unhandled OperationCancelledException
                if (t.IsFaulted || t.IsCanceled)
                {
                    try
                    {
                        exceptionHandler.Invoke(t.Exception);
                    }
                    catch (Exception e)
                    {
                        _logger?.LogError(e, $"Failed to correctly handle an Action error in FireAndForget. Reason: {e.Message}");
                    }
                }
            },
                TaskContinuationOptions.ExecuteSynchronously);
            task.ConfigureAwait(false);
            task.Start();
        }
Exemple #2
0
        public static void SafeCloseClientSocket(this Socket client, ILogger logger)
        {
            if(client == null)
                return;

            if (!client.Connected)
                return;
            
            try
            {
                client.Shutdown(SocketShutdown.Both);
            }
            catch(ObjectDisposedException)
            {
            }
            catch(Exception e)
            {
                if(logger != null)
                    logger.LogError(e);
            }
            
            try
            {
                client.Close();
            }
            catch(ObjectDisposedException)
            {
            }
            catch(Exception e)
            {
                if(logger != null)
                    logger.LogError(e);
            }
        }
 public RemoteConfigManager(IResourceLoader loader, IStorage storage, ILogger logger, RuntimePlatform platform)
 {
     this.storage = storage;
     logger.prefix = "Unibill.RemoteConfigManager";
     this.XML = loader.openTextFile ("unibillInventory.json").ReadToEnd ();
     Config = new UnibillConfiguration(XML, platform, logger);
     if (Config.UseHostedConfig) {
         string val = storage.GetString (CACHED_CONFIG_PATH, string.Empty);
         if (string.IsNullOrEmpty (val)) {
             logger.Log ("No cached config available. Using bundled");
         } else {
             logger.Log ("Cached config found, attempting to parse");
             try {
                 Config = new UnibillConfiguration(val, platform, logger);
                 if (Config.inventory.Count == 0) {
                     logger.LogError ("No purchasable items in cached config, ignoring.");
                     Config = new UnibillConfiguration (XML, platform, logger);
                 } else {
                     logger.Log (string.Format ("Using cached config with {0} purchasable items", Config.inventory.Count));
                     XML = val;
                 }
             } catch (Exception e) {
                 logger.LogError ("Error parsing inventory: {0}", e.Message);
                 Config = new UnibillConfiguration(XML, platform, logger);
             }
         }
         refreshCachedConfig (Config.HostedConfigUrl, logger);
     } else {
         logger.Log ("Not using cached inventory, using bundled.");
         Config = new UnibillConfiguration(XML, platform, logger);
     }
 }
#pragma warning disable SA1011 // Closing square brackets should be spaced correctly
        public async Task BuildImageAsync(string dockerfile, string imageName, string tag = "latest", string context = ".", IDictionary <string, string>?buildArgs = null, string[]?ignoredFiles = default, CancellationToken cancellationToken = default)
#pragma warning restore SA1011 // Closing square brackets should be spaced correctly
        {
            var tarFileName = Guid.NewGuid().ToString();

            try
            {
                // In order to pass the context we have to create tar file and use it as an argument.
                await _archiver.CreateTarArchiveAsync(tarFileName, context, ignoredFiles, cancellationToken);

                // Now call docker api.
                await CreateNewImageAsync(dockerfile, imageName, tag, tarFileName, buildArgs, cancellationToken);
            }
            catch (Exception exc)
            {
                _logger?.LogError(exc, $"Unable to create the image from dockerfile.");
                throw;
            }
            finally
            {
                // And don't forget to remove created tar.
                try
                {
                    File.Delete(tarFileName);
                }
                catch (Exception exc)
                {
                    _logger?.LogError(exc, $"Unable to delete tar file {tarFileName} with context. Please, cleanup manually.");
                }
            }
        }
        /// <inheritdoc/>
        protected override async Task OnOpeningAsync(CancellationToken token = default)
        {
            if (RemoteEndpoint.Server == null)
            {
                // If specific endpoint is not provided, use discovery to select endpoint with highest
                // security level.
                var endpointUrl       = RemoteEndpoint.EndpointUrl;
                var securityPolicyUri = RemoteEndpoint.SecurityPolicyUri;
                try
                {
                    _logger?.LogInformation($"Discovering endpoints of '{endpointUrl}'.");
                    var getEndpointsRequest = new GetEndpointsRequest
                    {
                        EndpointUrl = endpointUrl,
                        ProfileUris = new[] { TransportProfileUris.UaTcpTransport }
                    };
                    var getEndpointsResponse = await UaTcpDiscoveryService.GetEndpointsAsync(getEndpointsRequest, _loggerFactory).ConfigureAwait(false);

                    if (getEndpointsResponse.Endpoints == null || getEndpointsResponse.Endpoints.Length == 0)
                    {
                        throw new InvalidOperationException($"'{endpointUrl}' returned no endpoints.");
                    }

                    var selectedEndpoint = getEndpointsResponse.Endpoints
                                           .OfType <EndpointDescription>()
                                           .Where(e => string.IsNullOrEmpty(securityPolicyUri) || e.SecurityPolicyUri == securityPolicyUri)
                                           .OrderBy(e => e.SecurityLevel)
                                           .LastOrDefault();

                    if (selectedEndpoint is null)
                    {
                        throw new InvalidOperationException($"'{endpointUrl}' returned no endpoint for the requested security policy '{securityPolicyUri}'.");
                    }

                    RemoteEndpoint.Server              = selectedEndpoint.Server;
                    RemoteEndpoint.ServerCertificate   = selectedEndpoint.ServerCertificate;
                    RemoteEndpoint.SecurityMode        = selectedEndpoint.SecurityMode;
                    RemoteEndpoint.SecurityPolicyUri   = selectedEndpoint.SecurityPolicyUri;
                    RemoteEndpoint.UserIdentityTokens  = selectedEndpoint.UserIdentityTokens;
                    RemoteEndpoint.TransportProfileUri = selectedEndpoint.TransportProfileUri;
                    RemoteEndpoint.SecurityLevel       = selectedEndpoint.SecurityLevel;

                    _logger?.LogTrace($"Success discovering endpoints of '{endpointUrl}'.");
                }
                catch (Exception ex)
                {
                    _logger?.LogError($"Error discovering endpoints of '{endpointUrl}'. {ex.Message}");
                    throw;
                }
            }

            // Ask for user identity. May show dialog.
            if (UserIdentityProvider != null)
            {
                UserIdentity = await UserIdentityProvider(RemoteEndpoint);
            }

            await base.OnOpeningAsync(token);
        }
        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;
        }
        /// <summary>
        /// Subscriber
        /// </summary>
        protected void Subscribe <TRequest, TResponse>(CancellationToken ctx)
        {
            _eventingBasicConsumer.Received += async(sender, e) =>
            {
                try
                {
                    var    @event = (TRequest)_serializer.Deserialize(typeof(TRequest), e.Body);
                    object?response;

                    try
                    {
                        if (_config.ShouldCreateScope)
                        {
                            using (var scope = _services.CreateScope())
                            {
                                response = await CallService <TRequest, TResponse>(@event, scope.ServiceProvider, ctx);
                            }
                        }
                        else
                        {
                            response = await CallService <TRequest, TResponse>(@event, _services, ctx);
                        }
                    }
                    catch (Exception exception)
                    {
                        response = exception;
                    }
                    PublishResponse(e, response);
                }
                catch (Exception ex)
                {
                    _logger?.LogError(ex, ex.Message);
                }
                finally
                {
                    TryAck(e);
                }
            };

            _model.ConfirmSelect();
            _model.ExchangeDeclare(Descriptor.ExchangeName, ExchangeType.Fanout, true, true,
                                   new Dictionary <string, object>
            {
                ["x-delayed-type"] = ExchangeType.Direct
            });


            _model.QueueBind(Descriptor.QueueName, Descriptor.ExchangeName, string.Empty, null);
            _model.BasicConsume(Descriptor.QueueName, false, _eventingBasicConsumer);
        }
Exemple #8
0
        protected virtual Response DoGetResponse(ReadOnlySpan <byte> response, ILogger?logger)
        {
            var length = response.Length;

            if (length < 1)
            {
                logger?.LogError("The response was empty.");
                return(Response.Unknown);
            }

            // Calculate Device ID
            var deviceId = response[0];

            if ((deviceId & 0xf) > 0)
            {
                logger?.LogError($"The response's device byte '{deviceId:X2}' was invalid.");
                return(Response.Unknown);
            }

            deviceId = (byte)(deviceId >> 4);
            if (deviceId < 8)
            {
                logger?.LogError(
                    $"The response's device id '{deviceId - 8}' was invalid, as it must be greater than 0 (usually 1).");
                return(Response.Unknown);
            }

            deviceId -= 8;

            if (length < 2)
            {
                logger?.LogError(
                    $"The response's length '{length}' was too short.");
                return(Response.Get(ResponseType.Unknown, deviceId, 0));
            }

            // Calculate Socket
            var b      = response[1];
            var socket = (byte)(b & 0xf);

            if (length < 3)
            {
                logger?.LogError(
                    $"The response's length '{length}' was too short.");
                return(Response.Get(ResponseType.Unknown, deviceId, socket));
            }

            // Validate terminator
            var end = response[^ 1];
Exemple #9
0
        public bool TryConnect()
        {
            var opts = ConnectionFactory.GetDefaultOptions();

            opts.Servers      = _options.Servers;
            opts.MaxReconnect = _options.RetryCount;
            if (!string.IsNullOrEmpty(_options.Username))
            {
                opts.User = _options.Username;
            }
            if (!string.IsNullOrEmpty(_options.Password))
            {
                opts.Password = _options.Password;
            }
            if (!string.IsNullOrEmpty(_options.Token))
            {
                opts.Token = _options.Token;
            }
            try {
                _connection = _factory.CreateConnection(opts);
                return(IsConnected);
            } catch (Exception e) {
                _logger?.LogError(e, "Failed to connect to NAT server");
                return(false);
            }
        }
Exemple #10
0
        /// <summary>
        /// It tries to resolve refresh token id from claim <see cref="BearerSignInManagerDefaults.SignInServiceRefreshTokenIdClaimType"/>
        /// and then look in the database. If a refresh token has been found, it will be returned.
        /// </summary>
        public static async Task <ServiceResult <BearerTokenType> > FindRefreshTokenAsync <BearerTokenType>(IBearerTokenStore <BearerTokenType> refreshTokenStore, ClaimsPrincipal principal, ILogger?logger = null)
            where BearerTokenType : class, IBearerTokenEntity
        {
            principal = principal ?? throw BearerSignInManagerThrowHelper.GetPrincipalNullException(nameof(principal));
            var refreshTokenIdResult = FindRefreshTokenId(principal);

            if (!refreshTokenIdResult.Succeeded)
            {
                return(ServiceResult <BearerTokenType> .Failure(refreshTokenIdResult));
            }

            try {
                // Then we need the entity that belongs to refresh token id.
                var refreshTokenEntity = await refreshTokenStore.FindAsync(refreshTokenIdResult.Content);

                return(ReferenceEquals(refreshTokenEntity, null) ?
                       ServiceResult <BearerTokenType>
                       .Failure("The refresh token has been redeemed.")
                       .WithHttpStatusCode(HttpStatusCode.BadRequest) :
                       ServiceResult <BearerTokenType>
                       .Success(refreshTokenEntity)
                       .WithHttpStatusCode(HttpStatusCode.OK));
            } catch (Exception error) {
                const string errorMessage = "Search for refresh token failed.";
                logger?.LogError(error, errorMessage);

                return(errorMessage.ToJsonError()
                       .ToServiceResult <BearerTokenType>()
                       .WithHttpStatusCode(HttpStatusCode.InternalServerError));
            }
        }
Exemple #11
0
    private async Task <HttpResponseMessage> SendRequestAsync(HttpRequestMessage request, CancellationToken?cancellationToken = default)
    {
        try
        {
            return(await _httpMessageInvoker.SendAsync(request, cancellationToken ?? CancellationToken.None));
        }
        catch (Exception exception)
        {
            var baseAddress = (_httpMessageInvoker as System.Net.Http.HttpClient)?.BaseAddress.OriginalString;

            string?body = request.Content is null
                                ? null
                                : await request.Content.ReadAsStringAsync();

            exception.Data.Add(nameof(baseAddress), baseAddress);
            exception.Data.Add(nameof(body), body);
            exception.Data.Add(nameof(request.Method), request.Method);
            exception.Data.Add(nameof(request.RequestUri), request.RequestUri.OriginalString);

            _tracer?.ActiveSpan?.Log(exception);

            _logger?.LogError(exception,
                              "{0}={1}, {2}={3}, {4}={5}",
                              nameof(request.Method), request.Method,
                              nameof(request.RequestUri), request.RequestUri.OriginalString,
                              nameof(body), body);

            throw;
        }
    }
Exemple #12
0
        protected override Response DoGetResponse(ReadOnlySpan <byte> response, ILogger?logger)
        {
            var baseResponse = base.DoGetResponse(response, logger);
            var deviceId     = baseResponse.DeviceId;
            var type         = baseResponse.Type;

            if (type != ResponseType.Inquiry)
            {
                // All other responses are effectively errors and should already have a log.
                return(Response.Get(type, deviceId, baseResponse.Socket));
            }

            // Remove first 2 bytes, and last byte
            var payload = response.Slice(2, response.Length - 3);

            // Check remaining payload length
            if (payload.Length != _payloadSize)
            {
                logger?.LogError(
                    $"The inquiry response's payload length '{payload.Length}' is invalid, should be '{_payloadSize}'.");
                return(Response.Get(ResponseType.Unknown, deviceId));
            }

            // Finally parse payload
            return(!_tryParseResponseDelegate(payload, out var result, logger)
                   // Trust the delegate to log any failure reasons
                ? InquiryResponse <T> .Get(ResponseType.Unknown, result, deviceId)
                : InquiryResponse <T> .Get(result, deviceId));
        }
        /// <summary>
        /// Common logic for handling web exceptions when connecting to the SonarQube server. Common exceptions 
        /// are handled by logging user friendly errors.
        /// </summary>
        /// <returns>True if the exception was handled</returns>
        public static bool HandleHostUrlWebException(WebException ex, string hostUrl, ILogger logger)
        {
            var response = ex.Response as HttpWebResponse;
            if (response != null && response.StatusCode == HttpStatusCode.NotFound)
            {
                logger.LogError(Resources.ERROR_FileNotFound, response.ResponseUri);
                return true;
            }

            if (ex.Status == WebExceptionStatus.NameResolutionFailure)
            {
                logger.LogError(Resources.ERROR_UrlNameResolutionFailed, hostUrl);
                return true;
            }

            if (ex.Status == WebExceptionStatus.ConnectFailure)
            {
                logger.LogError(Resources.ERROR_ConnectionFailed, hostUrl);
                return true;
            }

            if (ex.Status == WebExceptionStatus.TrustFailure)
            {
                logger.LogError(Resources.ERROR_TrustFailure, hostUrl);
                return true;
            }

            return false;
        }
Exemple #14
0
        public static QueuedItem QueuedItemFromSensorDataContract( SensorDataContract sensorData, ILogger logger = null )
        {
            if( sensorData == null )
            {
                return null;
            }

            QueuedItem result = null;
            try
            {
                result = new QueuedItem
                {
                    JsonData = JsonConvert.SerializeObject( sensorData )
                };
            }
            catch( Exception ex )
            {
                if( logger != null )
                {
                    logger.LogError( "Error on serialize item: " + ex.Message );
                }
            }

            return result;
        }
Exemple #15
0
 public static void Route(ILogger logger, string msg)
 {
     if (!msg.IsNullOrEmpty())
     {
         if (msg.StartsWith(StartVerbose))
             _isVerboseMode = true;
         else if (msg.StartsWith(StopVerbose))
             _isVerboseMode = false;
         else
         {
             if (msg.StartsWith(Verbose))
                 logger.LogVerbose(msg.Substring(Verbose.Length));
             else if (msg.StartsWith(Success))
                 logger.LogSuccess(msg.Substring(Success.Length));
             else if (msg.StartsWith(Warning))
                 logger.LogWarning(msg.Substring(Warning.Length));
             else if (msg.StartsWith(Error))
                 logger.LogError(msg.Substring(Error.Length));
             else if (msg.StartsWith(Header))
             {
                 _isVerboseMode = false;
                 logger.LogHeader(msg.Substring(Header.Length));
             }
             else if (_isVerboseMode)
                 logger.LogVerbose(msg);
             else
                 logger.LogInfo(msg);
         }
     }
     else
     {
         //logger.LogInfo(msg);
     }
 }
        public ProjectInfoAnalysisResult Execute(AnalysisConfig config, IEnumerable<string> userCmdLineArguments, ILogger logger)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }
            if (userCmdLineArguments == null)
            {
                throw new ArgumentNullException("userCmdLineArguments");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            ProjectInfoAnalysisResult result = PropertiesFileGenerator.GenerateFile(config, logger);
            Debug.Assert(result != null, "Not expecting the file generator to return null");
            result.RanToCompletion = false;

            SonarProjectPropertiesValidator.Validate(
                config.SonarRunnerWorkingDirectory,
                result.Projects,
                onValid: () =>
                {
                    InternalExecute(config, userCmdLineArguments, logger, result);
                },
                onInvalid: (invalidFolders) =>
                {
                    // LOG error message
                    logger.LogError(Resources.ERR_ConflictingSonarProjectProperties, string.Join(", ", invalidFolders));
                });

            return result;
        }
        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;
        }
        /// <summary>
        /// Serializes an <see cref="Incident"/> instance based on the specified <see cref="AlertNotificationData"/> instance.
        /// </summary>
        /// <param name="monitorName"><see cref="string"/> name of relevant monitor.</param>
        /// <param name="data">Specified <see cref="AlertNotificationData"/> instance.</param>
        /// <param name="logger">OPTIONAL: <see cref="ILogger"/> handle.</param>
        /// <returns><see cref="string"/> representing serialized <see cref="Incident"/></returns>
        public string GetIncidentDescription(string monitorName, AlertNotificationData data, ILogger?logger = null)
        {
            Incident incident = new Incident
            {
                MonitorName   = monitorName,
                OcurrenceDate = DateTime.UtcNow,
                HowDetected   = Detection.Monitoring,
                Symptoms      = new List <Symptom>
                {
                    new Symptom
                    {
                        Details = new CommonContent
                        {
                            Description = $"{data.Message ?? string.Empty}",
                            Labels      = new string[]
                            {
                                "monitoring failure"
                            }
                        }
                    }
                }
            };

            try
            {
                return(_serializer.GetString(incident));
            }
            catch (Exception e)
            {
                logger?.LogError($"Problem serializing {typeof(Incident)} instance.  Error: {e}");
                return(string.Empty);
            }
        }
Exemple #19
0
        public TypeInfo Build(ModuleBuilder moduleBuilder, ILogger?logger = default, string?className = default)
        {
            _typeBuilder = moduleBuilder.DefineType(
                className ?? _description.EndpointClassName,
                TypeAttributes.NotPublic | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit);

            _ctor = _typeBuilder
                    .DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, null)
                    .GetILGenerator();
            _ctor.Emit(OpCodes.Ldarg_0);
            _ctor.Emit(OpCodes.Call, typeof(object).Constructor());

            foreach (var interfaceDescription in _description.Services)
            {
                foreach (var operation in interfaceDescription.Operations)
                {
                    if (IsSupportedContextInput(operation.Message))
                    {
                        BuildOperation(operation, interfaceDescription.InterfaceType);
                    }
                    else
                    {
                        var error = "Context options in [{0}] are not supported.".FormatWith(ReflectionTools.GetSignature(operation.Message.Operation));
                        logger?.LogError("Service {0}: {1}", _description.ServiceType.FullName, error);
                        BuildNotSupportedOperation(operation, interfaceDescription.InterfaceType, error);
                    }
                }
            }

            _ctor.Emit(OpCodes.Ret);

            return(_typeBuilder.CreateTypeInfo() !);
        }
Exemple #20
0
        public static void Main(string[] args) {
            var configBuilder = new ConfigurationBuilder().AddCommandLine(args);
            Configuration = configBuilder.Build();

            string configFile = Configuration["config"];
            if (configFile != null) {
                configBuilder.AddJsonFile(configFile, optional: false);
                Configuration = configBuilder.Build();
            }

            ConfigurationBinder.Bind(Configuration.GetSection("startup"), _startupOptions);
            ConfigurationBinder.Bind(Configuration.GetSection("security"), _securityOptions);

            _loggerFactory
                .AddDebug()
                .AddConsole(LogLevel.Trace)
                .AddProvider(new FileLoggerProvider(_startupOptions.Name));
            _logger = _loggerFactory.CreateLogger<Program>();

            if (_startupOptions.Name != null) {
                _logger.LogInformation(Resources.Info_BrokerName, _startupOptions.Name);
            }

            var tlsConfig = new TlsConfiguration(_logger, _securityOptions);
            var httpsOptions = tlsConfig.GetHttpsOptions(Configuration);

            Uri uri = GetServerUri(Configuration);
            try {
                CreateWebHost(httpsOptions).Run();
            } catch(AggregateException ex) when (ex.IsPortInUseException()) {
                _logger.LogError(0, ex.InnerException, Resources.Error_ConfiguredPortNotAvailable, uri?.Port);
            }
        }
        /// <summary>
        /// Publishes a message with awaiting acknowledgement.
        /// If you want, you can await this task for ack.
        /// </summary>
        /// <remarks>
        ///   <para>
        ///     Routing key must be shorter than 255 bytes.
        ///   </para>
        /// </remarks>
        public Task BasicPublishAsync(
            string exchange,
            string routingKey,
            bool mandatory,
            IBasicProperties basicProperties,
            ReadOnlyMemory <byte> body,
            int retryCount = 5,
            CancellationToken cancellationToken = default
            )
        {
            return(Policy
                   .Handle <OperationCanceledException>()
                   .WaitAndRetryAsync(
                       retryCount,
                       retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                       (ex, _, count, ctx) =>
            {
                if (count == retryCount)
                {
                    _logger?.LogError(
                        ex,
                        "Попытка опубликовать сообщение {Exchange} {RoutingKey} с RabbitMq {Count} из {RetryCount}",
                        exchange,
                        routingKey,
                        count,
                        retryCount
                        );
                }
            })
                   .ExecuteAsync(async ct =>
            {
                var publishInfo = CreatePublishTask(exchange, routingKey, mandatory, basicProperties, body);

                try
                {
                    await publishInfo.Task.CancelAfterAsync(_confirmTimeout, ct);
                }
                catch (OperationCanceledException)
                {
                    publishInfo.PublishNotConfirmed("Publish task cancelled.");
                    _publishTasks.TryRemove(publishInfo.PublishTag, out _);

                    throw;
                }
            }, cancellationToken));
        }
Exemple #22
0
        /// <inheritdoc/>
        /// <seealso href="https://reference.opcfoundation.org/v104/Core/docs/Part4/5.5.3/">OPC UA specification Part 4: Services, 5.5.3</seealso>
        protected override async Task OnCloseAsync(CancellationToken token = default)
        {
            try
            {
                var request = new CloseSecureChannelRequest {
                    RequestHeader = new RequestHeader {
                        TimeoutHint = TimeoutHint, ReturnDiagnostics = DiagnosticsHint
                    }
                };
                await RequestAsync(request).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger?.LogError($"Error closing secure channel. {ex.Message}");
            }

            await base.OnCloseAsync(token).ConfigureAwait(false);
        }
        /// <inheritdoc />
        public async Task <MigrationResult> MigrateSafeAsync(CancellationToken token = default)
        {
            try
            {
                await MigrateAsync(token);

                return(MigrationResult.SuccessfullyResult());
            }
            catch (MigrationException e)
            {
                _logger?.LogError(e, e.Message);
                return(MigrationResult.FailureResult(e.Error, e.Message));
            }
            catch (Exception e)
            {
                _logger?.LogError(e, $"Error while migrating database {_dbProvider.DbName}. Reason: {e.Message}");
                return(MigrationResult.FailureResult(MigrationError.Unknown, e.Message));
            }
        }
Exemple #24
0
        internal bool SetCurrentDataSet(string json, ILogger?logger = null)
        {
            CurrentDataSet = DeserializeArcgis(json);

            if (CurrentDataSet is null)
            {
                logger?.LogError("Deserialization failed, CurrentDataSet is null");
                return(false);
            }

            if (!CurrentDataSet.Features.Any())
            {
                logger?.LogError("Deserialization failed, no features");
                return(false);
            }

            LastUpdate           = CurrentDataSet.Features.First().Attributes.LastUpdate;
            PastData[LastUpdate] = CurrentDataSet;
            return(true);
        }
        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;
        }
 private static void LogProcessingCompleted(AnalysisPhase phase, int exitCode, ILogger logger)
 {
     string phaseLabel = phase == AnalysisPhase.PreProcessing ? Resources.PhaseLabel_PreProcessing : Resources.PhaseLabel_PostProcessing;
     if (exitCode == ProcessRunner.ErrorCode)
     {
         logger.LogError(Resources.ERROR_ProcessingFailed, phaseLabel, exitCode);
     }
     else
     {
         logger.LogInfo(Resources.MSG_ProcessingSucceeded, phaseLabel);
     }
 }
Exemple #27
0
        private Type?ResolveDetailType(string typeName)
        {
            try
            {
                return(Type.GetType(typeName, true, false));
            }
            catch (Exception ex)
            {
                _logger?.LogError("Fail to resolve fault detail type {0}: {1}", typeName, ex);
            }

            return(null);
        }
        protected override bool TryGetBinaryReportFile(AnalysisConfig config, TeamBuildSettings settings, ILogger logger, out string binaryFilePath)
        {
            IEnumerable<string> urls = this.urlProvider.GetCodeCoverageReportUrls(config.GetTfsUri(), config.GetBuildUri(), logger);
            Debug.Assert(urls != null, "Not expecting the returned list of urls to be null");

            bool continueProcessing = true;
            binaryFilePath = null;

            switch (urls.Count())
            {
                case 0:
                    logger.LogInfo(Resources.PROC_DIAG_NoCodeCoverageReportsFound);
                    break;

                case 1:
                    string url = urls.First();

                    string targetFileName = Path.Combine(config.SonarOutputDir, DownloadFileName);
                    bool result = this.downloader.DownloadReport(config.GetTfsUri(), url, targetFileName, logger);

                    if (result)
                    {
                        binaryFilePath = targetFileName;
                    }
                    else
                    {
                        continueProcessing = false;
                        logger.LogError(Resources.PROC_ERROR_FailedToDownloadReport);
                    }
                    break;

                default: // More than one
                    continueProcessing = false;
                    logger.LogError(Resources.PROC_ERROR_MultipleCodeCoverageReportsFound);
                    break;
            }

            return continueProcessing;
        }
Exemple #29
0
        private static bool ParseEnum <T>(byte b, out T result, ILogger?logger, bool strict = false) where T : Enum
        {
            result = (T)(object)b;
            if (b != 0xFF &&
                (!strict || Enum.IsDefined(typeof(T), result)))
            {
                return(true);
            }

            logger?.LogError($"Invalid '{typeof(T).Name}' value '0x{b:X2}' received.");
            b      = 0xFF;
            result = (T)(object)b;
            return(false);
        }
Exemple #30
0
 internal static async Task OnEventDispatchedMethod(IDomainEvent @event)
 {
     if (Client != null)
     {
         try
         {
             await new MongoDbEventStore(Options.SnapshotBehaviorProvider).StoreDomainEventAsync(@event).ConfigureAwait(false);
         }
         catch (Exception exc)
         {
             _logger?.LogError($"EventHandler.OnEventDispatchedMethod() : Exception {exc}");
         }
     }
 }
Exemple #31
0
 protected T WithWritableTransaction <T>(Func <LightningDatabase, LightningTransaction, T> func, ILogger?logger = default)
 {
     using var tx = Env.BeginTransaction(TransactionBeginFlags.None);
     try
     {
         using var db = tx.OpenDatabase(configuration: Config);
         var result = func.Invoke(db, tx); // NOTE: function is expected to call tx.Commit()
         return(result);
     }
     catch (Exception e)
     {
         logger?.LogError(ErrorEvents.ErrorSavingResource, e, "Unable to write to lmdb transaction", e);
         throw;
     }
 }
 public int Run()
 {
     _logger?.LogInformation("Running application in RUN mode.");
     using var packer = _serviceProvider.GetService <IPacker>();
     try
     {
         packer.Pack();
     }
     catch (Exception e)
     {
         _logger?.LogError($"Unable to pack a MEG file: {e.Message}", e);
         return(1);
     }
     return(0);
 }
Exemple #33
0
 public static void Assert(
     bool state,
     string message,
     ILogger?logger = null,
     [CallerMemberName] string function = "",
     [CallerFilePath] string path       = "",
     [CallerLineNumber] int lineNumber  = 0
     )
 {
     if (!state)
     {
         message += ", " + FormatCaller(function, path, lineNumber);
         logger?.LogError(message);
         throw new ArgumentException(message);
     }
 }
Exemple #34
0
 public static bool TryParseJson <T>(this TwinCollection twinCollection, string property, ILogger?logger, [NotNullWhen(true)] out T?value)
 {
     value = default;
     if (twinCollection.TryReadJsonBlock(property, out var json))
     {
         try
         {
             value = JsonSerializer.Deserialize <T>(json);
         }
         catch (JsonException ex)
         {
             logger?.LogError(ex, $"Failed to parse '{property}'. We expect type '{typeof(T)}'");
         }
     }
     return(value != null);
 }
Exemple #35
0
 protected T WithReadOnlyCursor <T>(Func <LightningCursor, LightningTransaction, T> func, ILogger?logger = default)
 {
     using var tx = Env.BeginTransaction(TransactionBeginFlags.ReadOnly);
     try
     {
         using var db     = tx.OpenDatabase(configuration: Config);
         using var cursor = tx.CreateCursor(db);
         var result = func.Invoke(cursor, tx);
         return(result);
     }
     catch (Exception e)
     {
         logger?.LogError(ErrorEvents.ErrorSavingResource, e, "Unable to read from lmdb transaction", e);
         tx.Reset();
         throw;
     }
 }
Exemple #36
0
        public static IApplicationBuilder UseProblemDetailsExceptionHandler(this IApplicationBuilder app, IWebHostEnvironment env, ILogger?logger = null,
                                                                            string correlationRequestIdHeader = DefaultRequestHeader)
        {
            app.UseExceptionHandler(builder =>
            {
                builder.Run(
                    async context =>
                {
                    context.Response.StatusCode  = (int)ExceptionStatusCode;
                    context.Response.ContentType = ContentType;

                    var feature = context.Features.Get <IExceptionHandlerFeature>();
                    if (feature?.Error is null)
                    {
                        return;
                    }

                    var exception = feature.Error;
                    logger?.LogError(exception, exception.Message);

                    var accessor    = (IHttpContextAccessor)builder.ApplicationServices.GetService(typeof(IHttpContextAccessor));
                    var httpContext = accessor.HttpContext ?? new DefaultHttpContext();

                    var title   = ReasonPhrases.GetReasonPhrase((int)ExceptionStatusCode);
                    var factory = (PublicProblemDetailsFactory)builder.ApplicationServices.GetService(typeof(ProblemDetailsFactory));
                    var details = factory.CreateProblemDetails(httpContext, ExceptionStatusCode, title, exception.Message);
                    httpContext.Request.Headers.TryGetValue(correlationRequestIdHeader, out var requestId);
                    details.Extensions.Add(new KeyValuePair <string, object>(correlationRequestIdHeader, requestId));

                    if (!env.IsProduction())
                    {
                        details.Extensions.Add(nameof(exception.StackTrace), exception.StackTrace);
                    }

                    foreach (DictionaryEntry entry in exception.Data)
                    {
                        details.Extensions.Add(entry.Key.ToString() !, entry.Value);
                    }

                    await StreamHelper.CopyDetailsTo(context.Response.Body, details);
                });
            });

            return(app);
        }
        public async Task <AsyncCacheResult> GetAsync(string key)
        {
            AsyncCacheResult res;

            try
            {
                res = await _cache.GetAsync(key);
            }
            catch (Exception e)
            {
                _logger?.LogError(e, "An error occured getting key '{key}' from distributed cache", key);
                throw;
            }

            bool shouldLog = _logger != null && _logger.IsEnabled(LogLevel.Trace);

            switch (res.Status)
            {
            case AsyncCacheStatus.Hit:
                _metrics.IncrementDistributedCacheGetHits();
                if (shouldLog)
                {
                    _logger.Log(LogLevel.Trace, "IAsyncCache: GET {0} -> HIT {1}B", key, res.Value !.Length);
                }
                break;

            case AsyncCacheStatus.Miss:
                _metrics.IncrementDistributedCacheGetMisses();
                if (shouldLog)
                {
                    _logger.Log(LogLevel.Trace, "IAsyncCache: GET  {0} -> MISS", key);
                }
                break;

            case AsyncCacheStatus.Error:
                _metrics.IncrementDistributedCacheGetErrors();
                if (shouldLog)
                {
                    _logger.Log(LogLevel.Trace, "IAsyncCache: GET  {0} -> ERROR", key);
                }
                break;
            }

            return(res);
        }
Exemple #38
0
        public static MemoryStream Compile(string assemblyName, AssemblyInfo assemblyInfo, IEnumerable<SyntaxTree> trees, IEnumerable<MetadataReference> references, ILogger logger = null)
        {
            trees = trees.Concat(new[] { GetAssemblyInfo(assemblyInfo) });
            var compilation = CSharpCompilation.Create(assemblyName, trees, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            var stream = new MemoryStream();
            var result = compilation.Emit(stream);
            if (!result.Success && logger != null)
            {
                foreach (var message in result.Diagnostics.Select(i => i.ToString()))
                {
                    logger.LogError(message);
                }
                return null;
            }
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }
        /// <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;
            }
        }
        public static void InvokeAll <TA>(this ConcurrentDictionary <Assembly, Action <TA> > dict, Assembly assembly, TA a, ILogger?logger = null)
        {
            foreach (var kvp in dict)
            {
                if (kvp.Key == assembly)
                {
                    continue;
                }

                try
                {
                    kvp.Value?.Invoke(a);
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex, $"An exception occurred while invoking action with param type {typeof(TA).Name}");
                }
            }
        }
Exemple #41
0
        public static void Assert <T>(
            bool test,
            string message,
            ILogger?logger = null,
            [CallerMemberName] string function = "",
            [CallerFilePath] string path       = "",
            [CallerLineNumber] int lineNumber  = 0
            ) where T : Exception
        {
            if (test)
            {
                return;
            }
            message.VerifyNotEmpty(nameof(message));

            message += ", " + FormatCaller(function, path, lineNumber);
            logger?.LogError(message);
            throw (Exception)Activator.CreateInstance(typeof(T), message) !;
        }
        public static void InvokeAll(this ConcurrentDictionary <Assembly, Action> dict, Assembly assembly, ILogger?logger = null)
        {
            foreach (var kvp in dict)
            {
                if (kvp.Key == assembly)
                {
                    continue;
                }

                try
                {
                    kvp.Value?.Invoke();
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex, $"An exception occurred while invoking action no params.");
                }
            }
        }
 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);
     }
 }
        public void Validate(ILogger?logger)
        {
            var now = DateTime.Now;

            var itemsSnapshot = _items.Values;

            foreach (var item in itemsSnapshot)
            {
                int duration = Convert.ToInt32(now.Subtract(item.Entered).TotalSeconds);
                if (duration >= item.Timeout)
                {
                    logger?.LogError("STUCK CODE: \"{StuckCodeLabel}\", duration {StuckCodeDuration} (entered at {StuckCodeEnterTime} from thread #{StuckCodeThreadId})",
                                     item.Label,
                                     duration.ToMinSec(),
                                     item.Entered.ToString(LoggerCi),
                                     item.ThreadId);
                }
            }
        }
        /// <summary>
        /// Attempts to load the analysis config file. The location of the file is
        /// calculated from TeamBuild-specific environment variables.
        /// Returns null if the required environment variables are not available.
        /// </summary>
        private static AnalysisConfig GetAnalysisConfig(TeamBuildSettings teamBuildSettings, ILogger logger)
        {
            AnalysisConfig config = null;

            if (teamBuildSettings != null)
            {
                string configFilePath = teamBuildSettings.AnalysisConfigFilePath;
                Debug.Assert(!string.IsNullOrWhiteSpace(configFilePath), "Expecting the analysis config file path to be set");

                if (File.Exists(configFilePath))
                {
                    config = AnalysisConfig.Load(teamBuildSettings.AnalysisConfigFilePath);
                }
                else
                {
                    logger.LogError(Resources.ERROR_ConfigFileNotFound, configFilePath);
                }
            }
            return config;
        }
Exemple #46
0
        public static SensorDataContract SensorDataContractFromString( string data, ILogger logger = null )
        {
            SensorDataContract result;
            try
            {
                result =
                    JsonConvert.DeserializeObject<SensorDataContract>( data );
            }
            catch( Exception ex )
            {
                result = null;
                //TODO: maybe better to add some metrics instead
                if( logger != null )
                {
                    logger.LogError( "Error on deserialize item: " + ex.Message );
                }
            }

            return result;
        }
        private void InternalDownloadReport(string tfsUri, string reportUrl, string reportDestinationPath, ILogger logger)
        {
            VssHttpMessageHandler vssHttpMessageHandler = GetHttpHandler(tfsUri, logger);

            logger.LogInfo(Resources.DOWN_DIAG_DownloadCoverageReportFromTo, reportUrl, reportDestinationPath);

            using (HttpClient httpClient = new HttpClient(vssHttpMessageHandler))
            using (HttpResponseMessage response = httpClient.GetAsync(reportUrl).Result)
            {
                if (response.IsSuccessStatusCode)
                {
                    using (FileStream fileStream = new FileStream(reportDestinationPath, FileMode.Create, FileAccess.Write))
                    {
                        response.Content.CopyToAsync(fileStream).Wait();
                    }
                }
                else
                {
                    logger.LogError(Resources.PROC_ERROR_FailedToDownloadReportReason, reportUrl, response.StatusCode, response.ReasonPhrase);
                }
            }
        }
        public static async Task<HttpResponseMessage> GetAsync(this HttpClient httpClient, string requestUri,
            ILogger logger)
        {
            if (logger == null)
            {
                return await httpClient.GetAsync(requestUri);
            }

            logger.LogVerbose($"Sending request {requestUri}");
            var now = DateTimeOffset.Now;
            var res = await httpClient.GetAsync(requestUri).ConfigureAwait(false);
            if (res.IsSuccessStatusCode)
            {
                logger.LogVerbose(
                    $"Got response {res.StatusCode} in {(DateTimeOffset.Now - now).TotalMilliseconds.ToString("F2")}ms");
            }
            else
            {
                logger.LogError(
                    $"Got response {res.StatusCode} in {(DateTimeOffset.Now - now).TotalMilliseconds.ToString("F2")}ms");
            }
            return res;
        }
        public bool Execute(string[] args, ILogger logger)
        {
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            bool success;

            ProcessedArgs processedArgs = ArgumentProcessor.TryProcessArgs(args, logger);

            if (processedArgs == null)
            {
                success = false;
                logger.LogError(Resources.ERROR_InvalidCommandLineArgs);
            }
            else
            {
                success = DoExecute(processedArgs, logger);
            }

            return success;
        }
Exemple #50
0
        public void Execute(
            ILogger logger,
            string sourceAssemblyPath,
            string derivatorClassName,
            string derivedPath)
        {
            var sourceAssembly = Assembly.LoadFrom(sourceAssemblyPath);

            ResolveAssemblyByDir(
                ()=>
                {
                    Type derivatorType = Type.GetType(derivatorClassName);
                    if (derivatorType == null)
                    {
                        logger.LogError("Unable to load derivator type from {0}", derivatorClassName);
                        return;
                    }

                    IDerivator derivator = (IDerivator)Activator.CreateInstance(derivatorType);
                    derivator.Execute(logger, sourceAssembly, derivedPath, GetDir(derivatorType.Assembly));
                },
                Path.GetDirectoryName(sourceAssemblyPath));
        }
Exemple #51
0
        /// <summary>
        /// Start the service
        /// </summary>
        /// <remarks>This service is not receiving any arguments at the moment</remarks>
        /// <param name="args">Arguments to receive when starting the service</param>
        protected override void OnStart(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            log = LogFactory.GetLogger(typeof(Service));
            log.LogInfo("Service Started.");
            try
            {

                //get service credential details
                if (!string.IsNullOrEmpty(serviceUserName))
                {
                    //Check what is the user for this service. If the user doesn't exist then it should create it.
                    MembershipUser membershipUser = Membership.GetUser(serviceUserName);

                    if (membershipUser == null)
                    {
                        //Could not acquire user.
                        log.LogFatal("Eagle Service cannot acquire user to execute tasks and it is going to stop.");
                        return;
                    }

                    //Add the identity and principal of our internal service user to the current principal
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(membershipUser.ProviderUserKey.ToString()), null);
                    ServiceTaskManager.Initialize();
                }
                else
                {
                    //Could not acquire user.
                    log.LogFatal("Eagle Service cannot acquire user to execute tasks and it is going to stop.");
                }
            }
            catch (Exception e)
            {
                log.LogError("Error on service start", ex: e);
            }
        }
Exemple #52
0
 public void Log(ILogger logger)
 {
     logger.LogError(message);
 }
Exemple #53
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;
            }
        }
Exemple #54
0
        private static int CheckPort(CommandOption port, ILogger logger)
        {
            if (!port.HasValue())
            {
                logger.LogError($"Option \"{port.LongName}\" is missing.");
            }

            int result;
            if (int.TryParse(port.Value(), out result))
            {
                return result;
            }
            else
            {
                logger.LogError($"Option \"{port.LongName}\" is not a valid Int32 value.");
                return -1;
            }
        }
        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 static async Task CollectRefactoringActions(IEnumerable<ICodeActionProvider> codeActionProviders, ILogger logger, CodeRefactoringContext? refactoringContext)
        {
            if (!refactoringContext.HasValue)
                return;

            foreach (var provider in codeActionProviders)
            {
                foreach (var refactoring in provider.Refactorings)
                {
                    if (_blacklist.Contains(refactoring.ToString()))
                    {
                        continue;
                    }

                    try
                    {
                        await refactoring.ComputeRefactoringsAsync(refactoringContext.Value);
                    }
                    catch
                    {
                        logger.LogError("Error computing refactorings for " + refactoring);
                    }
                }
            }
        }
        private static async Task CollectCodeFixActions(IEnumerable<ICodeActionProvider> codeActionProviders, ILogger logger, CodeFixContext? fixContext)
        {
            if (!fixContext.HasValue)
                return;

            foreach (var provider in codeActionProviders)
            {
                foreach (var codeFix in provider.CodeFixes)
                {
                    if (_blacklist.Contains(codeFix.ToString()))
                    {
                        continue;
                    }

                    try
                    {
                        await codeFix.RegisterCodeFixesAsync(fixContext.Value);
                    }
                    catch
                    {
                        logger.LogError("Error registering code fixes " + codeFix);
                    }
                }
            }
        }
        /// <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;
        }
        /* for test purposes */
        public static bool ExecuteJavaRunner(AnalysisConfig config, IEnumerable<string> userCmdLineArguments, ILogger logger, string exeFileName, string propertiesFileName)
        {
            Debug.Assert(File.Exists(exeFileName), "The specified exe file does not exist: " + exeFileName);
            Debug.Assert(File.Exists(propertiesFileName), "The specified properties file does not exist: " + propertiesFileName);

            IgnoreSonarScannerHome(logger);

            IEnumerable<string> allCmdLineArgs = GetAllCmdLineArgs(propertiesFileName, userCmdLineArguments, config);

            IDictionary<string, string> envVarsDictionary = GetAdditionalEnvVariables(logger);
            Debug.Assert(envVarsDictionary != null);

            logger.LogInfo(Resources.MSG_SonarScannerCalling);

            Debug.Assert(!String.IsNullOrWhiteSpace(config.SonarRunnerWorkingDirectory), "The working dir should have been set in the analysis config");
            Debug.Assert(Directory.Exists(config.SonarRunnerWorkingDirectory), "The working dir should exist");

            ProcessRunnerArguments runnerArgs = new ProcessRunnerArguments(exeFileName, logger)
            {
                CmdLineArgs = allCmdLineArgs,
                WorkingDirectory = config.SonarRunnerWorkingDirectory,
                EnvironmentVariables = envVarsDictionary
            };

            ProcessRunner runner = new ProcessRunner();

            // SONARMSBRU-202 Note that the Sonar Scanner may write warnings to stderr so
            // we should only rely on the exit code when deciding if it ran successfully
            bool success = runner.Execute(runnerArgs);

            if (success)
            {
                logger.LogInfo(Resources.MSG_SonarScannerCompleted);
            }
            else
            {
                logger.LogError(Resources.ERR_SonarScannerExecutionFailed);
            }
            return success;
        }
Exemple #60
-3
        /// <summary>
        /// Retries every 1 sec for 60 times by default.
        /// </summary>
        /// <param name="retryBlock"></param>
        /// <param name="logger"></param>
        /// <param name="cancellationToken"></param>
        /// <param name="retryCount"></param>
        public static async Task<HttpResponseMessage> RetryRequest(
            Func<Task<HttpResponseMessage>> retryBlock,
            ILogger logger,
            CancellationToken cancellationToken = default(CancellationToken),
            int retryCount = 60)
        {
            for (int retry = 0; retry < retryCount; retry++)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    logger.LogInformation("Failed to connect, retry canceled.");
                    throw new OperationCanceledException("Failed to connect, retry canceled.", cancellationToken);
                }

                try
                {
                    logger.LogWarning("Retry count {retryCount}..", retry + 1);
                    var response = await retryBlock();

                    if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        // Automatically retry on 503. May be application is still booting.
                        logger.LogWarning("Retrying a service unavailable error.");
                        continue;
                    }

                    return response; // Went through successfully
                }
                catch (Exception exception)
                {
                    if (retry == retryCount - 1)
                    {
                        logger.LogError("Failed to connect, retry limit exceeded.", exception);
                        throw;
                    }
                    else
                    {
                        if (exception is HttpRequestException
#if DNX451
                        || exception is System.Net.WebException
#endif
                        )
                        {
                            logger.LogWarning("Failed to complete the request : {0}.", exception.Message);
                            await Task.Delay(1 * 1000); //Wait for a while before retry.
                        }
                    }
                }
            }

            logger.LogInformation("Failed to connect, retry limit exceeded.");
            throw new OperationCanceledException("Failed to connect, retry limit exceeded.");
        }