コード例 #1
0
ファイル: Program.cs プロジェクト: elastic/apm-agent-dotnet
        /// <summary>
        /// Create a client that connects to cloud, uses dotnet user-secrets.
        /// </summary>
        private static ElasticClient CreateCloudClient()
        {
            var userSecrets    = new ConfigurationBuilder().AddUserSecrets <Program>().Build();
            var basicAuth      = new BasicAuthenticationCredentials(userSecrets["cloud:user"], userSecrets["cloud:password"]);
            var connectionPool = new CloudConnectionPool(userSecrets["cloud:id"], basicAuth);
            var settings       = DefaultConnectionSettings(new ConnectionSettings(connectionPool));

            return(new ElasticClient(settings));
        }
コード例 #2
0
ファイル: Elastic.cs プロジェクト: driis/VerticaXmas
    public static async Task <SantaPath> GetMovements(Guid id)
    {
        var connPool = new CloudConnectionPool(
            "xmas2019:ZXUtY2VudHJhbC0xLmF3cy5jbG91ZC5lcy5pbyRlZWJjNmYyNzcxM2Q0NTE5OTcwZDc1Yzg2MDUwZTM2MyQyNDFmMzQ3OWNkNzg0ZTUyOTRkODk5OTViMjg0MjAyYg==",
            new BasicAuthenticationCredentials("Participant", "fr5ZS6NT2gQE1VL0hLZmB1X8HhGAW4"));
        var cli = new ElasticClient(new ConnectionSettings(connPool, JsonNetSerializer.Default));

        var response =
            await cli.GetAsync <SantaPath>(new GetRequest("santa-trackings", id.ToString()), CancellationToken.None);

        return(response.Source);
    }
コード例 #3
0
        private static ConnectionSettings GetCloudBasedConnectionSettings(ElasticClientConfiguration configuration)
        {
            if (string.IsNullOrEmpty(configuration.CloudId) ||
                string.IsNullOrWhiteSpace(configuration.Username) ||
                string.IsNullOrWhiteSpace(configuration.Password))
            {
                throw new Exception("The cloudid, username and password is required in the search configuration.");
            }

            var credentials    = new BasicAuthenticationCredentials(configuration.Username, configuration.Password);
            var connectionPool = new CloudConnectionPool(configuration.CloudId, credentials);

            return(new ConnectionSettings(connectionPool));
        }
コード例 #4
0
        public SearchClient(string userName, string password, string cloudId)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException(nameof(userName));
            }
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException(nameof(password));
            }

            var credentials = new BasicAuthenticationCredentials(userName, password);
            var pool        = new CloudConnectionPool(cloudId, credentials);

            _client = new ElasticClient(new ConnectionSettings(pool));
        }
コード例 #5
0
        public Startup(IConfiguration configuration)
        {
            // Create Serilog Elasticsearch logger
            var credentials = new BasicAuthenticationCredentials("elastic", "qzKU7qkbpjEJMyzN5gBOIyl0");
            var pool        = new CloudConnectionPool("test:dXMtY2VudHJhbDEuZ2NwLmNsb3VkLmVzLmlvJDljNWJkOGNhNWYzZjQ5YjBhOGRkMDRlYTVlYzc0OWRiJDM3NmUxNzlmZWM0NDQyNWQ4N2RlYjBkZGEzODhlNGMz", credentials);

            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .Enrich.WithExceptionDetails()
                         .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(
                                                    new Uri("http://192.168.99.100:9200"))
            {
                AutoRegisterTemplate = true,
            })
                         .CreateLogger();


            Configuration = configuration;
        }
コード例 #6
0
        public static void AddElasticsearch(this IServiceCollection services, IConfiguration configuration)
        {
            var url          = configuration["elasticsearch:url"];
            var defaultIndex = configuration["elasticsearch:index"];
            var userName     = configuration["elasticsearch:user"];
            var password     = configuration["elasticsearch:password"];
            var cloudId      = configuration["elasticsearch:cloudId"];

            var credentials = new BasicAuthenticationCredentials(userName, password);
            var pool        = new CloudConnectionPool(cloudId, credentials);

            var settings = new ConnectionSettings(pool)
                           .DefaultIndex(defaultIndex)
                           .EnableDebugMode();


            var client = new ElasticClient(settings);

            services.AddSingleton <IElasticClient>(client);
        }
コード例 #7
0
        /**
         * [[cloud-connection-pool]]
         * ==== CloudConnectionPool
         *
         * A specialized subclass of `SingleNodeConnectionPool` that accepts a Cloud Id and credentials.
         * When used the client will also pick Elastic Cloud optmized defaults for the connection settings.
         *
         * A Cloud Id for your cluster can be fetched from your Elastic Cloud cluster administration console.
         *
         * A Cloud Id should be in the form of `cluster_name:base_64_data` where `base_64_data` are the UUIDs for the services in this cloud instance e.g
         *
         * `host_name$elasticsearch_uuid$kibana_uuid$apm_uuid`
         *
         * Out of these, only `host_name` and `elasticsearch_uuid` are always available.
         *
         */
        [U] public void CloudConnectionPool()
        {
            // hide
            string ToBase64(string s) => Convert.ToBase64String(Encoding.UTF8.GetBytes(s));

            // hide
            var hostName = "cloud-endpoint.example";
            // hide
            var elasticsearchUuid = "3dadf823f05388497ea684236d918a1a";
            // hide
            var services = $"{hostName}${elasticsearchUuid}$3f26e1609cf54a0f80137a80de560da4";
            // hide
            var cloudId = $"my_cluster:{ToBase64(services)}";

            /**
             * A cloud connection pool can be created using credentials and a `cloudId`
             */
            var credentials = new BasicAuthenticationCredentials("username", "password"); // <1> a username and password that can access Elasticsearch service on Elastic Cloud
            var pool        = new CloudConnectionPool(cloudId, credentials);              // <2> `cloudId` is a value that can be retrieved from the Elastic Cloud web console
            var client      = new ElasticClient(new ConnectionSettings(pool));

            // hide
            {
                pool.UsingSsl.Should().BeTrue();
                pool.Nodes.Should().HaveCount(1);
                var node = pool.Nodes.First();
                node.Uri.Port.Should().Be(443);
                node.Uri.Host.Should().Be($"{elasticsearchUuid}.{hostName}");
                node.Uri.Scheme.Should().Be("https");
            }

            /** This type of pool, like its parent the `SingleNodeConnectionPool`, is hardwired to opt out of
             * reseeding (<<sniffing-behaviour, sniffing>>) as well as <<pinging-behaviour, pinging>>.
             */
            // hide
            {
                pool.SupportsReseeding.Should().BeFalse();
                pool.SupportsPinging.Should().BeFalse();
            }

            /**
             * You can also directly create a cloud enabled connection using the `ElasticClient`'s constructor
             */
            client = new ElasticClient(cloudId, credentials);

            // hide
            {
                client.ConnectionSettings.ConnectionPool
                .Should()
                .BeOfType <CloudConnectionPool>();
            }

            // hide
            {
                client = new ElasticClient(new ConnectionSettings(pool));
                client.ConnectionSettings.ConnectionPool.Should().BeOfType <CloudConnectionPool>();
                client.ConnectionSettings.EnableHttpCompression.Should().BeTrue();
                client.ConnectionSettings.BasicAuthenticationCredentials.Should().NotBeNull();
                client.ConnectionSettings.BasicAuthenticationCredentials.Username.Should().Be("username");
            }

            //hide
            {
                var badCloudIds = new[]
                {
                    "",
                    "my_cluster",
                    "my_cluster:",
                    $"my_cluster:{ToBase64("hostname")}",
                    $"my_cluster:{ToBase64("hostname$")}"
                };

                foreach (var id in badCloudIds)
                {
                    Action create = () => new ElasticClient(id, credentials);

                    create.Should()
                    .Throw <ArgumentException>()
                    .And.Message.Should()
                    .Contain("should be a string in the form of cluster_name:base_64_data");
                }
            }
        }
コード例 #8
0
        /**
         * [[cloud-connection-pool]]
         * ==== CloudConnectionPool
         *
         * A specialized subclass of `SingleNodeConnectionPool that accepts a Cloud Id and credentials.
         * When used the client will also pick Elastic Cloud optmized defaults for the connection settings.
         *
         * A Cloud Id for your cluster can be fetched from your Elastic Cloud cluster administration console.
         *
         * A Cloud Id should be in the form of `cluster_name:base_64_data` where `base_64_data` are the UUIDs for the services in this cloud instance e.g
         *
         * `host_name$elasticsearch_uuid$kibana_uuid$apm_uuid`
         *
         * Out of these, only `host_name` and `elasticsearch_uuid` are always available.
         *
         */
        [U] public void CloudConnectionPool()
        {
            string ToBase64(string s) => Convert.ToBase64String(Encoding.UTF8.GetBytes(s));

            /* Here we obviously use a ficticuous Cloud Id so lets create a fake one. */

            var hostName          = "cloud-endpoint.example";
            var elasticsearchUuid = "3dadf823f05388497ea684236d918a1a";
            var services          = $"{hostName}${elasticsearchUuid}$3f26e1609cf54a0f80137a80de560da4";
            var cloudId           = $"my_cluster:{ToBase64(services)}";

            /*
             * In a real scenario you would be able to copy paste `cloudId`
             *
             * A cloud connection pool always needs credentials as well here opt for basic auth
             */
            var credentials = new BasicAuthenticationCredentials("username", "password");
            var pool        = new CloudConnectionPool(cloudId, credentials);

            pool.UsingSsl.Should().BeTrue();
            pool.Nodes.Should().HaveCount(1);
            var node = pool.Nodes.First();

            node.Uri.Port.Should().Be(443);
            node.Uri.Host.Should().Be($"{elasticsearchUuid}.{hostName}");
            node.Uri.Scheme.Should().Be("https");

            /** This type of pool like its parent the `SingleNodeConnectionPool` is hardwired to opt out of
             * reseeding (thus, sniffing) as well as pinging
             */
            pool.SupportsReseeding.Should().BeFalse();
            pool.SupportsPinging.Should().BeFalse();

            /**
             * You can also directly create a cloud enabled connection using the clients constructor
             */
            var client = new ElasticClient(cloudId, credentials);

            client.ConnectionSettings.ConnectionPool
            .Should()
            .BeOfType <CloudConnectionPool>();

            /** However we urge that you always pass your connection settings explicitly
             */
            client = new ElasticClient(new ConnectionSettings(pool));
            client.ConnectionSettings.ConnectionPool.Should().BeOfType <CloudConnectionPool>();

            client.ConnectionSettings.EnableHttpCompression.Should().BeTrue();
            client.ConnectionSettings.BasicAuthenticationCredentials.Should().NotBeNull();
            client.ConnectionSettings.BasicAuthenticationCredentials.Username.Should().Be("username");

            //hide
            var badCloudIds = new[]
            {
                "",
                "my_cluster",
                "my_cluster:",
                $"my_cluster:{ToBase64("hostname")}",
                $"my_cluster:{ToBase64("hostname$")}"
            };

            foreach (var id in badCloudIds)
            {
                Action create = () => new ElasticClient(id, credentials);

                create.Should().Throw <ArgumentException>()
                .And.Message.Should().Contain("should be a string in the form of cluster_name:base_64_data");
            }
        }