This is an automated email from the ASF dual-hosted git repository.

monkeydluffy pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/apisix.git


The following commit(s) were added to refs/heads/master by this push:
     new 18bf7aeac feat: consul deduplicate and sort (#10941)
18bf7aeac is described below

commit 18bf7aeac45cf50ce1f035c03ab501417315b1e7
Author: xiangwei meng <[email protected]>
AuthorDate: Tue Feb 27 11:25:11 2024 +0800

    feat: consul deduplicate and sort (#10941)
---
 apisix/discovery/consul/init.lua   |  51 ++++++-
 apisix/discovery/consul/schema.lua |   5 +
 ci/pod/docker-compose.first.yml    |  43 ++++++
 docs/en/latest/discovery/consul.md |   8 +
 t/discovery/consul2.t              | 292 +++++++++++++++++++++++++++++++++++++
 5 files changed, 393 insertions(+), 6 deletions(-)

diff --git a/apisix/discovery/consul/init.lua b/apisix/discovery/consul/init.lua
index a1e537a53..a6139993d 100644
--- a/apisix/discovery/consul/init.lua
+++ b/apisix/discovery/consul/init.lua
@@ -45,6 +45,7 @@ local next               = next
 local all_services = core.table.new(0, 5)
 local default_service
 local default_weight
+local sort_type
 local skip_service_map = core.table.new(0, 1)
 local dump_params
 
@@ -339,6 +340,25 @@ local function watch_result_is_valid(watch_type, index, 
catalog_index, health_in
 end
 
 
+local function combine_sort_nodes_cmp(left, right)
+    if left.host ~= right.host then
+        return left.host < right.host
+    end
+
+    return left.port < right.port
+end
+
+
+local function port_sort_nodes_cmp(left, right)
+    return left.port < right.port
+end
+
+
+local function host_sort_nodes_cmp(left, right)
+    return left.host < right.host
+end
+
+
 function _M.connect(premature, consul_server, retry_delay)
     if premature then
         return
@@ -489,6 +509,7 @@ function _M.connect(premature, consul_server, retry_delay)
             if is_not_empty(result.body) then
                 -- add services to table
                 local nodes = up_services[service_name]
+                local nodes_uniq = {}
                 for _, node in ipairs(result.body) do
                     if not node.Service then
                         goto CONTINUE
@@ -500,12 +521,29 @@ function _M.connect(premature, consul_server, retry_delay)
                         nodes = core.table.new(1, 0)
                         up_services[service_name] = nodes
                     end
-                    -- add node to nodes table
-                    core.table.insert(nodes, {
-                        host = svc_address,
-                        port = tonumber(svc_port),
-                        weight = default_weight,
-                    })
+                    -- not store duplicate service IDs.
+                    local service_id = svc_address .. ":" .. svc_port
+                    if not nodes_uniq[service_id] then
+                        -- add node to nodes table
+                        core.table.insert(nodes, {
+                            host = svc_address,
+                            port = tonumber(svc_port),
+                            weight = default_weight,
+                        })
+                        nodes_uniq[service_id] = true
+                    end
+                end
+                if nodes then
+                    if sort_type == "port_sort" then
+                        core.table.sort(nodes, port_sort_nodes_cmp)
+
+                    elseif sort_type == "host_sort" then
+                        core.table.sort(nodes, host_sort_nodes_cmp)
+
+                    elseif sort_type == "combine_sort" then
+                        core.table.sort(nodes, combine_sort_nodes_cmp)
+
+                    end
                 end
                 up_services[service_name] = nodes
             end
@@ -592,6 +630,7 @@ function _M.init_worker()
 
     log.notice("consul_conf: ", json_delay_encode(consul_conf, true))
     default_weight = consul_conf.weight
+    sort_type = consul_conf.sort_type
     -- set default service, used when the server node cannot be found
     if consul_conf.default_service then
         default_service = consul_conf.default_service
diff --git a/apisix/discovery/consul/schema.lua 
b/apisix/discovery/consul/schema.lua
index d7cf2954a..5d6fc641e 100644
--- a/apisix/discovery/consul/schema.lua
+++ b/apisix/discovery/consul/schema.lua
@@ -44,6 +44,11 @@ return {
                 wait = 60,
             }
         },
+        sort_type = {
+            type = "string",
+            enum = {"origin", "host_sort", "port_sort", "combine_sort"},
+            default = "origin",
+        },
         skip_services = {
             type = "array",
             minItems = 1,
diff --git a/ci/pod/docker-compose.first.yml b/ci/pod/docker-compose.first.yml
index aee79a838..622360638 100644
--- a/ci/pod/docker-compose.first.yml
+++ b/ci/pod/docker-compose.first.yml
@@ -55,6 +55,48 @@ services:
     networks:
       consul_net:
 
+  ## Consul cluster
+  consul_node_1:
+    image: consul:1.7
+    restart: unless-stopped
+    ports:
+      - "9500:8500"
+      - "8300:8300"
+      - "8301:8301"
+      - "8302:8302"
+      - "9600:8600"
+    command: [ "consul", "agent", "-server", "-bootstrap-expect=1", "-bind", 
"0.0.0.0", "-client", "0.0.0.0", "-node", "node-1", "-log-level", "info", 
"-data-dir=/consul/data", "-enable-script-checks" ]
+    networks:
+      consul_cluster_net:
+        aliases:
+          - consul.cluster
+
+  consul_node_2:
+    image: consul:1.7
+    restart: unless-stopped
+    environment:
+      - CONSUL_BIND_INTERFACE=eth0
+    ports:
+      - "9501:8500"
+    command: [ "consul", "agent", "-server", "-bind", "0.0.0.0", "-client", 
"0.0.0.0", "-retry-join", "consul.cluster", "-node", "node-2", "-log-level", 
"info", "-data-dir=/consul/data", "-enable-script-checks" ]
+    networks:
+      consul_cluster_net:
+        aliases:
+          - consul.cluster
+
+  consul_node_3:
+    image: consul:1.7
+    restart: unless-stopped
+    environment:
+      - CONSUL_BIND_INTERFACE=eth0
+    ports:
+      - "9502:8500"
+    command: [ "consul", "agent", "-server", "-bind", "0.0.0.0", "-client", 
"0.0.0.0", "-retry-join", "consul.cluster", "-node", "node-3", "-log-level", 
"info", "-data-dir=/consul/data", "-enable-script-checks" ]
+    networks:
+      consul_cluster_net:
+        aliases:
+          - consul.cluster
+
   ## Nacos cluster
   nacos_auth:
     hostname: nacos1
@@ -246,5 +288,6 @@ services:
 
 
 networks:
+  consul_cluster_net:
   consul_net:
   nacos_net:
diff --git a/docs/en/latest/discovery/consul.md 
b/docs/en/latest/discovery/consul.md
index 85e6b9ba2..1f230eddf 100644
--- a/docs/en/latest/discovery/consul.md
+++ b/docs/en/latest/discovery/consul.md
@@ -47,6 +47,7 @@ discovery:
     weight: 1                     # default 1
     fetch_interval: 5             # default 3 sec, only take effect for 
keepalive: false way
     keepalive: true               # default true, use the long pull way to 
query consul servers
+    sort_type: "origin"           # default origin
     default_service:              # you can define default service when 
missing hit
       host: "127.0.0.1"
       port: 20999
@@ -73,6 +74,13 @@ The `keepalive` has two optional values:
 - `true`, default and recommend value, use the long pull way to query consul 
servers
 - `false`, not recommend, it would use the short pull way to query consul 
servers, then you can set the `fetch_interval` for fetch interval
 
+The `sort_type` has four optional values:
+
+- `origin`, not sorting
+- `host_sort`, sort by host
+- `port_sort`, sort by port
+- `combine_sort`, with the precondition that hosts are ordered, ports are also 
ordered.
+
 #### Dump Data
 
 When we need reload `apisix` online, as the `consul` module maybe loads data 
from CONSUL slower than load routes from ETCD, and would get the log at the 
moment before load successfully from consul:
diff --git a/t/discovery/consul2.t b/t/discovery/consul2.t
new file mode 100644
index 000000000..841ef5026
--- /dev/null
+++ b/t/discovery/consul2.t
@@ -0,0 +1,292 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+use t::APISIX 'no_plan';
+
+repeat_each(1);
+log_level('info');
+no_root_location();
+no_shuffle();
+
+
+add_block_preprocessor(sub {
+    my ($block) = @_;
+
+    my $http_config = $block->http_config // <<_EOC_;
+
+    server {
+        listen 20999;
+
+        location / {
+            content_by_lua_block {
+                ngx.say("missing consul services")
+            }
+        }
+    }
+
+    server {
+        listen 30511;
+
+        location /hello {
+            content_by_lua_block {
+                ngx.say("server 1")
+            }
+        }
+    }
+    server {
+        listen 30512;
+
+        location /hello {
+            content_by_lua_block {
+                ngx.say("server 2")
+            }
+        }
+    }
+    server {
+        listen 30513;
+
+        location /hello {
+            content_by_lua_block {
+                ngx.say("server 3")
+            }
+        }
+    }
+    server {
+        listen 30514;
+
+        location /hello {
+            content_by_lua_block {
+                ngx.say("server 4")
+            }
+        }
+    }
+_EOC_
+
+    $block->set_value("http_config", $http_config);
+});
+
+our $yaml_config = <<_EOC_;
+apisix:
+  node_listen: 1984
+  enable_control: true
+  control:
+    ip: 127.0.0.1
+    port: 9090
+deployment:
+  role: data_plane
+  role_data_plane:
+    config_provider: yaml
+discovery:
+  consul:
+    servers:
+      - "http://127.0.0.1:8500";
+      - "http://127.0.0.1:8600";
+    skip_services:
+      - "service_c"
+    timeout:
+      connect: 1000
+      read: 1000
+      wait: 60
+    weight: 1
+    fetch_interval: 1
+    keepalive: true
+    default_service:
+      host: "127.0.0.1"
+      port: 20999
+      metadata:
+        fail_timeout: 1
+        weight: 1
+        max_fails: 1
+_EOC_
+
+
+run_tests();
+
+__DATA__
+
+=== TEST 1: sanity
+--- config
+location /consul1 {
+    rewrite  ^/consul1/(.*) /v1/agent/service/$1 break;
+    proxy_pass http://127.0.0.1:9500;
+}
+
+location /consul2 {
+    rewrite  ^/consul2/(.*) /v1/agent/service/$1 break;
+    proxy_pass http://127.0.0.1:9501;
+}
+location /consul3 {
+    rewrite  ^/consul3/(.*) /v1/agent/service/$1 break;
+    proxy_pass http://127.0.0.1:9502;
+}
+--- pipelined_requests eval
+[
+    "PUT /consul1/deregister/service_a1",
+    "PUT /consul1/deregister/service_b1",
+    "PUT /consul1/deregister/service_a2",
+    "PUT /consul1/deregister/service_b2",
+    "PUT /consul1/deregister/service_a3",
+    "PUT /consul1/deregister/service_a4",
+    "PUT /consul2/deregister/service_a1",
+    "PUT /consul2/deregister/service_a2",
+    "PUT /consul3/deregister/service_a1",
+    "PUT /consul3/deregister/service_a2",
+    "PUT /consul1/register\n" . 
"{\"ID\":\"service_a1\",\"Name\":\"service_a\",\"Tags\":[\"primary\",\"v1\"],\"Address\":\"127.0.0.1\",\"Port\":30511,\"Meta\":{\"service_a_version\":\"4.0\"},\"EnableTagOverride\":false,\"Weights\":{\"Passing\":10,\"Warning\":1}}",
+    "PUT /consul1/register\n" . 
"{\"ID\":\"service_a2\",\"Name\":\"service_a\",\"Tags\":[\"primary\",\"v1\"],\"Address\":\"127.0.0.1\",\"Port\":30512,\"Meta\":{\"service_a_version\":\"4.0\"},\"EnableTagOverride\":false,\"Weights\":{\"Passing\":10,\"Warning\":1}}",
+    "PUT /consul1/register\n" . 
"{\"ID\":\"service_a3\",\"Name\":\"service_a\",\"Tags\":[\"primary\",\"v1\"],\"Address\":\"localhost\",\"Port\":30511,\"Meta\":{\"service_a_version\":\"4.0\"},\"EnableTagOverride\":false,\"Weights\":{\"Passing\":10,\"Warning\":1}}",
+    "PUT /consul1/register\n" . 
"{\"ID\":\"service_a4\",\"Name\":\"service_a\",\"Tags\":[\"primary\",\"v1\"],\"Address\":\"localhost\",\"Port\":30512,\"Meta\":{\"service_a_version\":\"4.0\"},\"EnableTagOverride\":false,\"Weights\":{\"Passing\":10,\"Warning\":1}}",
+    "PUT /consul2/register\n" . 
"{\"ID\":\"service_a1\",\"Name\":\"service_a\",\"Tags\":[\"primary\",\"v1\"],\"Address\":\"127.0.0.1\",\"Port\":30511,\"Meta\":{\"service_a_version\":\"4.0\"},\"EnableTagOverride\":false,\"Weights\":{\"Passing\":10,\"Warning\":1}}",
+    "PUT /consul2/register\n" . 
"{\"ID\":\"service_a2\",\"Name\":\"service_a\",\"Tags\":[\"primary\",\"v1\"],\"Address\":\"127.0.0.1\",\"Port\":30512,\"Meta\":{\"service_a_version\":\"4.0\"},\"EnableTagOverride\":false,\"Weights\":{\"Passing\":10,\"Warning\":1}}",
+    "PUT /consul3/register\n" . 
"{\"ID\":\"service_a1\",\"Name\":\"service_a\",\"Tags\":[\"primary\",\"v1\"],\"Address\":\"127.0.0.1\",\"Port\":30511,\"Meta\":{\"service_a_version\":\"4.0\"},\"EnableTagOverride\":false,\"Weights\":{\"Passing\":10,\"Warning\":1}}",
+    "PUT /consul3/register\n" . 
"{\"ID\":\"service_a2\",\"Name\":\"service_a\",\"Tags\":[\"primary\",\"v1\"],\"Address\":\"127.0.0.1\",\"Port\":30512,\"Meta\":{\"service_a_version\":\"4.0\"},\"EnableTagOverride\":false,\"Weights\":{\"Passing\":10,\"Warning\":1}}",
+]
+--- error_code eval
+[200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 
200, 200, 200]
+
+
+
+=== TEST 2: show dump services without duplicates
+--- yaml_config
+apisix:
+  node_listen: 1984
+  enable_control: true
+discovery:
+  consul:
+    servers:
+      - "http://127.0.0.1:9500";
+    dump:
+      path: "consul.dump"
+      load_on_init: false
+--- config
+    location /t {
+        content_by_lua_block {
+            local json = require("toolkit.json")
+            local t = require("lib.test_admin")
+            ngx.sleep(2)
+
+            local code, body, res = 
t.test('/v1/discovery/consul/show_dump_file',
+                ngx.HTTP_GET)
+            local entity = json.decode(res)
+            ngx.say(json.encode(entity.services))
+        }
+    }
+--- timeout: 3
+--- request
+GET /t
+--- response_body
+{"service_a":[{"host":"127.0.0.1","port":30511,"weight":1},{"host":"127.0.0.1","port":30512,"weight":1},{"host":"localhost","port":30511,"weight":1},{"host":"localhost","port":30512,"weight":1}]}
+
+
+
+=== TEST 3: show dump services with host_sort
+--- yaml_config
+apisix:
+  node_listen: 1984
+  enable_control: true
+discovery:
+  consul:
+    servers:
+      - "http://127.0.0.1:9500";
+    sort_type: host_sort
+    dump:
+      path: "consul.dump"
+      load_on_init: false
+--- config
+    location /t {
+        content_by_lua_block {
+            local json = require("toolkit.json")
+            local t = require("lib.test_admin")
+            ngx.sleep(2)
+
+            local code, body, res = 
t.test('/v1/discovery/consul/show_dump_file',
+                ngx.HTTP_GET)
+            local entity = json.decode(res)
+            ngx.say(json.encode(entity.services))
+        }
+    }
+--- timeout: 3
+--- request
+GET /t
+--- response_body
+{"service_a":[{"host":"127.0.0.1","port":30511,"weight":1},{"host":"127.0.0.1","port":30512,"weight":1},{"host":"localhost","port":30511,"weight":1},{"host":"localhost","port":30512,"weight":1}]}
+
+
+
+=== TEST 4: show dump services with port sort
+--- yaml_config
+apisix:
+  node_listen: 1984
+  enable_control: true
+discovery:
+  consul:
+    servers:
+      - "http://127.0.0.1:9500";
+    sort_type: port_sort
+    dump:
+      path: "consul.dump"
+      load_on_init: false
+--- config
+    location /t {
+        content_by_lua_block {
+            local json = require("toolkit.json")
+            local t = require("lib.test_admin")
+            ngx.sleep(2)
+
+            local code, body, res = 
t.test('/v1/discovery/consul/show_dump_file',
+                ngx.HTTP_GET)
+            local entity = json.decode(res)
+            ngx.say(json.encode(entity.services))
+        }
+    }
+--- timeout: 3
+--- request
+GET /t
+--- response_body
+{"service_a":[{"host":"127.0.0.1","port":30511,"weight":1},{"host":"localhost","port":30511,"weight":1},{"host":"127.0.0.1","port":30512,"weight":1},{"host":"localhost","port":30512,"weight":1}]}
+
+
+
+=== TEST 5: show dump services with combine sort
+--- yaml_config
+apisix:
+  node_listen: 1984
+  enable_control: true
+discovery:
+  consul:
+    servers:
+      - "http://127.0.0.1:9500";
+    sort_type: combine_sort
+    dump:
+      path: "consul.dump"
+      load_on_init: false
+--- config
+    location /t {
+        content_by_lua_block {
+            local json = require("toolkit.json")
+            local t = require("lib.test_admin")
+            ngx.sleep(2)
+
+            local code, body, res = 
t.test('/v1/discovery/consul/show_dump_file',
+                ngx.HTTP_GET)
+            local entity = json.decode(res)
+            ngx.say(json.encode(entity.services))
+        }
+    }
+--- timeout: 3
+--- request
+GET /t
+--- response_body
+{"service_a":[{"host":"127.0.0.1","port":30511,"weight":1},{"host":"127.0.0.1","port":30512,"weight":1},{"host":"localhost","port":30511,"weight":1},{"host":"localhost","port":30512,"weight":1}]}

Reply via email to