コード例 #1
0
        private async Task RunAsync(Parameters parameters)
        {
            var secrets = SecretConfiguration.Load(parameters.SecretSource);
            var channel = await Channels.CreateSendChannel(parameters.ClusterId, secrets);

            _logger.LogInformation($"Waiting {parameters.Wait} seconds before starting...");
            await Task.Delay(TimeSpan.FromSeconds(parameters.Wait));

            for (var i = 0; i < parameters.Rounds; i++)
            {
                _logger.LogInformation($"Round #{i + 1}: sending {parameters.ServersPerRound} orders [Restart: {parameters.Restart}, Graceful: {parameters.Graceful}]");
                var responses = await channel.SendMessages(
                    GetMessages(),
                    new CancellationTokenSource(TimeSpan.FromSeconds(parameters.RoundDelay)).Token);

                _logger.LogInformation($"Round #{i + 1}: silos {string.Join(",", responses.Select(r => r.ServerName))} acked");
                _logger.LogInformation($"Round #{i + 1}: waiting {parameters.RoundDelay}");
                await Task.Delay(TimeSpan.FromSeconds(parameters.RoundDelay));
            }

            List <ServerMessage> GetMessages()
            {
                var msgs = new List <ServerMessage>();

                for (var i = 0; i < parameters.ServersPerRound; i++)
                {
                    msgs.Add(new ServerMessage(parameters.Graceful, parameters.Restart));
                }
                return(msgs);
            }
        }
コード例 #2
0
        public static async Task <ISendChannel> CreateSendChannel(string clusterId, SecretConfiguration configuration)
        {
            var writeQueue = new QueueClient(configuration.ClusteringConnectionString, string.Format(CLIENT_TO_SERVER_QUEUE, clusterId));
            var readQueue  = new QueueClient(configuration.ClusteringConnectionString, string.Format(SILO_TO_CLIENT_QUEUE, clusterId));

            await writeQueue.CreateIfNotExistsAsync();

            await readQueue.CreateIfNotExistsAsync();

            return(new SendChannel(writeQueue, readQueue));
        }
コード例 #3
0
        public async Task <string> SaveConfigurationAsync(SecretConfiguration config, CancellationToken token)
        {
            if (null == config)
            {
                throw new ArgumentNullException(nameof(config));
            }
            if (null == config.Policy)
            {
                throw new ArgumentNullException(nameof(config.Policy));
            }

            return(await OnSaveConfigurationAsync(config, token));
        }
        protected async override Task <string> OnSaveConfigurationAsync(SecretConfiguration config, CancellationToken token)
        {
            Contracts.Config sc = Contracts.Config.FromSecretConfiguration(config);

            if (Guid.Empty == sc.ConfigurationId)
            {
                sc.ConfigurationId = Guid.NewGuid();
            }

            await SaveObjectAsync(_rootContainer, FormatFileName(StorageFolders.Config, sc.ConfigurationId.ToString()), GetObjectJson <Contracts.Config>(sc), token);

            return(sc.ConfigurationId.ToString());
        }
コード例 #5
0
        public async Task Run(ClientParameters clientParams, LoadGeneratorParameters loadParams)
        {
            var secrets     = SecretConfiguration.Load(clientParams.SecretSource);
            var hostBuilder = new HostBuilder().UseOrleansClient((ctx, builder) =>
                                                                 builder.Configure <ClusterOptions>(options => { options.ClusterId = clientParams.ClusterId; options.ServiceId = clientParams.ServiceId; })
                                                                 .Configure <ConnectionOptions>(options => clientParams.ConnectionsPerEndpoint = 2)
                                                                 .UseAzureStorageClustering(options => options.ConfigureTableServiceClient(secrets.ClusteringConnectionString)));

            using var host = hostBuilder.Build();

            _logger.LogInformation("Connecting to cluster...");
            await host.StartAsync();

            var client = host.Services.GetService <IClusterClient>();

            var generator = new ConcurrentLoadGenerator <T>(
                numWorkers: loadParams.NumWorkers,
                blocksPerWorker: loadParams.BlocksPerWorker != 0 ? loadParams.BlocksPerWorker : int.MaxValue,
                requestsPerBlock: loadParams.RequestsPerBlock,
                issueRequest: _scenario.IssueRequest,
                getStateForWorker: workerId => _scenario.GetStateForWorker(client, workerId),
                logger: _logger,
                logIntermediateResults: true);

            _logger.LogInformation("Warming-up...");
            await generator.Warmup();

            var cts = loadParams.Duration != 0
                ? new CancellationTokenSource(TimeSpan.FromSeconds(loadParams.Duration))
                : new CancellationTokenSource();

            _logger.LogInformation("Running");
            var report = await generator.Run(cts.Token);

            // Register the measurements. n0 -> format as natural number
            BenchmarksEventSource.Register("requests", Operations.First, Operations.Sum, "Requests", "Number of requests completed", "n0");
            BenchmarksEventSource.Register("failures", Operations.First, Operations.Sum, "Failures", "Number of failures", "n0");
            BenchmarksEventSource.Register("rps", Operations.First, Operations.Sum, "Rate per second", "Rate per seconds", "n0");

            // Register the measurement values
            BenchmarksEventSource.Measure("requests", report.Completed);
            BenchmarksEventSource.Measure("failures", report.Failures);
            BenchmarksEventSource.Measure("rps", report.RatePerSecond);

            await host.StopAsync();
        }
コード例 #6
0
        private async Task RunAsync(Parameters parameters)
        {
            _logger.LogInformation("Connecting to cluster...");
            var secrets     = SecretConfiguration.Load(parameters.SecretSource);
            var hostBuilder = new HostBuilder()
                              .UseOrleansClient(builder => {
                builder
                .Configure <ClusterOptions>(options => { options.ClusterId = parameters.ClusterId; options.ServiceId = parameters.ServiceId; })
                .UseAzureStorageClustering(options => options.ConfigureTableServiceClient(secrets.ClusteringConnectionString));
            });

            using var host = hostBuilder.Build();
            await host.StartAsync();

            var client = host.Services.GetService <IClusterClient>();

            var counterGrain = client.GetGrain <ICounterGrain>(parameters.CounterKey);

            var duration = await counterGrain.GetRunDuration();

            BenchmarksEventSource.Register("duration", Operations.First, Operations.Last, "duration", "duration", "n0");
            BenchmarksEventSource.Measure("duration", duration.TotalSeconds);

            var initialWait = await counterGrain.WaitTimeForReport();

            _logger.LogInformation($"Counters should be ready in {initialWait}");
            await Task.Delay(initialWait);

            _logger.LogInformation($"Counters ready");
            foreach (var counter in parameters.Counters)
            {
                var value = await counterGrain.GetTotalCounterValue(counter);

                _logger.LogInformation($"{counter}: {value}");
                BenchmarksEventSource.Register(counter, Operations.First, Operations.Sum, counter, counter, "n0");
                BenchmarksEventSource.Measure(counter, value);
                if (string.Equals(counter, "requests", StringComparison.InvariantCultureIgnoreCase))
                {
                    var rps = (float)value / duration.TotalSeconds;
                    BenchmarksEventSource.Register("rps", Operations.First, Operations.Last, "rps", "Requests per second", "n0");
                    BenchmarksEventSource.Measure("rps", rps);
                }
            }

            await host.StopAsync();
        }
コード例 #7
0
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your email service here to send an email.
            SmtpClient client = new SmtpClient("in-v3.mailjet.com");

            client.Port      = 587;
            client.EnableSsl = true;

            //If you need to authenticate
            client.Credentials = new NetworkCredential(SecretConfiguration.Get("mailjet:appid"), SecretConfiguration.Get("mailjet:appsecret"));

            MailMessage messagetosend = new MailMessage("*****@*****.**", message.Destination, message.Subject, message.Body);

            messagetosend.IsBodyHtml = true;
            //return Task.Delay(1500);

            return(client.SendMailAsync(messagetosend));
        }
コード例 #8
0
        public async Task <DirectionObject> GetDirections(string userAdress, string eventAddress, string unit, DirectionModes md1)
        {
            string apkey = SecretConfiguration.Get("google.direction.api");

            HttpClient httpcli = new HttpClient();
            var        start   = truncateaddress(userAdress);
            var        end     = truncateaddress(eventAddress);
            var        request =
                $@"https://maps.googleapis.com/maps/api/directions/json?origin=" + start + "&destination=" + end + $"&mode={md1}&units={unit}&key={apkey}";

            var result = await httpcli.GetStringAsync(request);

            var objResult = JsonConvert.DeserializeObject <DirectionObject>(result);



            return(objResult);
        }
コード例 #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime, IOptions <SecretConfiguration> settings)
        {
            loggerFactory.AddSerilog();
            Log.Logger.Information("Configuring http request pipeline: {environment}", new { EnvironmentName = env.EnvironmentName, ApplicationName = env.ApplicationName });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("default");

            SecretConfiguration secretConfiguration = settings.Value;

            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                Audience  = secretConfiguration.Audience,
                Authority = $"https://{secretConfiguration.ClientDomain}/",
            });

            app.UseMiddleware <HttpErrorHandleMiddleware>();
            app.UseMvc();

            app.UseSwagger(swaggerOptions =>
            {
                swaggerOptions.RouteTemplate = "docs/swagger/{documentName}/swagger.json";
            });

            app.UseSwaggerUI(swaggerUiOptions =>
            {
                swaggerUiOptions.RoutePrefix = "docs";
                swaggerUiOptions.SwaggerEndpoint("swagger/v1/swagger.json", "Canonn API v1");
                swaggerUiOptions.ConfigureOAuth2(secretConfiguration.ClientId, secretConfiguration.ClientSecret,
                                                 secretConfiguration.ClientDomain, "Canonn API",
                                                 additionalQueryStringParameters: new { audience = secretConfiguration.Audience });
            });

            // Ensure any buffered events are sent at shutdown
            appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);
            // Ensure container and dependencies are cleaned up accordingly
            appLifetime.ApplicationStopped.Register(ApplicationContainer.Dispose);
        }
        protected async override Task <SecretConfiguration> OnGetSecretConfigurationAsync(string configId, CancellationToken token)
        {
            string json = await GetObjectAsync(_rootContainer, FormatFileName(StorageFolders.Config, configId), token);

            if (string.IsNullOrWhiteSpace(json))
            {
                return(null);
            }

            var cfg = Newtonsoft.Json.JsonConvert.DeserializeObject <Contracts.Config>(json);

            SecretConfiguration result = null;

            if (null != cfg)
            {
                result = cfg.ToSecretConfiguration();
                if (result.Policy.PolicyId != Guid.Empty)
                {
                    result.Policy = await GetPolicyAsync(result.Policy.PolicyId.ToString(), token);
                }
            }

            return(result);
        }
コード例 #11
0
 public void TestDurationRoutesApi()
 {
     //string startAdress = "14 rue godefroy 69006 Lyon";
     string     startAdress = "69006 Lyon";
     string     endAddress  = "La triche 69001 Lyon";
     var        ulrRequest  = $@"https://maps.googleapis.com/maps/api/directions/json?origin={startAdress.Replace(" ", "+")}&destination={endAddress.Replace(" ", "+")}&mode=driving&units=metric&key={SecretConfiguration.Get("google.direction.api")}";
     HttpClient httpcli     = new HttpClient();
     var        result      = httpcli.GetStringAsync(ulrRequest).Result;
     var        objResult   = JsonConvert.DeserializeObject <DirectionObject>(result);
 }
コード例 #12
0
        public void TestMethod1()
        {
            var result = SecretConfiguration.Get("fake:apclient");

            Assert.AreEqual("668478945646", result);
        }
コード例 #13
0
 protected abstract Task <string> OnSaveConfigurationAsync(SecretConfiguration config, CancellationToken token);
コード例 #14
0
 public CheckController(IOptions <SecretConfiguration> options, IRepository repo)
 {
     _keys = options.Value;
     _repo = repo;
 }
コード例 #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientConfigurationController"/>
 /// </summary>
 /// <param name="settings">The configuration settings to provide</param>
 public ClientConfigurationController(IOptions <SecretConfiguration> settings)
 {
     _settings = settings?.Value ?? throw new ArgumentNullException(nameof(settings));
 }