apisix~集成服务发现注册中心

apisix · 浏览次数 : 0

小编点评

## Generate k8s ServiceAccount Token This configuration outlines the steps for setting up a ServiceAccount and ClusterRole in Kubernetes to access and listen to Kubernetes Endpoints resources. **1. Create ServiceAccount:** * Define a `ServiceAccount` with the name `apisix-test` and namespace `default`. * Create a `ClusterRole` named `apisix-testrules` with the following attributes: * `apiGroups`: `[""]` (no namespace restrictions) * `resources`: * `kind`: `Endpoints` * `name`: `endpoints` * `verbs`: ["get", "list", "watch"] * `subjects`: * `kind`: `ServiceAccount` * `name`: `apisix-test` * `namespace`: `default` * `roleBindingName`: `apsisix-testroleRef` **2. Get ServiceAccount Token:** * For versions prior to v1.24, you can use `kubectl get secret` commands to extract the token. * For v1.24 and later, the token is stored in a dedicated `Secret` named `apsisix-test-kubeapi`. * Use the following command to retrieve the token: ```sh kubectl get secret apisix-test-kubeapi -n default -o jsonpath={\".data.token\"} | base64 -d ``` **3. Add Token to APISIX Configuration:** * In the `config.yaml` of your APISIX cluster, add the token as a `discovery` object: ```yaml apiVersion: v1 kind: Endpoints metadata: name: plat-dev namespace: defaultsubsets spec: addresses: - ip: "10.5.10.109" - ip: "10.5.10.110" ports: - port: 3306 name: port ``` **4. Verify Token Permission:** * Use the `kubectl get` command to verify the token has access to the endpoints service: ```sh kubectl get service --all-namespaces ``` **Note:** * Replace `test-apisix.pkulaw.com` with your actual APISIX domain name. * This configuration assumes that the service's address is publicly accessible from the cluster. * Ensure that the token is valid and has the necessary permissions to access the endpoints service.

正文

摘要

当业务量发生变化时,需要对上游服务进行扩缩容,或者因服务器硬件故障需要更换服务器。如果网关是通过配置来维护上游服务信息,在微服务架构模式下,其带来的维护成本可想而知。再者因不能及时更新这些信息,也会对业务带来一定的影响,还有人为误操作带来的影响也不可忽视,所以网关非常必要通过服务注册中心动态获取最新的服务实例信息。架构图如下所示:

  1. 服务启动时将自身的一些信息,比如服务名、IP、端口等信息上报到注册中心;各个服务与注册中心使用一定机制(例如心跳)通信,如果注册中心与服务长时间无法通信,就会注销该实例;当服务下线时,会删除注册中心的实例信息;
  2. 网关会准实时地从注册中心获取服务实例信息;
  3. 当用户通过网关请求服务时,网关从注册中心获取的实例列表中选择一个进行代理;

常见的注册中心:Eureka, Etcd, Consul, Nacos, Zookeeper 等

如何扩展注册中心?

基本步骤

APISIX 要扩展注册中心其实是件非常容易的事情,其基本步骤如下:

  1. 在 apisix/discovery/ 目录中添加注册中心客户端的实现;
  2. 实现用于初始化的 _M.init_worker() 函数以及用于获取服务实例节点列表的 _M.nodes(service_name) 函数;
  3. 将注册中心数据转换为 APISIX 格式的数据;

集成nacos

https://www.bookstack.cn/read/apisix-2.13-zh/275fbdd662ec08a9.md

discovery:
  nacos:
    host:
      - "http://192.168.xx.xx:8848"
    prefix: "/nacos/v1"
    fetch_interval: 1
    weight: 1
    timeout:
      connect: 2000
      send: 2000
      read: 5000

集成kubernetes

https://www.bookstack.cn/read/apisix-2.13-zh/a586728927b44a68.md
https://apisix.apache.org/zh/docs/apisix/next/discovery/kubernetes/

discovery:
  kubernetes:
    service:
      schema: https
      host: 192.168.60.146
      port: "6443"  #这里有一个比较坑的地方,port 必须是字符串,否则会导致 APISIX 启动报错:
    client:
      token: |-
        ZXlKaGJHY2lPaUpTVXpJMU5pSXNJbXRwWkNJNkltWTNNRVpCUTJSa2FHSnNkMVpsYjIwMWNFODVTMVpLUjE5TFFVTlhZVEo0ZWs5UlpFMXJiakZtV0RRaWZRLmV5SnBjM01pT2lKcmRXSmxjbTVsZEdWekwzTmxjblpwWTJWaFkyTnZkVzUwSWl3aWEzVmlaWEp1WlhSbGN5NXBieTl6WlhKMmFXTmxZV05qYjNWdWRDOXVZVzFsYzNCaFkyVWlPaUpoY0dsemFYZ2lMQ0pyZFdKbGNtNWxkR1Z6TG1sdkwzTmxjblpwWTJWaFkyTnZkVzUwTDNObFkzSmxkQzV1WVcxbElqb2laR1ZtWVhWc2RDMTBiMnRsYmkxa2F6WTJlaUlzSW10MVltVnlibVYwWlhNdWFXOHZjMlZ5ZG1salpXRmpZMjkxYm5RdmMyVnlkbWxqWlMxaFkyTnZkVzUwTG01aGJXVWlPaUprWldaaGRXeDBJaXdpYTNWaVpYSnVaWFJsY3k1cGJ5OXpaWEoyYVdObFlXTmpiM1Z1ZEM5elpYSjJhV05sTFdGalkyOTFiblF1ZFdsa0lqb2lOemxpTnpnd00yWXRPR1poWXkwMFlXRTVMVGsxWWpjdFlXSmhORFEwWVdNNE4yRXhJaXdpYzNWaUlqb2ljM2x6ZEdWdE9uTmxjblpwWTJWaFkyTnZkVzUwT21Gd2FYTnBlRHBrWldaaGRXeDBJbjAuT3hWUTh2d2w0ZnZaLThZbTk1anlNcTNxTFBPTDhjaGZxdlZKQy10WXhLb3J5X2Fma3dzcU5WZ1RONWZuYlhmLW53MlNHWmpJdV9MbnhhbGxiQmhGT0l6UkI3QTY5QkpsYkpfTTNTNHNXcjdhN1EzaF9xTUZsc0pQQ2VhSG1NV3doZUR2dnZfOHFoV2dfN3MtRGk4OHp6QWpva1dOMlZIM3FBRXU5dWpmeVRlUTJXRzZYTVJyWWM1Y0pwN2F2WjBrNUo0V05yMHdTRHpYRkFsQUtUOHV4NUJWSlg0VEl6eXdjZDdTdWtkR3FrbmVtUnc3Q0lDWmR0bnZxZ1lXWnJpRFdwaVBSYklDLUFISFgtY3RrREtBV19TdFhvNFRLSTcxTlRYTzdVd0wtMWV4eXM0VnBETEZ6TkdhVDBUOWVRM1llTktfRUxRQy0zZWJGOEItRjFDRU5n
    match:
     - default
     - ^my-[a-z]+$

获取serviceaccount账号的token的方法

apisix的k8s服务发现配置

1 为了让 APISIX 能查询和监听 Kubernetes 的 Endpoints 资源变动,我们需要创建一个 ServiceAccount:

kind: ServiceAccount
apiVersion: v1
metadata:
  name: apisix-test
  namespace: default

2 以及一个具有集群级查询和监听 Endpoints 资源权限的 ClusterRole:

kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: apisix-test
rules:
- apiGroups: [ "" ]
  resources: [ endpoints ]
  verbs: [ get,list,watch ]

3 再将这个 ServiceAccount 和 ClusterRole 关联起来:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: apisix-test
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: apisix-test
subjects:
  - kind: ServiceAccount
    name: apisix-test
    namespace: default

4 然后我们需要获取这个 ServiceAccount 的 token 值,如果 Kubernetes 是 v1.24 之前的版本,可以通过下面的方法获取 token 值:

$ kubectl get secrets | grep apisix-test
$ kubectl get secret apisix-test-token-89hcm -o jsonpath={.data.token} | base64 -d

5 Kubernetes 从 v1.24 版本开始,不能再通过 kubectl get secret 获取 token 了,需要手动建立secret来生成token:

# 集群执行这个yaml  
apiVersion: v1
kind: Secret
metadata:
  name: apisix-test-kubeapi
  namespace: default
  annotations:
    kubernetes.io/service-account.name: "apisix-test"
type: kubernetes.io/service-account-token
data:

# 然后执行
kubectl get secret apisix-test-kubeapi -n default -o jsonpath={".data.token"} | base64 -d 

6 我们在 APISIX 的配置文件 config.yaml 中添加如下内容( 将上面生成的 token 填写到 token 字段 ):

discovery:
  kubernetes:
    service:
      schema: https
      host: 127.0.0.1
      port: "6443"
    client:
      token: ...

上面服务发现,我选择kubernetes时,并没有成功,而我直接在节点节,使用<服务名>.<命令空间>,这种方式反而是支持的,配置如下

clusterrole相关操作

kubectl describe  serviceaccount  <sa-name>
kubectl describe clusterrole <clusterrole-name>
kubectl describe clusterrolebinding <clusterrolebinding-name>
kubectl get rolebindings,clusterrolebindings --all-namespaces | grep apisix-test  

添加上游服务

说明: service_name 必须满足格式:[namespace]/[name]:[portName]

  • namespace: Endpoints 所在的命名空间
  • name: Endpoints 的资源名
  • portName: Endpoints 定义包含的 ports.name 值,如果 Endpoints 没有定义 ports.name,请依次使用 targetPort, port 代替。设置了 ports.name 的情况下,不能使用后两者。
    返回值: 以如下 Endpoints 为例:
apiVersion: v1
kind: Endpoints
metadata:
  name: plat-dev
  namespace: default
subsets:
  - addresses:
      - ip: "10.5.10.109"
      - ip: "10.5.10.110"
    ports:
      - port: 3306
        name: port

这里有一个比较坑的地方,port 必须是字符串,否则会导致 APISIX 启动报错 invalid discovery kubernetes configuration: object matches none of the required

问题与解决

  • k8s token错误
2024/05/17 03:01:07 [error] 54#54: *114 [lua] informer_factory.lua:295: list failed, kind: Endpoints, reason: Unauthorized, message : {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}

检查token值

  • k8s serviceaccount账号无权限
2024/05/17 03:01:07 [error] 54#54: *114 [lua] informer_factory.lua:295: list failed, kind: Endpoints, reason: Forbidden, message : {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Forbidden","code":403}

检查serviceaccount绑定的clusterrole是否有endpoint权限

  • 上游服务未找到
2024/05/17 03:05:22 [error] 52#52: *623 [lua] init.lua:400: nodes(): get unexpected upstream service_name: cms.default.svc.cluster.local, client: 192.168.60.136, server: _, request: "GET /k8s/products HTTP/1.1", host: "test-apisix.pkulaw.com"

2024/05/17 03:05:22 [error] 52#52: *623 [lua] init.lua:545: handle_upstream(): failed to set upstream: no valid upstream node: nil, client: 192.168.60.136, server: _, request: "GET /k8s/products HTTP/1.1", host: "test-apisix.pkulaw.com"

因为apisix中获取到的是k8s服务的endpoints地址【由service指向的pod的真实地址】,这个地址对k8s集群外是不公开的,如图

大功告成!

参考:https://www.aneasystone.com/archives/2023/03/apisix-service-discovery.html

与apisix~集成服务发现注册中心相似的内容:

apisix~集成服务发现注册中心

摘要 当业务量发生变化时,需要对上游服务进行扩缩容,或者因服务器硬件故障需要更换服务器。如果网关是通过配置来维护上游服务信息,在微服务架构模式下,其带来的维护成本可想而知。再者因不能及时更新这些信息,也会对业务带来一定的影响,还有人为误操作带来的影响也不可忽视,所以网关非常必要通过服务注册中心动态获

apisix~升级原始插件的方法

扩展apisix原始插件 当apisix提供的插件不能满足我们要求时,我们可能需要将它的plugin进行个性化扩展,例如一个jwt认证插件jwt-auth,它本身具有验证jwt有效性功能,支持rs256,hs256等常用签名算法,但在验证之后,如果希望将jwt中的用户信息取出来,并放请求头向上游传递

apisix~自定义插件的部署

参考 https://docs.api7.ai/apisix/how-to-guide/custom-plugins/create-plugin-in-lua https://apisix.apache.org/docs/apisix/next/plugin-develop/ https://api

apisix~14在自定义插件中调用proxy_rewrite

在 Apache APISIX 中,通过 proxy-rewrite 插件来修改上游配置时,需要确保插件的执行顺序和上下文环境正确。你提到在自己的插件中调用 proxy_rewrite.rewrite({host="new_upstream"}, ctx),但新上游没有生效,这可能是由于以下几个原因

Apisix网关-使用Grafana可视化Apisix的Prometheus数据

Apisix安装部署 Apisix官网安装教程 Apisix Dashboard官网安装教程 本次教程使用RPM包安装方式 使用systemctl管理服务 Apisix配置要点 /usr/local/apisix/conf/config.yaml Apisix服务监听 etcd连接配置 admin_

apisix~authz-keycloak插件介绍

参考:https://apisix.apache.org/docs/apisix/plugins/authz-keycloak/ kc插件源码梳理及原理说明 如果只是进行keycloak颁发的token进行校验(签名校验和有效期校验),那么我们可以使用jwt-auth这个插件实现,并且已经对这个插件

apisix~lua插件开发与插件注册

开发插件的步骤 在APISIX中,要自定义插件,一般需要按照以下步骤进行操作: 编写Lua脚本:首先,你需要编写Lua脚本来实现你想要的功能。可以根据APISIX提供的插件开发文档和示例进行编写。 将Lua脚本放置到APISIX插件目录:将编写好的Lua脚本文件放置到APISIX的插件目录下,一般是

apisix~jwt-auth插件

在网关开启jwt-auth插件之后,你的网关就具有了jwt解析和校验的功能,主要是校验jwt token的有效性,包含过期时间和签名等。 https://apisix.apache.org/docs/apisix/plugins/jwt-auth/ 支持的签名算法 "HS256" "HS512" "

【转帖】使用 LuaRocks 安装 Apache APISIX 依赖项时,为什么会导致超时、安装缓慢或安装失败?

使用 LuaRocks 安装 Apache APISIX 依赖项时,为什么会导致超时、安装缓慢或安装失败?# http://apisix.incubator.apache.org/zh/docs/apisix/2.14/FAQ/ 可能是因为使用的 LuaRocks 服务器延迟过高。 为了解决这个问题