Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            try
            {
                Environment.SetEnvironmentVariable("GIGYA_CONFIG_ROOT", Environment.CurrentDirectory);
                Environment.SetEnvironmentVariable("GIGYA_CONFIG_PATHS_FILE", "");
                Environment.SetEnvironmentVariable("GIGYA_ENVVARS_FILE", Environment.CurrentDirectory);
                Environment.SetEnvironmentVariable("REGION", "us1");
                Environment.SetEnvironmentVariable("ZONE", "us1a");
                Environment.SetEnvironmentVariable("ENV", "dev");

                CurrentApplicationInfo.Init("CalculatorService.Client");

                var kernel = new StandardKernel();
                kernel.Load <MicrodotModule>();
                kernel.Load <NLogModule>();

                ICalculatorService calculatorService = kernel.Get <ICalculatorService>();
                int sum = calculatorService.Add(2, 3).Result;
                Console.WriteLine($"Sum: {sum}");
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
        }
Ejemplo n.º 2
0
        public static void Main(string[] args)
        {
            Environment.SetEnvironmentVariable("HS_CONFIG_ROOT", Environment.CurrentDirectory);
            CurrentApplicationInfo.Init("TimeTracker-ReportService");

            IConfiguration config = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", true, true)
                                    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", true, true)
                                    .AddEnvironmentVariables()
                                    .Build();

            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
            {
                Task.Factory.StartNew(() => CreateWebHostBuilder(args).Build().Run(), TaskCreationOptions.AttachedToParent)
                .ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        Console.WriteLine(task.Exception.ToString());
                    }
                });
            }

            var host = new ReportServiceHost(config);

            if (int.TryParse(Environment.GetEnvironmentVariable("PORT"), out int envPort))
            {
                host.Run(new ServiceArguments(basePortOverride: envPort));
            }
            else
            {
                host.Run();
            }
        }
Ejemplo n.º 3
0
        public ServiceProxyProvider(string serviceName, IEventPublisher <ClientCallEvent> eventPublisher,
                                    ICertificateLocator certificateLocator,
                                    ILog log,
                                    Func <string, ReachabilityCheck, IMultiEnvironmentServiceDiscovery> serviceDiscoveryFactory,
                                    Func <DiscoveryConfig> getConfig,
                                    JsonExceptionSerializer exceptionSerializer,
                                    CurrentApplicationInfo appInfo)
        {
            EventPublisher     = eventPublisher;
            CertificateLocator = certificateLocator;

            Log = log;

            ServiceName         = serviceName;
            GetDiscoveryConfig  = getConfig;
            ExceptionSerializer = exceptionSerializer;
            AppInfo             = appInfo;

            var metricsContext = Metric.Context(METRICS_CONTEXT_NAME).Context(ServiceName);

            _serializationTime   = metricsContext.Timer("Serialization", Unit.Calls);
            _deserializationTime = metricsContext.Timer("Deserialization", Unit.Calls);
            _roundtripTime       = metricsContext.Timer("Roundtrip", Unit.Calls);

            _successCounter              = metricsContext.Counter("Success", Unit.Calls);
            _failureCounter              = metricsContext.Counter("Failed", Unit.Calls);
            _hostFailureCounter          = metricsContext.Counter("HostFailure", Unit.Calls);
            _applicationExceptionCounter = metricsContext.Counter("ApplicationException", Unit.Calls);

            ServiceDiscovery = serviceDiscoveryFactory(serviceName, ValidateReachability);
        }
Ejemplo n.º 4
0
        public TestingKernel(Action <IKernel> additionalBindings = null, Dictionary <string, string> mockConfig = null)
        {
            CurrentApplicationInfo.Init(APPNAME);


            this.Load <MicrodotModule>();

            Rebind <IEventPublisher>().To <NullEventPublisher>();
            Rebind <ILog>().To <T>().InSingletonScope();
            Rebind <IDiscoverySourceLoader>().To <AlwaysLocalHost>().InSingletonScope();
            var locationsParserMock = Substitute.For <IConfigurationLocationsParser>();

            locationsParserMock.ConfigFileDeclarations.Returns(Enumerable.Empty <ConfigFileDeclaration>().ToArray());
            Rebind <IConfigurationLocationsParser>().ToConstant(locationsParserMock);
            Rebind <IMetricsInitializer>().To <MetricsInitializerFake>().InSingletonScope();

            additionalBindings?.Invoke(this);

            Rebind <IConfigurationDataWatcher, ManualConfigurationEvents>()
            .To <ManualConfigurationEvents>()
            .InSingletonScope();

            Rebind <IConfigItemsSource, OverridableConfigItems>()
            .To <OverridableConfigItems>()
            .InSingletonScope()
            .WithConstructorArgument("data", mockConfig ?? new Dictionary <string, string>());



            Rebind <IHealthMonitor>().To <FakeHealthMonitor>().InSingletonScope();
        }
        public Application(
            IExecutionOrderBookRepository executionOrderBookRepository,
            ILog logger,
            Settings settings,
            CurrentApplicationInfo applicationInfo,
            ISlackNotificationsSender slackNotificationsSender)
            : base(logger, slackNotificationsSender, applicationInfo, MessageFormat.MessagePack)
        {
            _executionOrderBookRepository = executionOrderBookRepository;
            _log      = logger;
            _settings = settings;

            _retryPolicy = Policy
                           .Handle <Exception>()
                           .WaitAndRetryAsync(new[]
            {
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(4),
                TimeSpan.FromSeconds(8),
            }, onRetry: (exception, timespan, retryCount, context) =>
            {
                _log.WriteWarningAsync(nameof(ExecutionOrderBookBroker), nameof(HandleMessage),
                                       $"Cannot save orderBookMessage with order id {context["id"]}, external order id {context["externalOrderId"]}, retryCount {retryCount}",
                                       exception);
            });
        }
Ejemplo n.º 6
0
 public void OneTimeSetUp()
 {
     if (CurrentApplicationInfo.Name == null)
     {
         CurrentApplicationInfo.Init("Tests");
     }
 }
Ejemplo n.º 7
0
 public AccountStatSqlReportsApplication(ILog logger, Settings settings,
                                         CurrentApplicationInfo applicationInfo, IAccountsStatsReportsRepository accountsStatsReportsRepository,
                                         IMarginTradingAccountStatsRepository statsRepository, ISlackNotificationsSender slackNotificationsSender) :
     base(logger, settings, applicationInfo, accountsStatsReportsRepository, statsRepository,
          slackNotificationsSender)
 {
 }
Ejemplo n.º 8
0
 protected BrokerApplicationBase(ILog logger, ISlackNotificationsSender slackNotificationsSender,
                                 CurrentApplicationInfo applicationInfo)
 {
     _logger = logger;
     _slackNotificationsSender = slackNotificationsSender;
     ApplicationInfo           = applicationInfo;
 }
Ejemplo n.º 9
0
        public ConsulClient(string serviceName, Func <ConsulConfig> getConfig,
                            ISourceBlock <ConsulConfig> configChanged, IEnvironment environment,
                            ILog log, IDateTime dateTime, Func <string, AggregatingHealthStatus> getAggregatedHealthStatus,
                            CurrentApplicationInfo appInfo)
        {
            _serviceName       = serviceName;
            _serviceNameOrigin = serviceName;

            GetConfig = getConfig;
            _dateTime = dateTime;
            Log       = log;
            Zone      = environment.Zone;

            _waitForConfigChange = new TaskCompletionSource <bool>();
            configChanged.LinkTo(new ActionBlock <ConsulConfig>(ConfigChanged));

            ConsulAddress = new Uri($"http://{environment.ConsulAddress ?? $"{CurrentApplicationInfo.HostName}:8500"}");
            _httpClient   = new HttpClient {
                BaseAddress = ConsulAddress, Timeout = TimeSpan.FromMinutes(100)
            };                                                                                                 // timeout will be implemented using cancellationToken when calling httpClient
            var aggregatedHealthStatus = getAggregatedHealthStatus("ConsulClient");

            _resultChanged      = new BufferBlock <EndPointsResult>();
            _initializedVersion = new TaskCompletionSource <bool>();
            ShutdownToken       = new CancellationTokenSource();
            _healthCheck        = aggregatedHealthStatus.RegisterCheck(_serviceNameOrigin, () => _getHealthStatus());
        }
Ejemplo n.º 10
0
        private void OnWindowsServiceStart(string[] args)
        {
            if (Arguments == null)
            {
                Arguments = new ServiceArguments(args);
                CurrentApplicationInfo.Init(ServiceName, Arguments.InstanceName, InfraVersion);
            }

            try
            {
                if (Arguments.ServiceStartupMode != ServiceStartupMode.WindowsService)
                {
                    throw new InvalidOperationException($"Cannot start in {Arguments.ServiceStartupMode} mode when starting as a Windows service.");
                }

                if (Environment.UserInteractive == false)
                {
                    throw new InvalidOperationException(
                              "This Windows service requires to be run with 'user interactive' enabled to correctly read certificates. " +
                              "Either the service wasn't configure with the 'Allow service to interact with desktop' option enabled " +
                              "or the OS is ignoring the checkbox due to a registry settings. " +
                              "Make sure both the checkbox is checked and following registry key is set to DWORD '0':\n" +
                              @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\NoInteractiveServices");
                }

                WindowsService.RequestAdditionalTime(60000);

                OnStart();
            }
            catch
            {
                WindowsService.ExitCode = 1064; // "An exception occurred in the service when handling the control request." (net helpmsg 1064)
                throw;
            }
        }
Ejemplo n.º 11
0
        public HttpServiceListener(
            IActivator activator,
            IWorker worker,
            IServiceEndPointDefinition serviceEndPointDefinition,
            ICertificateLocator certificateLocator,
            ILog log,
            IEnumerable <ICustomEndpoint> customEndpoints,
            IEnvironment environment,
            JsonExceptionSerializer exceptionSerializer,
            ServiceSchema serviceSchema,
            Func <LoadShedding> loadSheddingConfig,
            IServerRequestPublisher serverRequestPublisher,
            CurrentApplicationInfo appInfo)
        {
            ServiceSchema           = serviceSchema;
            _serverRequestPublisher = serverRequestPublisher;

            ServiceEndPointDefinition = serviceEndPointDefinition;
            Worker              = worker;
            Activator           = activator;
            Log                 = log;
            CustomEndpoints     = customEndpoints.ToArray();
            Environment         = environment;
            ExceptionSerializer = exceptionSerializer;
            LoadSheddingConfig  = loadSheddingConfig;
            AppInfo             = appInfo;

            if (ServiceEndPointDefinition.HttpsPort != null && ServiceEndPointDefinition.ClientCertificateVerification != ClientCertificateVerificationMode.Disable)
            {
                ServerRootCertHash = certificateLocator.GetCertificate("Service").GetHashOfRootCertificate();
            }

            Listener = new HttpListener {
                IgnoreWriteExceptions = true
            };
            if (ServiceEndPointDefinition.HttpsPort != null)
            {
                Listener.Prefixes.Add($"https://+:{ServiceEndPointDefinition.HttpsPort}/");
            }
            if (ServiceEndPointDefinition.HttpPort != null)
            {
                Listener.Prefixes.Add($"http://+:{ServiceEndPointDefinition.HttpPort}/");
            }
            if (!Listener.Prefixes.Any())
            {
                Log.Warn(_ => _("HttpServiceListener is not listening on any ports, no HTTP or HTTPS ports in ServiceEndPointDefinition"));
            }

            var context = Metric.Context("Service").Context(AppInfo.Name);

            _serializationTime          = context.Timer("Serialization", Unit.Calls);
            _deserializationTime        = context.Timer("Deserialization", Unit.Calls);
            _roundtripTime              = context.Timer("Roundtrip", Unit.Calls);
            _metaEndpointsRoundtripTime = context.Timer("MetaRoundtrip", Unit.Calls);
            _successCounter             = context.Counter("Success", Unit.Calls);
            _failureCounter             = context.Counter("Failed", Unit.Calls);
            _activeRequestsCounter      = context.Timer("ActiveRequests", Unit.Requests);
            _endpointContext            = context.Context("Endpoints");
        }
Ejemplo n.º 12
0
 public MetricsInitializer(ILog log, IConfiguration configuration, IMetricsSettings metricsSettings, HealthMonitor healthMonitor, CurrentApplicationInfo appInfo)
 {
     Configuration   = configuration;
     MetricsSettings = metricsSettings;
     HealthMonitor   = healthMonitor;
     Log             = log;
     AppInfo         = appInfo;
 }
Ejemplo n.º 13
0
 public Application(IMarginTradingOrdersHistoryRepository ordersHistoryRepository, ILog logger,
                    Settings settings, CurrentApplicationInfo applicationInfo,
                    ISlackNotificationsSender slackNotificationsSender) : base(logger, slackNotificationsSender,
                                                                               applicationInfo)
 {
     _ordersHistoryRepository = ordersHistoryRepository;
     _settings = settings;
 }
Ejemplo n.º 14
0
 public Application(ILog logger, Settings settings,
                    CurrentApplicationInfo applicationInfo,
                    IOrderbookBestPricesRepository orderbookBestPricesRepository,
                    ISlackNotificationsSender slackNotificationsSender)
     : base(logger, slackNotificationsSender, applicationInfo)
 {
     _settings = settings;
     _orderbookBestPricesRepository = orderbookBestPricesRepository;
 }
Ejemplo n.º 15
0
 public Application(ILog logger, Settings settings,
                    CurrentApplicationInfo applicationInfo,
                    ISlackNotificationsSender slackNotificationsSender,
                    IReloadingManager <Settings> reloadingManager)
     : base(logger, slackNotificationsSender, applicationInfo)
 {
     _settings         = settings;
     _reloadingManager = reloadingManager;
 }
Ejemplo n.º 16
0
 public MetricsInitializer(ILog log, IConfiguration configuration, IMetricsSettings metricsSettings, HealthMonitor healthMonitor, IEnvironmentVariableProvider envProvider, CurrentApplicationInfo appInfo)
 {
     Configuration   = configuration;
     MetricsSettings = metricsSettings;
     HealthMonitor   = healthMonitor;
     Log             = log;
     EnvProvider     = envProvider;
     AppInfo         = appInfo;
 }
Ejemplo n.º 17
0
 public Application(ILog logger, Settings settings,
                    CurrentApplicationInfo applicationInfo,
                    IAccountMarginEventsReportsRepository accountMarginEventsReportsRepository,
                    ISlackNotificationsSender slackNotificationsSender)
     : base(logger, slackNotificationsSender, applicationInfo)
 {
     _settings = settings;
     _accountMarginEventsReportsRepository = accountMarginEventsReportsRepository;
 }
Ejemplo n.º 18
0
 public Application(IMarginTradingAccountHistoryRepository accountHistoryRepository, ILog logger,
                    Settings settings, CurrentApplicationInfo applicationInfo,
                    IAccountTransactionsReportsRepository accountTransactionsReportsRepository,
                    ISlackNotificationsSender slackNotificationsSender)
     : base(logger, slackNotificationsSender, applicationInfo)
 {
     _accountHistoryRepository = accountHistoryRepository;
     _settings = settings;
     _accountTransactionsReportsRepository = accountTransactionsReportsRepository;
 }
Ejemplo n.º 19
0
 public Application(IExternalOrderReportRepository externalOrderReportRepository,
                    ILog logger,
                    Settings.AppSettings appSettings,
                    CurrentApplicationInfo applicationInfo,
                    ISlackNotificationsSender slackNotificationsSender)
     : base(logger, slackNotificationsSender, applicationInfo)
 {
     _externalOrderReportRepository = externalOrderReportRepository;
     _appSettings = appSettings;
 }
Ejemplo n.º 20
0
 public StackTraceEnhancer(
     Func <StackTraceEnhancerSettings> getConfig,
     IEnvironment environment,
     CurrentApplicationInfo appInfo,
     IJsonExceptionSerializationSettings jsonExceptionSerializationSettings)
 {
     _jsonExceptionSerializationSettings = jsonExceptionSerializationSettings;
     AppInfo     = appInfo;
     GetConfig   = getConfig;
     Environment = environment;
 }
Ejemplo n.º 21
0
 protected AccountStatReportsApplication(ILog logger,
                                         Settings settings, CurrentApplicationInfo applicationInfo,
                                         IAccountsStatsReportsRepository accountsStatsReportsRepository,
                                         IMarginTradingAccountStatsRepository statsRepository,
                                         ISlackNotificationsSender slackNotificationsSender)
     : base(logger, slackNotificationsSender, applicationInfo)
 {
     _settings = settings;
     _accountsStatsReportsRepository = accountsStatsReportsRepository;
     _statsRepository = statsRepository;
 }
Ejemplo n.º 22
0
 public EventSerializer(Func <EventConfiguration> loggingConfigFactory,
                        IEnvironment environment, IStackTraceEnhancer stackTraceEnhancer,
                        Func <EventConfiguration> eventConfig,
                        CurrentApplicationInfo appInfo)
 {
     LoggingConfigFactory = loggingConfigFactory;
     Environment          = environment;
     StackTraceEnhancer   = stackTraceEnhancer;
     EventConfig          = eventConfig;
     AppInfo = appInfo;
 }
Ejemplo n.º 23
0
        public void SetUp()
        {
            CurrentApplicationInfo.Init("CalculatorService.Client");

            _testingKernel = new StandardKernel();
            _testingKernel.Bind <ConfigCreatorObject>().ToSelf().InTransientScope();
            _testingKernel.Bind <ConfigCreatorFuncObject>().ToSelf().InTransientScope();
            _testingKernel.Load <MicrodotModule>();
            _testingKernel.Load <NLogModule>();
            _testingKernel.Get <Ninject.SystemInitializer.SystemInitializer>().Init();
        }
Ejemplo n.º 24
0
 public Application(
     IExecutionOrderBookRepository executionOrderBookRepository,
     ILog logger,
     Settings settings,
     CurrentApplicationInfo applicationInfo,
     ISlackNotificationsSender slackNotificationsSender)
     : base(logger, slackNotificationsSender, applicationInfo, MessageFormat.MessagePack)
 {
     _executionOrderBookRepository = executionOrderBookRepository;
     _log      = logger;
     _settings = settings;
 }
Ejemplo n.º 25
0
 public Application(
     RabbitMqCorrelationManager correlationManager,
     ILoggerFactory loggerFactory,
     ILog logger,
     Settings settings,
     CurrentApplicationInfo applicationInfo,
     IAccountMarginEventsRepository accountMarginEventsRepository,
     ISlackNotificationsSender slackNotificationsSender)
     : base(correlationManager, loggerFactory, logger, slackNotificationsSender, applicationInfo)
 {
     _settings = settings;
     _accountMarginEventsRepository = accountMarginEventsRepository;
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Performs discovery of services in the silo and populates the class' static members with information about them.
        /// </summary>
        public ClusterIdentity(ILog log, IEnvironment environment, CurrentApplicationInfo appInfo)
        {
            string dc  = environment.Zone;
            string env = environment.DeploymentEnvironment;

            var serviceIdSourceString = string.Join("_", dc, env, appInfo.Name, environment.InstanceName);

            ServiceId = Guid.Parse(serviceIdSourceString.GetHashCode().ToString("X32"));

            DeploymentId = serviceIdSourceString + "_" + appInfo.Version;

            log.Info(_ => _("Orleans Cluster Identity Information (see tags)", unencryptedTags: new { OrleansDeploymentId = DeploymentId, OrleansServiceId = ServiceId, serviceIdSourceString }));
        }
 public Application(
     ISystemClock systemClock,
     ILog logger,
     Settings settings,
     CurrentApplicationInfo applicationInfo,
     ISlackNotificationsSender slackNotificationsSender,
     IConnectionMultiplexer redis)
     : base(logger, slackNotificationsSender, applicationInfo, MessageFormat.MessagePack)
 {
     _systemClock = systemClock;
     _log         = logger;
     _settings    = settings;
     _redis       = redis;
 }
 public Application(
     IDatabase redisDatabase,
     ISystemClock systemClock,
     ILog logger,
     Settings settings,
     CurrentApplicationInfo applicationInfo,
     ISlackNotificationsSender slackNotificationsSender)
     : base(logger, slackNotificationsSender, applicationInfo, MessageFormat.MessagePack)
 {
     _redisDatabase = redisDatabase;
     _systemClock   = systemClock;
     _log           = logger;
     _settings      = settings;
 }
Ejemplo n.º 29
0
 public ConfigurationResponseBuilder(ConfigCache configCache,
                                     IEnvironment envs,
                                     IAssemblyProvider assemblyProvider,
                                     UsageTracking usageTracking,
                                     ServiceArguments serviceArguments,
                                     CurrentApplicationInfo appInfo)
 {
     UsageTracking    = usageTracking;
     ServiceArguments = serviceArguments;
     AppInfo          = appInfo;
     ConfigCache      = configCache;
     Envs             = envs;
     AssemblyProvider = assemblyProvider;
 }
Ejemplo n.º 30
0
        public HttpServiceListener(IActivator activator, IWorker worker, IServiceEndPointDefinition serviceEndPointDefinition,
                                   ICertificateLocator certificateLocator, ILog log,
                                   IEnumerable <ICustomEndpoint> customEndpoints, IEnvironment environment,
                                   JsonExceptionSerializer exceptionSerializer,
                                   ServiceSchema serviceSchema,
                                   Func <LoadShedding> loadSheddingConfig,
                                   IServerRequestPublisher serverRequestPublisher,
                                   CurrentApplicationInfo appInfo
                                   )
        {
            ServiceSchema           = serviceSchema;
            _serverRequestPublisher = serverRequestPublisher;

            ServiceEndPointDefinition = serviceEndPointDefinition;
            Worker              = worker;
            Activator           = activator;
            Log                 = log;
            CustomEndpoints     = customEndpoints.ToArray();
            Environment         = environment;
            ExceptionSerializer = exceptionSerializer;
            LoadSheddingConfig  = loadSheddingConfig;
            AppInfo             = appInfo;

            if (serviceEndPointDefinition.UseSecureChannel)
            {
                ServerRootCertHash = certificateLocator.GetCertificate("Service").GetHashOfRootCertificate();
            }

            var urlPrefixTemplate = ServiceEndPointDefinition.UseSecureChannel ? "https://+:{0}/" : "http://+:{0}/";

            Prefix = string.Format(urlPrefixTemplate, ServiceEndPointDefinition.HttpPort);

            Listener = new HttpListener
            {
                IgnoreWriteExceptions = true,
                Prefixes = { Prefix }
            };

            var context = Metric.Context("Service").Context(AppInfo.Name);

            _serializationTime          = context.Timer("Serialization", Unit.Calls);
            _deserializationTime        = context.Timer("Deserialization", Unit.Calls);
            _roundtripTime              = context.Timer("Roundtrip", Unit.Calls);
            _metaEndpointsRoundtripTime = context.Timer("MetaRoundtrip", Unit.Calls);
            _successCounter             = context.Counter("Success", Unit.Calls);
            _failureCounter             = context.Counter("Failed", Unit.Calls);
            _activeRequestsCounter      = context.Timer("ActiveRequests", Unit.Requests);
            _endpointContext            = context.Context("Endpoints");
        }