public EpoxyTransport(
            ILayerStackProvider layerStackProvider,
            Func <string, Task <IPAddress> > resolver,
            EpoxyServerTlsConfig serverTlsConfig,
            EpoxyClientTlsConfig clientTlsConfig,
            TimeoutConfig timeoutConfig,
            ILogSink logSink, bool enableDebugLogs,
            IMetricsSink metricsSink)
        {
            // Layer stack provider may be null
            this.layerStackProvider = layerStackProvider;

            // Always need a resolver, so substitute in default if given null
            this.resolver = resolver ?? ResolveViaDnsAsync;

            // may be null - indicates no TLS for listeners
            this.serverTlsConfig = serverTlsConfig;

            // Client-side TLS is determined by how the connection is
            // established, so we substitute in the Default TLS config if we
            // happened to get null
            this.clientTlsConfig = clientTlsConfig ?? EpoxyClientTlsConfig.Default;

            this.timeoutConfig = timeoutConfig;

            // Log sink may be null
            logger = new Logger(logSink, enableDebugLogs);
            // Metrics sink may be null
            metrics = new Metrics(metricsSink);

            connections = new CleanupCollection <EpoxyConnection>();
            listeners   = new CleanupCollection <EpoxyListener>();
        }
Exemplo n.º 2
0
        public void Deserialization_ValidData_CreatesValidInstance()
        {
            TimeoutConfig config = JsonConvert.DeserializeObject <TimeoutConfig>(
                "{ time : 2.2, cancelDelegates : false }");

            Assert.IsNotNull(config);
            Assert.AreEqual(2.2d, config.TimeoutInSeconds, 0.0001d);
            Assert.IsFalse(config.CancelDelegates);
        }
Exemplo n.º 3
0
        public void AsPolicy_LoggerNull_Throws()
        {
            var config = new TimeoutConfig
            {
                TimeoutInSeconds = 1.0d,
                CancelDelegates  = true
            };

            Assert.ThrowsException <ArgumentNullException>(
                () => config.AsTypeModel(null));
        }
Exemplo n.º 4
0
        public void AsPolicy_TimeoutInSecondsMaxValue_Throws()
        {
            var logger = new Mock <ILogger>(MockBehavior.Loose);
            var config = new TimeoutConfig
            {
                TimeoutInSeconds = double.MaxValue,
                CancelDelegates  = false
            };

            Assert.ThrowsException <InvalidOperationException>(
                () => config.AsTypeModel(logger.Object));
        }
Exemplo n.º 5
0
        public void AsPolicy_NegativeTimeoutInSeconds_Throws()
        {
            var logger = new Mock <ILogger>(MockBehavior.Loose);
            var config = new TimeoutConfig
            {
                TimeoutInSeconds = -1.0d,
                CancelDelegates  = true
            };

            Assert.ThrowsException <InvalidOperationException>(
                () => config.AsTypeModel(logger.Object));
        }
Exemplo n.º 6
0
        public void TestCachedJsonData()
        {
            Stopwatch sw = Stopwatch.StartNew();
            var       apiTimeoutValue = TimeoutConfig.GetSpecificApiReadTimeoutValue(_product, _version, _actionName);
            var       executeTime1    = sw.ElapsedMilliseconds;

            Assert.Equal(86000, apiTimeoutValue);

            sw.Restart();
            apiTimeoutValue = TimeoutConfig.GetSpecificApiReadTimeoutValue(_product, _version, "AllocateEipAddress");
            var executeTime2 = sw.ElapsedMilliseconds;

            Assert.Equal(17000, apiTimeoutValue);
        }
Exemplo n.º 7
0
        public void AsPolicy_TimeoutInSecondsValid_CancelDelegates_ReturnsPolicy()
        {
            var logger = new Mock <ILogger>(MockBehavior.Loose);
            var config = new TimeoutConfig
            {
                TimeoutInSeconds = 5.0d,
                CancelDelegates  = true
            };

            IAsyncPolicy <HttpResponseMessage> policy = config.AsTypeModel(logger.Object);

            Assert.IsNotNull(policy);
            Assert.IsInstanceOfType(policy, typeof(AsyncTimeoutPolicy <HttpResponseMessage>));
        }
Exemplo n.º 8
0
        internal static void ConfigureSocketKeepAlive(Socket socket, TimeoutConfig timeoutConfig, Logger logger)
        {
            if (timeoutConfig.KeepAliveTime != TimeSpan.Zero && timeoutConfig.KeepAliveInterval != TimeSpan.Zero)
            {
                // Socket.IOControl for IOControlCode.KeepAliveValues is expecting a structure like
                // the following on Windows:
                //
                // struct tcp_keepalive
                // {
                //     u_long onoff; // 0 for off, non-zero for on
                //     u_long keepalivetime; // milliseconds
                //     u_long keepaliveinterval; // milliseconds
                // };
                //
                // On some platforms this gets mapped to the relevant OS structures, but on other
                // platforms, this may fail with a PlatformNotSupportedException.
                UInt32 keepAliveTimeMillis     = checked ((UInt32)timeoutConfig.KeepAliveTime.TotalMilliseconds);
                UInt32 keepAliveIntervalMillis = checked ((UInt32)timeoutConfig.KeepAliveInterval.TotalMilliseconds);

                var keepAliveVals = new byte[sizeof(UInt32) * 3];
                keepAliveVals[0] = 1;

                keepAliveVals[4] = (byte)(keepAliveTimeMillis & 0xff);
                keepAliveVals[5] = (byte)((keepAliveTimeMillis >> 8) & 0xff);
                keepAliveVals[6] = (byte)((keepAliveTimeMillis >> 16) & 0xff);
                keepAliveVals[7] = (byte)((keepAliveTimeMillis >> 24) & 0xff);

                keepAliveVals[8]  = (byte)(keepAliveIntervalMillis & 0xff);
                keepAliveVals[9]  = (byte)((keepAliveIntervalMillis >> 8) & 0xff);
                keepAliveVals[10] = (byte)((keepAliveIntervalMillis >> 16) & 0xff);
                keepAliveVals[11] = (byte)((keepAliveIntervalMillis >> 24) & 0xff);

                try
                {
                    socket.IOControl(IOControlCode.KeepAliveValues, keepAliveVals, null);
                }
                catch (ObjectDisposedException)
                {
                    // Oh well: the connection went down before we could configure it. Nothing to be
                    // done, except to wait for the next socket operation to fail and let normal
                    // clean up take over.
                }
                catch (Exception ex) when(ex is SocketException || ex is PlatformNotSupportedException)
                {
                    logger.Site().Warning(ex, "Socket keep-alive could not be configured");
                }
            }
        }
        private void ResolveTimeout(HttpRequest request, string product, string version, string actionName)
        {
            var apiReadTimeout = TimeoutConfig.GetSpecificApiReadTimeoutValue(product, version, actionName);

            int finalReadTimeout;

            if (request.ReadTimeout > 0)
            {
                finalReadTimeout = request.ReadTimeout;
            }
            else if (ReadTimeout > 0)
            {
                finalReadTimeout = ReadTimeout;
            }
            else if (apiReadTimeout > 0)
            {
                finalReadTimeout = apiReadTimeout;
            }
            else
            {
                finalReadTimeout = 0;
            }

            request.SetReadTimeoutInMilliSeconds(finalReadTimeout);

            int finalConnectTimeout;

            if (request.ConnectTimeout > 0)
            {
                finalConnectTimeout = request.ConnectTimeout;
            }
            else if (ConnectTimeout > 0)
            {
                finalConnectTimeout = ConnectTimeout;
            }
            else
            {
                finalConnectTimeout = 0;
            }

            request.SetConnectTimeoutInMilliSeconds(finalConnectTimeout);
        }
Exemplo n.º 10
0
        public void TestJsonDataNull()
        {
            var apiTimeoutValue = TimeoutConfig.GetSpecificApiReadTimeoutValue(_product, _version, "error-actionName");

            Assert.Equal(0, apiTimeoutValue);
        }
Exemplo n.º 11
0
        public void TestParameterNull()
        {
            var apiTimeoutValue = TimeoutConfig.GetSpecificApiReadTimeoutValue(_product, _version, null);

            Assert.Equal(0, apiTimeoutValue);
        }
Exemplo n.º 12
0
        public void TestApiTimeoutValue()
        {
            var timeoutValue = TimeoutConfig.GetSpecificApiReadTimeoutValue(_product, _version, _actionName);

            Assert.Equal(86000, timeoutValue);
        }
Exemplo n.º 13
0
        public void ConfigureServices(IServiceCollection services)
        {
            var db       = new DatabaseConfig();
            var mqtt     = new MqttConfig();
            var timeouts = new TimeoutConfig();
            var mail     = new MailConfig();
            var text     = new TextConfig();

            this.Configuration.GetSection("Mail").Bind(mail);
            this.Configuration.GetSection("Database").Bind(db);
            this.Configuration.GetSection("Mqtt").Bind(mqtt);
            this.Configuration.GetSection("Timeouts").Bind(timeouts);
            this.Configuration.GetSection("Text").Bind(text);

            var privatemqtt = mqtt.InternalBroker;

            services.AddConnectionStrings(db.Networking.ConnectionString, db.SensateIoT.ConnectionString);
            services.AddAuthorizationContext();
            services.AddNetworkingContext();
            services.AddDocumentStore(db.MongoDB.ConnectionString, db.MongoDB.DatabaseName, db.MongoDB.MaxConnections);
            services.Configure <TimeoutConfig>(this.Configuration.GetSection("Timeouts"));

            services.Configure <MqttConfig>(this.Configuration.GetSection("Mqtt"));
            services.Configure <MetricsOptions>(this.Configuration.GetSection("HttpServer:Metrics"));
            services.AddHostedService <MetricsService>();

            services.AddInternalMqttService(options => {
                options.Ssl        = privatemqtt.Ssl;
                options.Host       = privatemqtt.Host;
                options.Port       = privatemqtt.Port;
                options.Username   = privatemqtt.Username;
                options.Password   = privatemqtt.Password;
                options.Id         = Guid.NewGuid().ToString();
                options.TopicShare = "$share/triggers/";
            });

            services.Configure <RouterSettings>(s => {
                s.Host   = this.Configuration.GetValue <string>("Router:Host");
                s.Port   = this.Configuration.GetValue <ushort>("Router:Port");
                s.Secure = this.Configuration.GetValue <bool>("Router:Secure");
            });

            if (mail.Provider == "SendGrid")
            {
                services.AddSingleton <IEmailSender, SendGridMailer>();
                services.Configure <SendGridAuthOptions>(opts => {
                    opts.FromName = mail.FromName;
                    opts.From     = mail.From;
                    opts.Key      = mail.SendGrid.Key;
                    opts.Username = mail.SendGrid.Username;
                });
            }
            else if (mail.Provider == "SMTP")
            {
                services.AddSingleton <IEmailSender, SmtpMailer>();
                services.Configure <SmtpAuthOptions>(opts => {
                    opts.FromName = mail.FromName;
                    opts.From     = mail.From;
                    opts.Password = mail.Smtp.Password;
                    opts.Username = mail.Smtp.Username;
                    opts.Ssl      = mail.Smtp.Ssl;
                    opts.Port     = mail.Smtp.Port;
                    opts.Host     = mail.Smtp.Host;
                });
            }

            if (text.Provider == "Twillio")
            {
                TwilioClient.Init(text.Twilio.AccountSid, text.Twilio.AuthToken);

                var incoming = IncomingPhoneNumberResource.Fetch(pathSid: text.Twilio.PhoneSid);
                services.Configure <TextServiceSettings>(options => {
                    options.AlphaCode   = text.AlphaCode;
                    options.PhoneNumber = incoming.PhoneNumber.ToString();
                });

                services.AddScoped <ITextSendService, TwillioTextSendService>();
            }
            else
            {
                throw new InvalidOperationException("Text provider not configured!");
            }

            services.AddScoped <IControlMessageRepository, ControlMessageRepository>();
            services.AddScoped <ITriggerRepository, TriggerRepository>();
            services.AddScoped <IControlMessageRepository, ControlMessageRepository>();
            services.AddScoped <ITriggerActionExecutionService, TriggerActionExecutionService>();

            services.AddSingleton <IDataPointMatchingService, DataPointMatchingService>();
            services.AddSingleton <IRegexMatchingService, RegexMatchingService>();
            services.AddSingleton <IRouterClient, RouterClient>();
            services.AddSingleton <IEmailSender, SmtpMailer>();
            services.AddSingleton <ITriggerActionCache, TriggerActionCache>();

            services.AddHostedService <TriggerActionReloadService>();

            services.AddHttpClient();
            services.AddMqttHandlers();
        }
 public DataPointMatchingService(IOptions <TimeoutConfig> settings)
 {
     this.m_timeouts = settings.Value;
 }