EnvoyFilter详解

 欢迎关注我的公众号:

 目前刚开始写一个月,一共写了18篇原创文章,文章目录如下:

istio多集群探秘,部署了50次多集群后我得出的结论

istio多集群链路追踪,附实操视频

istio防故障利器,你知道几个,istio新手不要读,太难!

istio业务权限控制,原来可以这么玩

istio实现非侵入压缩,微服务之间如何实现压缩

不懂envoyfilter也敢说精通istio系列-http-rbac-不要只会用AuthorizationPolicy配置权限

不懂envoyfilter也敢说精通istio系列-02-http-corsFilter-不要只会vs

不懂envoyfilter也敢说精通istio系列-03-http-csrf filter-再也不用再代码里写csrf逻辑了

不懂envoyfilter也敢说精通istio系列http-jwt_authn-不要只会RequestAuthorization

不懂envoyfilter也敢说精通istio系列-05-fault-filter-故障注入不止是vs

不懂envoyfilter也敢说精通istio系列-06-http-match-配置路由不只是vs

不懂envoyfilter也敢说精通istio系列-07-负载均衡配置不止是dr

不懂envoyfilter也敢说精通istio系列-08-连接池和断路器

不懂envoyfilter也敢说精通istio系列-09-http-route filter

不懂envoyfilter也敢说精通istio系列-network filter-redis proxy

不懂envoyfilter也敢说精通istio系列-network filter-HttpConnectionManager

不懂envoyfilter也敢说精通istio系列-ratelimit-istio ratelimit完全手册

学习目标

什么是EnvoyFilter

EnvoyFilter provides a mechanism to customize the Envoy configuration generated by Istio Pilot. Use EnvoyFilter to modify values for certain fields, add specific filters, or even add entirely new listeners, clusters, etc. This feature must be used with care, as incorrect configurations could potentially destabilize the entire mesh. Unlike other Istio networking objects, EnvoyFilters are additively applied. Any number of EnvoyFilters can exist for a given workload in a specific namespace. The order of application of these EnvoyFilters is as follows: all EnvoyFilters in the config root namespace, followed by all matching EnvoyFilters in the workload’s namespace.

资源详解

FieldTypeDescriptionRequired
workloadSelectorWorkloadSelectorCriteria used to select the specific set of pods/VMs on which this patch configuration should be applied. If omitted, the set of patches in this configuration will be applied to all workload instances in the same namespace. If omitted, the EnvoyFilter patches will be applied to all workloads in the same namespace. If the EnvoyFilter is present in the config root namespace, it will be applied to all applicable workloads in any namespace.No
configPatchesEnvoyConfigObjectPatch[]One or more patches with match conditions.Yes

没有workloadSelector

全局有效

ef-accesslog-global.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: access-log
  namespace: istio-system
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
    patch:
      operation: MERGE
      value:
        typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
          access_log:
          - name: envoy.access_loggers.file
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.access_loggers.file.v3.FileAccessLog"
              path: /dev/stdout
              log_format:
                text_format: "[%START_TIME%] \" %RESPONSE_CODE% \n"

名称空间有效

ef-accesslog-namespeced.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: access-log
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
    patch:
      operation: MERGE
      value:
        typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
          access_log:
          - name: envoy.access_loggers.file
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.access_loggers.file.v3.FileAccessLog"
              path: /dev/stdout
              log_format:
                text_format: "[%START_TIME%] \" %RESPONSE_CODE% \n"

workloadSelector

ef-productpage-accesslog.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: access-log
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
    patch:
      operation: MERGE
      value:
        typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
          access_log:
          - name: envoy.access_loggers.file
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.access_loggers.file.v3.FileAccessLog"
              path: /dev/stdout
              log_format:
                text_format: "[%START_TIME%] \" %RESPONSE_CODE% \n"

configPatches

FieldTypeDescriptionRequired
applyToApplyToSpecifies where in the Envoy configuration, the patch should be applied. The match is expected to select the appropriate object based on applyTo. For example, an applyTo with HTTP_FILTER is expected to have a match condition on the listeners, with a network filter selection on envoy.filters.network.http_connection_manager and a sub filter selection on the HTTP filter relative to which the insertion should be performed. Similarly, an applyTo on CLUSTER should have a match (if provided) on the cluster and not on a listener.No
matchEnvoyConfigObjectMatchMatch on listener/route configuration/cluster.No
patchPatchThe patch to apply along with the operation.No

applyTo

ApplyTo specifies where in the Envoy configuration, the given patch should be applied.

NameDescription
INVALID
LISTENERApplies the patch to the listener.
FILTER_CHAINApplies the patch to the filter chain.
NETWORK_FILTERApplies the patch to the network filter chain, to modify an existing filter or add a new filter.
HTTP_FILTERApplies the patch to the HTTP filter chain in the http connection manager, to modify an existing filter or add a new filter.
ROUTE_CONFIGURATIONApplies the patch to the Route configuration (rds output) inside a HTTP connection manager. This does not apply to the virtual host. Currently, only MERGE operation is allowed on the route configuration objects.
VIRTUAL_HOSTApplies the patch to a virtual host inside a route configuration.
HTTP_ROUTEApplies the patch to a route object inside the matched virtual host in a route configuration.
CLUSTERApplies the patch to a cluster in a CDS output. Also used to add new clusters.
EXTENSION_CONFIGApplies the patch to or adds an extension config in ECDS output. Note that ECDS is only supported by HTTP filters.

INVALID

LISTENER

kubectl apply -f gateway/gateway-https.yaml -n istio

ef-ingressgateway-remove-listener.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: LISTENER
    match:
      listener:
        portNumber: 8080
    patch:
      operation: REMOVE

删除8443 listener

kubectl port-forward istio-ingressgateway-d46c4ff9b-zsjgd -n istio-system --address 0.0.0.0 15001:15000

http://192.168.198.154:15001/config_dump

添加监听器

ef-productpage-add-listener.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
  namespace: istio 
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: LISTENER
    match:
      context: SIDECAR_INBOUND
    patch:
      operation: ADD
      value:
        name: proxy
        address:
          socket_address:
            protocol: TCP
            address: 0.0.0.0
            port_value: 8083
        filter_chains:
        - filters:
          - name: "envoy.filters.network.http_connection_manager"
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
              stat_prefix: ingress_proxy
              route_config:
                name: route_a
                virtual_hosts:
                - name: envoy_cyz
                  domains:
                  - "*"
                  routes:
                  - match:
                      prefix: "/"
                    route:
                      cluster: cluster123
              http_filters:
              - name: "envoy.filters.http.router
                typed_config:
                  "@type": "type.googleapis.com/envoy.extensions.filters.http.router.v3.Router" 
  - applyTo: CLUSTER
    patch:
      operation: ADD
      value: 
        name: "cluster123"
        type: STATIC
        connect_timeout: 0.5s
        lb_policy: ROUND_ROBIN
        load_assignment:
          cluster_name: cluster123
          endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: 127.0.0.1
                    port_value: 9080

添加vs

vs-bookinfo.yaml

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: bookinfo
spec:
  hosts:
  - "*"
  gateways:
  - bookinfo-gateway
  http:
  - match:
    - uri:
        prefix: /
    route:
    - destination:
        host: productpage.istio.svc.cluster.local
        port:
          number: 8083

k8s svc 添加端口

kubectl edit svc productpage -n istio

  - name: http8083
    port: 8083
    protocol: TCP
    targetPort: 8083

访问:

http://bookinfo.demo:30986/productpage

添加listenerFilter

ef-listener-filter.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
  namespace: istio-system
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: LISTENER
    patch:
      operation: MERGE
      value:
        listener_filters:
        - name: envoy.filters.listener.original_src
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.listener.original_src.v3.OriginalSrc
        - name: envoy.filters.listener.tls_inspector

FILTER_CHAIN

ef-ingressgateway-filter-chain-remove.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: FILTER_CHAIN
    match:
      listener:
        portNumber: 8080
    patch:
      operation: REMOVE
     

ef-ingressgateway-filter-chain-merge.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: FILTER_CHAIN
    match:
      listener:
        portNumber: 8080
    patch:
      operation: MERGE
      value:
        name: test

NETWORK_FILTER

ef-ingressgateway-network-filter-merge.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        portNumber: 8080
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
    patch:
      operation: MERGE
      value:
            name: envoy.filters.network.http_connection_manager
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
              "stat_prefix": "test"
              

echo

先部署gateway

gateway/gateway-mysql.yaml

apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
  name: mysql
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 3306
      name: mysql
      protocol: MYSQL
    hosts:
    - "*"

ef-ingressgateway-network-filter-echo-3306.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        portNumber: 3306
    patch:
      operation: REMOVE
  - applyTo: NETWORK_FILTER
    match:
      listener:
        portNumber: 3306
    patch:
      operation: ADD
      value:
            name: envoy.filters.network.echo
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.filters.network.echo.v3.Echo"

telnet 192.168.198.154 30300

direct_response

先部署网关,同上

ef-ingressgateway-network-filter-direct_response-3306.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        portNumber: 3306
    patch:
      operation: REMOVE
  - applyTo: NETWORK_FILTER
    match:
      listener:
        portNumber: 3306
    patch:
      operation: ADD
      value:
            name: envoy.filters.network.direct_response
            typed_config:
                 "@type": "type.googleapis.com/envoy.extensions.filters.network.direct_response.v3.Config"
                 response:
                   inline_string: "test this is direct response||||||"

telnet 192.168.198.154 30300

dubbo

applyto/dubbo/dubbo-deploy.yaml

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: dubbo-sample-provider-v1
  labels:
    app: dubbo-sample-provider
spec:
  selector:
    matchLabels:
      app: dubbo-sample-provider
  replicas: 1
  template:
    metadata:
      labels:
        app: dubbo-sample-provider
        version: v1
    spec:
      containers:
        - name: dubbo-sample-provider
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/dubbo-sample-provider
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 20880
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: dubbo-sample-provider-v2
  labels:
    app: dubbo-sample-provider
spec:
  selector:
    matchLabels:
      app: dubbo-sample-provider
  replicas: 1
  template:
    metadata:
      labels:
        app: dubbo-sample-provider
        version: v2
    spec:
      containers:
        - name: dubbo-sample-provider
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/dubbo-sample-provider
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 20880
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: dubbo-sample-consumer
  labels:
    app: dubbo-sample-consumer
spec:
  selector:
    matchLabels:
      app: dubbo-sample-consumer
  replicas: 1
  template:
    metadata:
      labels:
        app: dubbo-sample-consumer
    spec:
      containers:
        - name: dubbo-sample-consumer
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/dubbo-sample-consumer
          imagePullPolicy: IfNotPresent
          env:
            - name: mode
              value: demo

applyto/dubbo/se-dubbo.yaml

apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: test-dubbo-service
  annotations:
    interface: org.apache.dubbo.samples.basic.api.DemoService
spec:
  hosts:
  - org.apache.dubbo.samples.basic.api.demoservice
  addresses:
  - 192.168.198.166
  ports:
  - number: 20880
    name: tcp-dubbo
    protocol: TCP
  workloadSelector:
    labels:
      app: dubbo-sample-provider
  resolution: STATIC

applyto/dubbo/dr-dubbo.yaml

apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: dubbo-sample-provider
spec:
  host: org.apache.dubbo.samples.basic.api.demoservice
  subsets:
  - name: v1
    labels:
      version: v1
  - name: v2
    labels:
      version: v2

applyto/dubbo/ef-dubbo.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: envoyfilter-dubbo-proxy
  namespace: istio-system
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: 193.193.192.192_20880
        filterChain:
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: REPLACE
      value:
        name: envoy.filters.network.dubbo_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.dubbo_proxy.v3.DubboProxy
          stat_prefix: outbound|20880||org.apache.dubbo.samples.basic.api.demoservice
          protocol_type: Dubbo
          serialization_type: Hessian2
          route_config:
          - name: outbound|20880||org.apache.dubbo.samples.basic.api.demoservice
            interface: org.apache.dubbo.samples.basic.api.DemoService
            routes:
            - match:
                method:
                  name:
                    exact: sayHello
              route:
                cluster: outbound|20880|v2|org.apache.dubbo.samples.basic.api.demoservice
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: virtualInbound
        filterChain:
          destination_port: 20880
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: REPLACE
      value:
        name: envoy.filters.network.dubbo_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.dubbo_proxy.v3.DubboProxy
          stat_prefix: inbound|20880||
          protocol_type: Dubbo
          serialization_type: Hessian2
          route_config:
          - name: inbound|20880||
            interface: org.apache.dubbo.samples.basic.api.DemoService
            routes:
            - match:
                method:
                  name:
                    exact: sayHello
              route:
                cluster: inbound|20880||

thrift_proxy

1部署应用

applyto/thrift/thrift-deploy.yaml

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: thrift-sample-server-v1
  labels:
    app: thrift-sample-server
spec:
  selector:
    matchLabels:
      app: thrift-sample-server
  replicas: 1
  template:
    metadata:
      labels:
        app: thrift-sample-server
        version: v1
    spec:
      containers:
        - name: thrift-sample-server
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/thrift-sample-server:latest
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 9090
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: thrift-sample-server-v2
  labels:
    app: thrift-sample-server
spec:
  selector:
    matchLabels:
      app: thrift-sample-server
  replicas: 1
  template:
    metadata:
      labels:
        app: thrift-sample-server
        version: v2
    spec:
      containers:
        - name: thrift-sample-server
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/thrift-sample-server:latest
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 9090
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: thrift-sample-client
  labels:
    app: thrift-sample-client
spec:
  selector:
    matchLabels:
      app: thrift-sample-client
  replicas: 1
  template:
    metadata:
      labels:
        app: thrift-sample-client
    spec:
      containers:
        - name: thrift-sample-client
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/thrift-sample-client:latest
          imagePullPolicy: IfNotPresent
          env:
            - name: helloServer
              value: "thrift-sample-server"
            - name: mode
              value: "demo"
---
apiVersion: v1
kind: Service
metadata:
  name: thrift-sample-server
spec:
  selector:
    app: thrift-sample-server
  ports:
    - name: tcp-thrift-hello-server
      protocol: TCP
      port: 9090
      targetPort: 9090
---

2配置dr

applyto/thrift/dr-thrift.yaml

apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: thrift-sample-server
spec:
  host: thrift-sample-server
  subsets:
  - name: v1
    labels:
      version: v1
  - name: v2
    labels:
      version: v2

3配置envoyfilter

applyto/thrift/envoyfilter-thrift-proxy.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: thrift-sample-server
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: ${thrift-sample-server-vip}_9090    # sed -i .bak "s/\${thrift-sample-server-vip}/`kubectl get svc thrift-sample-server -n thrift -o=jsonpath='{.spec.clusterIP}'`/" istio/envoyfilter-thrift-proxy.yaml
        filterChain:
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: REPLACE
      value:
        name: envoy.filters.network.thrift_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.thrift_proxy.v3.ThriftProxy
          stat_prefix: "outbound|9090||thrift-sample-server.thrift.svc.cluster.local"
          transport: AUTO_TRANSPORT
          protocol: AUTO_PROTOCOL
          thrift_filters:
          - name: envoy.filters.thrift.router
          route_config:
            routes:
            - match:
                # empty string matches any request method name
                method_name: ""
              route:
                weighted_clusters:
                  clusters:
                    - name: "outbound|9090|v1|thrift-sample-server.istio.svc.cluster.local"
                      weight: 50
                    - name: "outbound|9090|v2|thrift-sample-server.istio.svc.cluster.local"
                      weight: 50
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: virtualInbound
        filterChain:
          destination_port: 9090
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: REPLACE
      value:
        name: envoy.filters.network.thrift_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.thrift_proxy.v3.ThriftProxy
          stat_prefix: inbound|9090||
          transport: AUTO_TRANSPORT
          protocol: AUTO_PROTOCOL
          thrift_filters:
          - name: envoy.filters.thrift.router
          route_config:
            routes:
            - match:
                # empty string matches any request method name
                method_name: ""
              route:
                cluster: inbound|9090||

替换${thrift-sample-server-vip}

4查看日志

kubectl logs --tail 10 -f thrift-sample-client-85696799d9-5bmn4 -n istio

zoonkeeper&kafka

1部署应用

helm repo add bitnami https://charts.bitnami.com/bitnami

helm repo update

helm install my-release --set persistence.enabled=false --set zookeeper.persistence.enabled=false bitnami/kafka -n istio

applyto/kafka-zoonkeeper/kafka-sample.yaml

kind: Deployment
apiVersion: apps/v1
metadata:
  name: kafka-cat-producer
spec:
  selector:
    matchLabels:
      app: kafka-cat-producer
  template:
    metadata:
      labels:
        app: kafka-cat-producer
    spec:
      containers:
        - name: kafka-cat-producer
          image: confluentinc/cp-kafkacat
          imagePullPolicy: IfNotPresent
          command: ["/bin/sh"]
          args: ["-c", "while true; do  echo -e 'send kafka message '`date`'\r\n'|kafkacat -P  -b my-release-kafka:9092 -t test; echo 'send message to kafka'; sleep $((1 + RANDOM % 11)); done"]
---
kind: Deployment
apiVersion: apps/v1
metadata:
  name: kafka-cat-consumer
spec:
  selector:
    matchLabels:
      app: kafka-cat-consumer
  template:
    metadata:
      labels:
        app: kafka-cat-consumer
    spec:
      containers:
        - name: kafka-cat-consumer
          image: confluentinc/cp-kafkacat
          imagePullPolicy: IfNotPresent
          command: ["/bin/sh"]
          args: ["-c", "kafkacat -C -b my-release-kafka:9092 -t test"]

2配置kafka envoyfilter

applyto/kafka-zoonkeeper/envoyfilter-kafka-filter.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: kafka-envoy-filter
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: ${my-release-kafka}_9092    # sed -i .bak "s/\${my-release-kafka}/`kubectl get svc my-release-kafka -n kafka -o=jsonpath='{.spec.clusterIP}'`/" istio/envoyfilter-kafka-filter.yaml
        filterChain:
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: INSERT_BEFORE
      value:
        name: envoy.filters.network.kafka_broker
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.kafka_broker.v3.KafkaBroker
          stat_prefix: "outbound|9092||my-release-kafka.istio.svc.cluster.local"

替换${my-release-kafka}

3配置zoonkeeper envoyfilter

applyto/kafka-zoonkeeper/envoyfilter-zookeeper-filter.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: zookeeper-envoy-filter
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: ${my-release-zookeeper}_2181    # sed -i .bak "s/\${my-release-zookeeper}/`kubectl get svc my-release-zookeeper -n kafka -o=jsonpath='{.spec.clusterIP}'`/" istio/envoyfilter-zookeeper-filter.yaml
        filterChain:
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: INSERT_BEFORE
      value:
        name: envoy.filters.network.zookeeper_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.zookeeper_proxy.v3.ZooKeeperProxy
          stat_prefix: "outbound|2181||my-release-zookeeper.istio.svc.cluster.local"

替换${my-release-zookeeper}

4测试

kubectl exec -it kafka-cat-consumer-6865bdcf9b-c55h9 -n istio -- /bin/bash

kafkacat -C -b my-release-kafka:9092 -t test

mysql_proxy

ef-network_filter_mysql.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: mysqldb
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: 10.68.10.86_3306
        filterChain:
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: INSERT_BEFORE
      value:
        name: envoy.filters.network.mysql_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.mysql_proxy.v3.MySQLProxy
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: 10.68.10.86_3306
        filterChain:
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: INSERT_BEFORE
      value:
        name: envoy.filters.network.rbac
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.rbac.v3.RBAC
          stat_prefix: rbac
          rules:
             action: DENY
             policies:
               "product-viewer":
                 permissions:
                 - metadata:
                     filter: envoy.filters.network.mysql_proxy
                     path:
                     - key: t1.test
                     value:
                       list_match:
                         one_of:
                           string_match:
                             prefix: update
                 principals:
                 - any: true
           enforcement_type: CONTINUOUS
          

注意修改listener ip

csrf

applyto/csrf/samesite/csrf-deploy.yaml

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: csrf
  labels:
    app: csrf
spec:
  selector:
    matchLabels:
      app: csrf
  replicas: 1
  template:
    metadata:
      labels:
        app: csrf
        version: v1
    spec:
      containers:
        - name: csrf
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/csrf-satesite:latest
          imagePullPolicy: Always
          ports:
            - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: csrf
spec:
  selector:
    app: csrf
  ports:
    - name: tcp-csrf
      protocol: TCP
      port: 8080
      targetPort: 8080
---

applyto/csrf/samesite/envoyfilter-csrf-gateway.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        #name: 0.0.0.0_8080  
        portNumber: 8080
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
    patch:
      operation: MERGE
      value:
        name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
          codec_type: AUTO
          stat_prefix: ingress_http
          route_config:
            name: local_route
            virtual_hosts:
            - name: www
              domains:
              - "*"
              cors:
                allow_origin_string_match:
                - safe_regex:
                    google_re2: {}
                    regex: .*
                filter_enabled:
                  default_value:
                    numerator: 100
                    denominator: HUNDRED
              typed_per_filter_config:
                envoy.filters.http.csrf:
                  "@type": type.googleapis.com/envoy.extensions.filters.http.csrf.v3.CsrfPolicy
                  filter_enabled:
                    default_value:
                      numerator: 100
                      denominator: HUNDRED
                    runtime_key: csrf.www.enabled
                  shadow_enabled:
                    default_value:
                      numerator: 0
                      denominator: HUNDRED
                    runtime_key: csrf.www.shadow_enabled
              routes:
              - match:
                  prefix: "/csrf/disabled"
                route:
                  cluster: generic_service
                typed_per_filter_config:
                  envoy.filters.http.csrf:
                    "@type": type.googleapis.com/envoy.extensions.filters.http.csrf.v3.CsrfPolicy
                    filter_enabled:
                      default_value:
                        numerator: 0
                        denominator: HUNDRED
              - match:
                  prefix: "/csrf/shadow"
                route:
                  cluster: generic_service
                typed_per_filter_config:
                  envoy.filters.http.csrf:
                    "@type": type.googleapis.com/envoy.extensions.filters.http.csrf.v3.CsrfPolicy
                    filter_enabled:
                      default_value:
                        numerator: 0
                        denominator: HUNDRED
                    shadow_enabled:
                      default_value:
                        numerator: 100
                        denominator: HUNDRED
              - match:
                  prefix: "/csrf/additional_origin"
                route:
                  cluster: generic_service
                typed_per_filter_config:
                  envoy.filters.http.csrf:
                    "@type": type.googleapis.com/envoy.extensions.filters.http.csrf.v3.CsrfPolicy
                    filter_enabled:
                      default_value:
                        numerator: 100
                        denominator: HUNDRED
                    additional_origins:
                    - safe_regex:
                        google_re2: {}
                        regex: .*
              - match:
                  prefix: "/"
                route:
                  cluster: generic_service
  - applyTo: HTTP_FILTER
    match:
        listener:
          #name: 0.0.0.0_8080  
          portNumber: 8080
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
              subFilter:
                name: envoy.filters.http.router
    patch:
        operation: INSERT_BEFORE
        value:
          name: envoy.filters.http.cors
          typed_config:                  
            "@type": type.googleapis.com/envoy.extensions.filters.http.cors.v3.Cors
  - applyTo: HTTP_FILTER
    match:
        listener:
          #name: 0.0.0.0_8080  
          portNumber: 8080
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
              subFilter:
                name: envoy.filters.http.router
    patch:
        operation: INSERT_BEFORE
        value:           
          name: envoy.filters.http.csrf
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.csrf.v3.CsrfPolicy
            filter_enabled:
              default_value:
                numerator: 100
                denominator: HUNDRED 
  - applyTo: CLUSTER
    match:
      context: ANY
      cluster: {} 
    patch:
      operation: ADD
      value:
        name: generic_service
        connect_timeout: 0.25s
        type: STRICT_DNS
        lb_policy: ROUND_ROBIN
        load_assignment:
          cluster_name: generic_service
          endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: csrf.istio.svc.cluster.local
                    port_value: 8080
        

cors

index.html

<html>
<head><title></title></head>
<body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>  
<script>
$(function(){
        $("#cors").click(
                function(){
                        $.ajax({
                                type:"get",
                                dataType : "html",
                                url:"http://bookinfo.demo:30986/productpage",
                                success:function(data){
                                        alert(data);
                                }
                        })
                });

        $("#cors2").click(
                function(){
                        $.ajax({
                                type:"get",
                                dataType : "json",
                                url:"http://bookinfo.demo:30986/reviews/1",
                                contentType : 'application/json;charset=UTF-8',
                                success:function(data){
                                        var jsonStr = JSON.stringify(data);
                                        alert(jsonStr);
                                }
                        })
                });
          $("#cors3").click(
                function(){
                        $.ajax({
                                type:"delete",
                                contentType : 'application/json;charset=UTF-8',
                                dataType : "json",
                                url:"http://bookinfo.demo:30986/reviews/1",
                                success:function(data){
                                        var jsonStr = JSON.stringify(data);
                                        alert(jsonStr);
                                }
                        })
                });
           $("#cors4").click(
                function(){
                        $.ajax({
                                type:"get",
                                contentType : 'application/json;charset=UTF-8',
                                dataType : "json",
                                headers:{"X-Custom-Header":"value"},
                                url:"http://bookinfo.demo:30986/reviews/1",
                                success:function(data){
                                        var jsonStr = JSON.stringify(data);
                                        alert(jsonStr);
                                }
                        })
                });
         
});

</script>
<input type="button" id="cors" value="简单请求"/>
<input type="button" id="cors2" value="非简单请求"/>
<input type="button" id="cors3" value="非简单请求delete"/>
<input type="button" id="cors4" value="非简单请求headers"/>
</body>
</html>

ef-cors.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: 0.0.0.0_8080  
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
    patch:
      operation: MERGE
      value:
        name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
          codec_type: AUTO
          stat_prefix: ingress_http
          route_config:
            name: local_route
            virtual_hosts:
            - name: local_route
              domains:
              - "*"
              cors:
                allow_methods: "GET,POST,OPTIONS,DELETE"
                allow_headers: "content-type,x-custom-header"
                max_age: "60"
                allow_origin_string_match:
                - exact: "http://mytest.com:8081"
                filter_enabled:
                  default_value:
                    numerator: 100
                    denominator: HUNDRED
              routes:
              - match:
                  path: "/productpage"
                route:
                  cluster: outbound|9080||productpage.istio.svc.cluster.local
              - match:
                  prefix: "/reviews"
                route:
                  cluster: outbound|9080||reviews.istio.svc.cluster.local
  
           

ext_authz

applyto/ext_authz/auth_deploy.yaml

apiVersion: v1
kind: Service
metadata:
  name: auth
  labels:
    app: auth
spec:
  ports:
  - name: http
    port: 9002
    targetPort: 9002
  selector:
    app: auth
---
kind: Deployment
apiVersion: apps/v1
metadata:
  name: auth
  labels:
    app: auth
spec:
  replicas: 1
  selector:
    matchLabels:
      app: auth
  template:
    metadata:
      labels:
        app: auth
    spec:
      containers:
        - name: auth
          imagePullPolicy: Always
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/ext_authz_grpc:latest 
          ports:
          - containerPort: 9002

applyto/ext_authz/ef-ext_auth.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: 0.0.0.0_8080  
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
    patch:
      operation: MERGE
      value:
        name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
          codec_type: AUTO
          stat_prefix: ingress_http
          route_config:
            name: local_route
            virtual_hosts:
            - name: upstream
              domains:
              - "*"
              routes:
              - match:
                  prefix: "/"
                route:
                  cluster: outbound|9080||productpage.istio.svc.cluster.local
  - applyTo: HTTP_FILTER
    match:
        listener:
          name: 0.0.0.0_8080  
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
              subFilter:
                name: envoy.filters.http.router
    patch:
        operation: INSERT_BEFORE
        value: 
            name: envoy.filters.http.ext_authz
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz
              transport_api_version: V3
              http_service:
                server_uri:
                  uri: ext_authz
                  cluster: ext_authz-http-service
                  timeout:  0.250s
                authorization_response:
                  allowed_upstream_headers:
                    patterns:
                    - exact: x-current-user
  - applyTo: CLUSTER
    match:
      context: ANY
      cluster: {} 
    patch:
      operation: ADD
      value:
        name: ext_authz-http-service
        connect_timeout: 0.25s
        type: STRICT_DNS
        lb_policy: ROUND_ROBIN
        load_assignment:
          cluster_name: grpc-authservice
          endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: auth.istio.svc.cluster.local
                    port_value: 9002

测试

curl http://bookinfo.demo:30986/productpage -H "Authorization: Bearer token1"

curl http://bookinfo.demo:30986/productpage -H "Authorization: Bearer token10"

HTTP_FILTER

ef-ingressgateway-http-filter-remove.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: HTTP_FILTER
    match:
      listener:
        portNumber: 8080
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
            subFilter:
              name: "envoy.filters.http.fault"
    patch:
      operation: REMOVE

ef-ingressgateway-http-filter-compression.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  namespace: istio-system
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: GATEWAY
        listener:
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
              subFilter:
                name: envoy.filters.http.router
      patch:
        operation: INSERT_BEFORE
        value:
          name: envoy.filters.http.compressor
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.compressor.v3.Compressor
            response_direction_config:
              common_config:
                min_content_length: 100
                content_type:
                - 'text/html'
            compressor_library:
              name: text_optimized
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.compression.gzip.compressor.v3.Gzip
                memory_level: 3
                window_bits: 10
                compression_level: BEST_COMPRESSION
                compression_strategy: DEFAULT_STRATEGY

ef-ingressgateway-http-filter-compression-insert-after.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  namespace: istio-system
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: GATEWAY
        listener:
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
              subFilter:
                name: istio.metadata_exchange
      patch:
        operation: INSERT_AFTER
        value:
          name: envoy.filters.http.compressor
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.compressor.v3.Compressor
            response_direction_config:
              common_config:
                min_content_length: 100
                content_type:
                - 'text/html'
            compressor_library:
              name: text_optimized
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.compression.gzip.compressor.v3.Gzip
                memory_level: 3
                window_bits: 10
                compression_level: BEST_COMPRESSION
                compression_strategy: DEFAULT_STRATEGY

ratelimit/envoyfilter-local-rate-limit.yaml

本地限流

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: filter-local-ratelimit-svc
  namespace: istio-system
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_FILTER
      listener:
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
      patch:
        operation: INSERT_BEFORE
        value:
          name: envoy.filters.http.local_ratelimit
          typed_config:
            "@type": type.googleapis.com/udpa.type.v1.TypedStruct
            type_url: type.googleapis.com/envoy.extensions.filters.http.local_ratelimit.v3.LocalRateLimit
            value:
              stat_prefix: http_local_rate_limiter
              token_bucket:
                max_tokens: 10
                tokens_per_fill: 10
                fill_interval: 60s
              filter_enabled:
                runtime_key: local_rate_limit_enabled
                default_value:
                  numerator: 100
                  denominator: HUNDRED
              filter_enforced:
                runtime_key: local_rate_limit_enforced
                default_value:
                  numerator: 100
                  denominator: HUNDRED
              response_headers_to_add:
                - append: false
                  header:
                    key: x-local-rate-limit
                    value: 'true'

lua filter

ef-http-filter-lua.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: HTTP_FILTER
    match:
      context: SIDECAR_INBOUND
      listener:
        portNumber: 9080
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
            subFilter:
              name: "envoy.filters.http.router"
    patch:
      operation: INSERT_BEFORE
      value: 
       name: envoy.filters.http.lua
       typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua"
          inlineCode: |
            function envoy_on_response(response_handle)
                response_handle:logInfo(" ========= XXXXX ========== ")
                response_handle:headers():add("X-User-Header", "worked")
            end

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: sidecar-token-service-filter-for-bookinfo
  namespace: default
spec:
  workloadSelector:
    labels:
      app: productpage # target the app to which you want to apply the filter
  configPatches:
  - applyTo: HTTP_FILTER
    match:
      context: SIDECAR_INBOUND
      listener:
        filterChain:
          filter:
            name: "envoy.http_connection_manager"
            subFilter:
              name: "envoy.filters.http.jwt_authn"
    patch:
      operation: INSERT_BEFORE
      value:
       name: envoy.ext_authz
       config:
         stat_prefix: ext_authz
         grpc_service:
           envoy_grpc:
             cluster_name: ext_authz
           timeout: 10s # Timeout for the entire request (including authcode for token exchange with the IDP)
  - applyTo: CLUSTER
    match:
      context: ANY
      cluster: {} # this line is required starting in istio 1.4.0
    patch:
      operation: ADD
      value:
        name: ext_authz
        connect_timeout: 5s # This timeout controls the initial TCP handshake timeout - not the timeout for the entire request
        type: LOGICAL_DNS
        lb_policy: ROUND_ROBIN
        http2_protocol_options: {}
        load_assignment:
          cluster_name: ext_authz
          endpoints:
            - lb_endpoints:
                - endpoint:
                    address:
                      socket_address:
                        address: 127.0.0.1
                        port_value: 10003

grpc_web

https://github.com/superj80820/GRPC-Web-Simple-Demo

https://github.com/SafetyCulture/grpc-web-devtools/tree/master/example

grpc-web在vue中的使用_寒山苦旅的博客-CSDN博客

deploy

applyto/web-grpc/web-grpc-deploy.yaml

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-grpc
  labels:
    app: web-grpc
spec:
  selector:
    matchLabels:
      app: web-grpc
  replicas: 1
  template:
    metadata:
      labels:
        app: web-grpc
        version: v1
    spec:
      containers:
        - name: csrf
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/server:latest
          imagePullPolicy: Always
          ports:
            - containerPort: 50051
---
apiVersion: v1
kind: Service
metadata:
  name: web-grpc
spec:
  selector:
    app: web-grpc
  ports:
    - name: grpc-web-grpc
      protocol: TCP
      port: 50051
      targetPort: 50051
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web-grpc-client
  labels:
    app: web-grpc-client
spec:
  selector:
    matchLabels:
      app: web-grpc-client
  replicas: 1
  template:
    metadata:
      labels:
        app: web-grpc-client
        version: v1
    spec:
      containers:
        - name: csrf
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/client:latest
          imagePullPolicy: Always
          ports:
            - containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
  name: web-grpc-client
spec:
  selector:
    app: web-grpc-client
  ports:
    - name: http-web-grpc-client
      protocol: TCP
      port: 8080
      targetPort: 8080

注意svc的port的名字grpc-web-grpc,表名用的是grpc协议

vs

applyto/web-grpc/vs-web-grpc.yaml

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: web-grpc
spec:
  hosts:
  - "*"
  gateways:
  - bookinfo-gateway
  http:
  - match:
    - uri:
        prefix: /s12.example
    corsPolicy:
      allowOrigins:
      - exact: http://192.168.198.154:30986
      - exact: http://192.168.198.154:8081
      allowMethods:
      - GET
      - OPTIONS
      - POST
      - PUT
      - DELETE
      maxAge: "1m"
      allowHeaders:
      - keep-alive
      - user-agent
      - cache-control
      - content-type
      - content-transfer-encoding
      - custom-header-1
      - x-accept-content-transfer-encoding
      - x-accept-response-streaming
      - x-user-agent
      - x-grpc-web
      - grpc-timeout
      exposeHeaders: 
      - custom-header-1
      - grpc-status
      - grpc-message
    route:
    - destination:
        host: web-grpc.istio.svc.cluster.local
        port:
          number: 50051

applyto/web-grpc/vs-web-grpc-client.yaml

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: bookinfo
spec:
  hosts:
  - "*"
  gateways:
  - bookinfo-gateway
  http:
  - match:
    - uri:
        prefix: /
    route:
    - destination:
        host: web-grpc-client.istio.svc.cluster.local
        port:
          number: 8080

applyto/web-grpc/ef-web-grpc.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: web-grpc
  configPatches:
  - applyTo: HTTP_FILTER
    match:
        listener:
          destination_port: 50051
          transport_protocol: "tls"
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
              subFilter:
                name: istio.metadata_exchange
    patch:
        operation: INSERT_BEFORE
        value:           
          name: envoy.filters.http.grpc_web
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.grpc_web.v3.GrpcWeb

访问:

http://192.168.198.154:30986/

fault

ef-fault.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: ANY
        listener:
          filterChain:
            filter:
              name: "envoy.filters.network.http_connection_manager"
              subFilter:
                name: "envoy.filters.http.router"
      patch:
        operation: INSERT_BEFORE
        value:
            name: envoy.filters.http.fault
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.fault.v3.HTTPFault
              abort:
                http_status: 503
                percentage:
                  numerator: 100
                  denominator: HUNDRED
              delay:
                fixed_delay: 3s
                percentage:
                  numerator: 100
                  denominator: HUNDRED

ROUTE_CONFIGURATION

ef-ingressgateway-route-configuration.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: ROUTE_CONFIGURATION
    match:
      context: SIDECAR_INBOUND
      routeConfiguration:
        portNumber: 9080
    patch:
      operation: MERGE
      value:
          name: "inbound|9080||"
          virtual_hosts:
          - name: “inbound|http|9080”
            domains:
            - "productpage.istio.svc.cluster.local"
            - "productpage.istio.svc.cluster.local:9080"
            - "productpage"
            - "productpage:9080"
            - "productpage.istio.svc.cluster"
            - "productpage.istio.svc.cluster:9080"
            - "productpage.istio.svc"
            - "productpage.istio.svc:9080"
            - "productpage.istio"
            - "productpage.istio:9080"
            routes:
            - match:
                prefix: "/"
              direct_response:
                status: 200
                body:
                  inline_string: "example body\n"

ef-dubbo-route-configuration.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  configPatches:
  - applyTo: ROUTE_CONFIGURATION
    match:
      context: SIDECAR_OUTBOUND
      routeConfiguration:
        portNumber: 9080
    patch:
      operation: MERGE
      value:
        name: "20882"
        virtualHosts:
        - name: "mosn.io.dubbo.DemoService:20882"
          domains:
          - mosn.io.dubbo.DemoService
          retryPolicy:
            numRetries: 3
          routes:
          - match:
              headers:
              - name: "zone"
                exactMatch: "gz01"
            route:
              timeout: 10s
              weightedClusters:
                clusters:
                  - name: "outbound|20882|blue|mosn.io.dubbo.DemoService"
                    weight: 10
                  - name: "outbound|20882|green|mosn.io.dubbo.DemoService"
                    weight: 90
                totalWeight: 100
              retryPolicy:
                retryOn: "true"
                numRetries: 2
                perTryTimeout: 2s
          - match:
              prefix: "/"
            route:
              timeout: 10s
              cluster: "outbound|20880||quasra.dubbo.proxy"
              retryPolicy:
                retryOn: "true"
                numRetries: 2
                perTryTimeout: 2s
        - name: "mosn.io.dubbo.DemoService2:20882"
          domains:
          - mosn.io.dubbo.DemoService2
          retryPolicy:
            numRetries: 5
          routes:
          - match:
              prefix: "/"
            route:
              timeout: 5s
              cluster: "outbound|20882||mosn.io.dubbo.DemoService2"
              retryPolicy:
                numRetries: 3
                perTryTimeout: 1s

VIRTUAL_HOST

部署ratelimit

1创建cm

ratelimit/ratelimit-config.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: ratelimit-config
data:
  config.yaml: |
    domain: productpage-ratelimit
    descriptors:
      - key: PATH
        value: "/productpage"
        rate_limit:
          unit: minute
          requests_per_unit: 1
      - key: PATH
        rate_limit:
          unit: minute
          requests_per_unit: 100

2创建deployment

ratelimit/ratelimit-deploy.yaml

apiVersion: v1
kind: Service
metadata:
  name: redis
  labels:
    app: redis
spec:
  ports:
  - name: redis
    port: 6379
  selector:
    app: redis
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis
spec:
  replicas: 1
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
      - image: redis:alpine
        imagePullPolicy: Always
        name: redis
        ports:
        - name: redis
          containerPort: 6379
      restartPolicy: Always
      serviceAccountName: ""
---
apiVersion: v1
kind: Service
metadata:
  name: ratelimit
  labels:
    app: ratelimit
spec:
  ports:
  - name: http-port
    port: 8080
    targetPort: 8080
    protocol: TCP
  - name: grpc-port
    port: 8081
    targetPort: 8081
    protocol: TCP
  - name: http-debug
    port: 6070
    targetPort: 6070
    protocol: TCP
  selector:
    app: ratelimit
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ratelimit
spec:
  replicas: 1
  selector:
    matchLabels:
      app: ratelimit
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: ratelimit
    spec:
      containers:
      - image: envoyproxy/ratelimit:6f5de117 # 2021/01/08
        imagePullPolicy: Always
        name: ratelimit
        command: ["/bin/ratelimit"]
        env:
        - name: LOG_LEVEL
          value: debug
        - name: REDIS_SOCKET_TYPE
          value: tcp
        - name: REDIS_URL
          value: redis:6379
        - name: USE_STATSD
          value: "false"
        - name: RUNTIME_ROOT
          value: /data
        - name: RUNTIME_SUBDIRECTORY
          value: ratelimit
        ports:
        - containerPort: 8080
        - containerPort: 8081
        - containerPort: 6070
        volumeMounts:
        - name: config-volume
          mountPath: /data/ratelimit/config/config.yaml
          subPath: config.yaml
      volumes:
      - name: config-volume
        configMap:
          name: ratelimit-config

3创建envoy-filter

ratelimit/envoyfilter-filter.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: filter-ratelimit
  namespace: istio-system
spec:
  workloadSelector:
    # select by label in the same namespace
    labels:
      istio: ingressgateway
  configPatches:
    # The Envoy config you want to modify
    - applyTo: HTTP_FILTER
      match:
        context: GATEWAY
        listener:
          filterChain:
            filter:
              name: "envoy.filters.network.http_connection_manager"
              subFilter:
                name: "envoy.filters.http.router"
      patch:
        operation: INSERT_BEFORE
        # Adds the Envoy Rate Limit Filter in HTTP filter chain.
        value:
          name: envoy.filters.http.ratelimit
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.ratelimit.v3.RateLimit
            # domain can be anything! Match it to the ratelimter service config
            domain: productpage-ratelimit
            failure_mode_deny: true
            rate_limit_service:
              grpc_service:
                envoy_grpc:
                  cluster_name: rate_limit_cluster
                timeout: 10s
              transport_api_version: V3
    - applyTo: CLUSTER
      match:
        cluster:
          service: ratelimit.istio.svc.cluster.local
      patch:
        operation: ADD
        # Adds the rate limit service cluster for rate limit service defined in step 1.
        value:
          name: rate_limit_cluster
          type: STRICT_DNS
          connect_timeout: 10s
          lb_policy: ROUND_ROBIN
          http2_protocol_options: {}
          load_assignment:
            cluster_name: rate_limit_cluster
            endpoints:
            - lb_endpoints:
              - endpoint:
                  address:
                     socket_address:
                      address: ratelimit.istio.svc.cluster.local
                      port_value: 8081

4创建action envoyfilter

ratelimit/envoyfilter-action.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: filter-ratelimit-svc
  namespace: istio-system
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
    - applyTo: VIRTUAL_HOST
      match:
        context: GATEWAY
        routeConfiguration:
          vhost:
            name: "*:80"
            route:
              action: ANY
      patch:
        operation: MERGE
        # Applies the rate limit rules.
        value:
          rate_limits:
            - actions: # any actions in here
              - request_headers:
                  header_name: ":path"
                  descriptor_key: "PATH"

5访问

http://bookinfo.demo:30986/productpage

返回429,太多请求错误

cache

还在开发中

applyto/cache/cache-deploy.yaml

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cache
  labels:
    app: cache
spec:
  selector:
    matchLabels:
      app: cache
  replicas: 1
  template:
    metadata:
      labels:
        app: cache
        version: v1
    spec:
      containers:
        - name: cache
          image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/cache:latest
          imagePullPolicy: Always
          ports:
            - containerPort: 8083
---
apiVersion: v1
kind: Service
metadata:
  name: cache
spec:
  selector:
    app: cache
  ports:
    - name: tcp-cache
      protocol: TCP
      port: 8083
      targetPort: 8083

applyto/cache/vs-cache.yaml

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: cache
spec:
  hosts:
  - "*"
  gateways:
  - bookinfo-gateway
  http:
  - match:
    - uri:
        prefix: /service
    route:
    - destination:
        host: cache.istio.svc.cluster.local
        port:
          number: 8083

applyto/cache/ef-cache.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: cache
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: GATEWAY
        listener:
          filterChain:
            filter:
              name: "envoy.filters.network.http_connection_manager"
              subFilter:
                name: "envoy.filters.http.router"
      patch:
        operation: INSERT_FIRST
        value:
            name: "envoy.filters.http.cache.simple_http_cache"
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.filters.http.cache.v3alpha.CacheConfig"
              typed_config:
                "@type": "type.googleapis.com/envoy.extensions.cache.simple_http_cache.v3alpha.SimpleHttpCacheConfig"

记得修改时区

http://bookinfo.demo:30986/service/1/valid-for-minute

http://bookinfo.demo:30986/service/1/private

http://bookinfo.demo:30986/service/1/no-cache

HTTP_ROUTE

ef-ingressgateway-http-route.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_ROUTE
      match:
        context: SIDECAR_INBOUND
        routeConfiguration:
          portNumber: 9080
      patch:
        operation: MERGE
        value:
          match:
            #headers:
            #  - name: some-header
            #    present_match: true
            prefix: /
          direct_response:
                status: 200
                body:
                  inline_string: "example body\n"

CLUSTER

ef-productpage-cluster.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
  namespace: istio 
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: HTTP_ROUTE
    match:
      context: SIDECAR_INBOUND
      routeConfiguration:
        portNumber: 9080
    patch:
        operation: MERGE
        value:
          match:
            prefix: /
          route:
            cluster: "cluster123"
            timeout: "111s"
  - applyTo: CLUSTER
    patch:
      operation: ADD
      value: 
        name: "cluster123"
        type: STATIC
        connect_timeout: 0.5s
        lb_policy: ROUND_ROBIN
        load_assignment:
          cluster_name: cluster123
          endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: 127.0.0.1
                    port_value: 9080

redis_proxy

1部署redis

applyto/redis/redis-cluster-deploy.yaml

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: redis-cluster
data:
  update-node.sh: |
    #!/bin/sh
    REDIS_NODES="/data/nodes.conf"
    sed -i -e "/myself/ s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/${POD_IP}/" ${REDIS_NODES}
    exec "$@"
  redis.conf: |+
    cluster-enabled yes
    cluster-require-full-coverage no
    cluster-node-timeout 15000
    cluster-config-file /data/nodes.conf
    cluster-migration-barrier 1
    appendonly yes
    protected-mode no
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis-cluster
spec:
  serviceName: redis-cluster
  replicas: 6
  selector:
    matchLabels:
      app: redis-cluster
  template:
    metadata:
      labels:
        app: redis-cluster
    spec:
      containers:
      - name: redis
        image: redis:6.0.8-alpine
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 6379
          name: tcp-client
        - containerPort: 16379
          name: tcp-gossip
        command: ["/conf/update-node.sh", "redis-server", "/conf/redis.conf", "--cluster-announce-ip $(POD_IP)"]
        env:
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        volumeMounts:
        - name: conf
          mountPath: /conf
          readOnly: false
      volumes:
      - name: conf
        configMap:
          name: redis-cluster
          defaultMode: 0755

---
apiVersion: v1
kind: Service
metadata:
  name: redis-cluster
spec:
  type: ClusterIP
  ports:
  - port: 6379
    targetPort: 6379
    name: tcp-client
  - port: 16379
    targetPort: 16379
    name: tcp-gossip
  selector:
    app: redis-cluster

applyto/redis/redis-client-deploy.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis-client
  labels:
    app: redis-client
spec:
  selector:
    matchLabels:
      app: redis-client
  replicas: 1
  template:
    metadata:
      labels:
        app: redis-client
    spec:
      containers:
      - name: redis-client
        image: redis
        imagePullPolicy: IfNotPresent

applyto/redis/redis-mirror-deploy.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis-mirror
  labels:
    app: redis-mirror
spec:
  selector:
    matchLabels:
      app: redis-mirror
  replicas: 1
  template:
    metadata:
      labels:
        app: redis-mirror
    spec:
      containers:
      - name: redis-mirror
        image: redis
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 6379

---
apiVersion: v1
kind: Service
metadata:
  name: redis-mirror
spec:
  selector:
    app: redis-mirror
  ports:
  - name: tcp  # istio will treat it as a normal tcp service since the prefix is tcp
    port: 6379
    protocol: TCP
    targetPort: 6379

2设置 envoyfilter cluster

applyto/redis/envoyfilter-cluster.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: custom-redis-cluster
  namespace: istio-system
spec:
  configPatches:
  - applyTo: CLUSTER
    patch:
      operation: INSERT_FIRST
      value:
        name: "custom-redis-cluster"
        connect_timeout: 0.5s
        lb_policy: CLUSTER_PROVIDED
        load_assignment:
          cluster_name: custom-redis-cluster
          endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: redis-cluster-0.redis-cluster.istio.svc.cluster.local
                    port_value: 6379
            - endpoint:
                address:
                  socket_address:
                    address: redis-cluster-1.redis-cluster.istio.svc.cluster.local
                    port_value: 6379
            - endpoint:
                address:
                  socket_address:
                    address: redis-cluster-2.redis-cluster.istio.svc.cluster.local
                    port_value: 6379
            - endpoint:
                address:
                  socket_address:
                    address: redis-cluster-3.redis-cluster.istio.svc.cluster.local
                    port_value: 6379
            - endpoint:
                address:
                  socket_address:
                    address: redis-cluster-4.redis-cluster.istio.svc.cluster.local
                    port_value: 6379
            - endpoint:
                address:
                  socket_address:
                    address: redis-cluster-5.redis-cluster.istio.svc.cluster.local
                    port_value: 6379
        cluster_type:
          name: envoy.clusters.redis
          typed_config:
            "@type": type.googleapis.com/google.protobuf.Struct
            value:
              cluster_refresh_rate: 5s
              cluster_refresh_timeout: 3s
              redirect_refresh_interval: 5s
              redirect_refresh_threshold: 5

3设置redis_proxy

applyto/redis/envoyfilter-redis-proxy.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: add-redis-proxy
  namespace: istio-system
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: ${REDIS_VIP}_6379               # Replace REDIS_VIP with the cluster IP of "redis-cluster service
        filterChain:
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: REPLACE
      value:
        name: envoy.filters.network.redis_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.redis_proxy.v3.RedisProxy
          stat_prefix: redis_stats
          prefix_routes:
            catch_all_route:
              cluster: custom-redis-cluster
          settings:
            op_timeout: 5s
            enable_redirection: true
            enable_command_stats: true
            read_policy: REPLICA

替换REDIS_VIP

4构建redis集群

获取pod ip

kubectl get pods -l app=redis-cluster -o jsonpath='{range.items[*]}{.status.podIP}:6379 ' -n istio

构建集群

kubectl exec -it redis-cluster-0 -n istio -- redis-cli --cluster create --cluster-replicas 1 172.20.0.227:6379 172.20.1.238:6379 172.20.2.209:6379 172.20.0.228:6379 172.20.1.239:6379 172.20.2.210:6379

验证集群是否成功

kubectl exec -it redis-cluster-0 -c redis -n istio -- redis-cli cluster info

进入客户端

kubectl exec -it redis-client-6c4b6c4fb5-7hbv9 -n istio -- /bin/bash

连接集群

redis-cli -h redis-cluster -p 6379

设置数据

set a a等

验证数据

kubectl exec redis-cluster-0 -c redis -n istio -- redis-cli --scan

5设置redis _proxy with mirror

applyto/redis/envoyfilter-redis-proxy-with-mirror.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: add-redis-proxy
  namespace: istio-system
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: ${REDIS_VIP}_6379             # Replace REDIS_VIP with the cluster IP of "redis-cluster service
        filterChain:
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: REPLACE
      value:
        name: envoy.filters.network.redis_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.redis_proxy.v3.RedisProxy
          stat_prefix: redis_stats
          prefix_routes:
            catch_all_route:
              request_mirror_policy:
              - cluster: outbound|6379||redis-mirror.istio.svc.cluster.local
                exclude_read_commands: True     # Mirror write commands only:
              cluster: custom-redis-cluster
          settings:
            op_timeout: 5s
            enable_redirection: true
            enable_command_stats: true
            read_policy: REPLICA

替换REDIS_VIP

6进入客户端,连接集群,设置数据

7进入客户端,连接mirror,验证数据

EXTENSION_CONFIG

ef-extension-config.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  configPatches:
  - applyTo: EXTENSION_CONFIG
    patch:
      operation: ADD 
      value:
        name: my-wasm-extension
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm
          config:
            root_id: my-wasm-root-id
            vm_config:
              vm_id: my-wasm-vm-id
              runtime: envoy.wasm.runtime.v8
              code:
                local:
                  inline_string: "envoy.wasm.stats"
                #remote:
                #  http_uri:
                #    uri: http://my-wasm-binary-uri
            configuration:
              "@type": "type.googleapis.com/google.protobuf.StringValue"
              value: |
                {}
  - applyTo: HTTP_FILTER
    match:
        context: SIDECAR_INBOUND
        listener:
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
              subFilter:
                name: envoy.filters.http.router
    patch:
      operation: INSERT_BEFORE
      value:
        name: my-wasm-extension 
        config_discovery:
          config_source:
            ads: {}
          type_urls: ["type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm"]

ef-extension-config-attributegen.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: SIDECAR_INBOUND
        listener:
          filterChain:
            filter:
              name: "envoy.filters.network.http_connection_manager"
              subFilter:
                name: "envoy.filters.http.router"
      patch:
        operation: INSERT_BEFORE
        value:
          name: istio.attributegen
          config_discovery:
            config_source:
              ads: {}
              initial_fetch_timeout: 0s 
            type_urls: [ "type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm"]       
    - applyTo: EXTENSION_CONFIG
      match:
        context: SIDECAR_INBOUND
      patch:
        operation: ADD
        value:
          name: istio.attributegen
          typed_config:
            "@type": type.googleapis.com/udpa.type.v1.TypedStruct
            type_url: type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm
            value:
              config:
                configuration:
                  "@type": "type.googleapis.com/google.protobuf.StringValue"
                  value: |
                    {
                      "attributes": [
                      {
                        "output_attribute": "istio_responseClass",
                        "match": [
                         {
                             "value": "2xx",
                             "condition": "response.code >= 200 && response.code <= 299"
                         }]
                      },
                      {
                        "output_attribute": "istio_operationId",
                        "match": [
                        {
                            "value": "getoperation",
                            "condition": "request.method == 'GET'"
                        }]
                      },
                      {
                        "output_attribute": "istio_grpcResponseStatus",
                        "match": [
                        {
                            "value": "OK",
                            "condition": "response.grpc_status == 0"
                        }]
                      }]
                    }
                vm_config:
                  runtime: envoy.wasm.runtime.null
                  code:
                    local:
                      inline_string: envoy.wasm.attributegen

match

One or more match conditions to be met before a patch is applied to the generated configuration for a given proxy.

FieldTypeDescriptionRequired
contextPatchContextThe specific config generation context to match on. Istio Pilot generates envoy configuration in the context of a gateway, inbound traffic to sidecar and outbound traffic from sidecar.No
proxyProxyMatchMatch on properties associated with a proxy.No
listenerListenerMatch (oneof)Match on envoy listener attributes.No
routeConfigurationRouteConfigurationMatch (oneof)Match on envoy HTTP route configuration attributes.No
clusterClusterMatch (oneof)Match on envoy cluster attributes.No

context

NameDescription
ANYAll listeners/routes/clusters in both sidecars and gateways.
SIDECAR_INBOUNDInbound listener/route/cluster in sidecar.
SIDECAR_OUTBOUNDOutbound listener/route/cluster in sidecar.
GATEWAYGateway listener/route/cluster.

ANY

applyto/fault/ef-fault.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: ANY
        listener:
          filterChain:
            filter:
              name: "envoy.filters.network.http_connection_manager"
              subFilter:
                name: "envoy.filters.http.router"
      patch:
        operation: INSERT_BEFORE
        value:
            name: envoy.filters.http.fault
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.fault.v3.HTTPFault
              abort:
                http_status: 503
                percentage:
                  numerator: 100
                  denominator: HUNDRED
              delay:
                fixed_delay: 3s
                percentage:
                  numerator: 100
                  denominator: HUNDRED

SIDECAR_INBOUND

applyto/ef-extension-config-attributegen.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: SIDECAR_INBOUND
        listener:
          filterChain:
            filter:
              name: "envoy.filters.network.http_connection_manager"
              subFilter:
                name: "envoy.filters.http.router"
      patch:
        operation: INSERT_BEFORE
        value:
          name: istio.attributegen
          config_discovery:
            config_source:
              ads: {}
              initial_fetch_timeout: 0s 
            type_urls: [ "type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm"]       
    - applyTo: EXTENSION_CONFIG
      match:
        context: SIDECAR_INBOUND
      patch:
        operation: ADD
        value:
          name: istio.attributegen
          typed_config:
            "@type": type.googleapis.com/udpa.type.v1.TypedStruct
            type_url: type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm
            value:
              config:
                configuration:
                  "@type": "type.googleapis.com/google.protobuf.StringValue"
                  value: |
                    {
                      "attributes": [
                      {
                        "output_attribute": "istio_responseClass",
                        "match": [
                         {
                             "value": "2xx",
                             "condition": "response.code >= 200 && response.code <= 299"
                         }]
                      },
                      {
                        "output_attribute": "istio_operationId",
                        "match": [
                        {
                            "value": "getoperation",
                            "condition": "request.method == 'GET'"
                        }]
                      },
                      {
                        "output_attribute": "istio_grpcResponseStatus",
                        "match": [
                        {
                            "value": "OK",
                            "condition": "response.grpc_status == 0"
                        }]
                      }]
                    }
                vm_config:
                  runtime: envoy.wasm.runtime.null
                  code:
                    local:
                      inline_string: envoy.wasm.attributegen

SIDECAR_OUTBOUND

applyto/fault/ef-fault-outbound.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: SIDECAR_OUTBOUND
        listener:
          filterChain:
            filter:
              name: "envoy.filters.network.http_connection_manager"
              subFilter:
                name: "envoy.filters.http.router"
      patch:
        operation: INSERT_BEFORE
        value:
            name: envoy.filters.http.fault
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.fault.v3.HTTPFault
              abort:
                http_status: 503
                percentage:
                  numerator: 100
                  denominator: HUNDRED
              delay:
                fixed_delay: 3s
                percentage:
                  numerator: 100
                  denominator: HUNDRED

GATEWAY

applyto/ef-ingressgateway-http-filter-compression-insert-after.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  namespace: istio-system
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: GATEWAY
        listener:
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
              subFilter:
                name: istio.metadata_exchange
      patch:
        operation: INSERT_AFTER
        value:
          name: envoy.filters.http.compressor
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.compressor.v3.Compressor
            response_direction_config:
              common_config:
                min_content_length: 100
                content_type:
                 - 'text/html'
            compressor_library:
              name: text_optimized
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.compression.gzip.compressor.v3.Gzip
                memory_level: 3
                window_bits: 10
                compression_level: BEST_COMPRESSION
                compression_strategy: DEFAULT_STRATEGY

proxy

FieldTypeDescriptionRequired
proxyVersionstringA regular expression in golang regex format (RE2) that can be used to select proxies using a specific version of istio proxy. The Istio version for a given proxy is obtained from the node metadata field ISTIO_VERSION supplied by the proxy when connecting to Pilot. This value is embedded as an environment variable (ISTIO_META_ISTIO_VERSION) in the Istio proxy docker image. Custom proxy implementations should provide this metadata variable to take advantage of the Istio version check option.No
metadatamapMatch on the node metadata supplied by a proxy when connecting to Istio Pilot. Note that while Envoy’s node metadata is of type Struct, only string key-value pairs are processed by Pilot. All keys specified in the metadata must match with exact values. The match will fail if any of the specified keys are absent or the values fail to match.No

ef-match-proxy.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: SIDECAR_OUTBOUND
        proxy:
          proxyVersion: 1.9.2
        listener:
          filterChain:
            filter:
              name: "envoy.filters.network.http_connection_manager"
              subFilter:
                name: "envoy.filters.http.router"
      patch:
        operation: INSERT_BEFORE
        value:
            name: envoy.filters.http.fault
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.fault.v3.HTTPFault
              abort:
                http_status: 503
                percentage:
                  numerator: 100
                  denominator: HUNDRED
              delay:
                fixed_delay: 3s
                percentage:
                  numerator: 100
                  denominator: HUNDRED

listener

FieldTypeDescriptionRequired
portNumberuint32The service port/gateway port to which traffic is being sent/received. If not specified, matches all listeners. Even though inbound listeners are generated for the instance/pod ports, only service ports should be used to match listeners.No
filterChainFilterChainMatchMatch a specific filter chain in a listener. If specified, the patch will be applied to the filter chain (and a specific filter if specified) and not to other filter chains in the listener.No
namestringMatch a specific listener by its name. The listeners generated by Pilot are typically named as IP:Port.No

portNumber

ef-match-listener-portnumber.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
  namespace: istio-system
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: LISTENER
    match:
      listener:
        portNumber: 8080
    patch:
      operation: MERGE
      value:
        listener_filters:
        - name: envoy.filters.listener.original_src
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.listener.original_src.v3.OriginalSrc
        - name: envoy.filters.listener.tls_inspector

filterChain

FieldTypeDescriptionRequired
namestringThe name assigned to the filter chain.No
snistringThe SNI value used by a filter chain’s match condition. This condition will evaluate to false if the filter chain has no sni match.No
transportProtocolstringApplies only to SIDECAR_INBOUND context. If non-empty, a transport protocol to consider when determining a filter chain match. This value will be compared against the transport protocol of a new connection, when it’s detected by the tls_inspector listener filter.Accepted values include:raw_buffer - default, used when no transport protocol is detected.tls - set when TLS protocol is detected by the TLS inspector.No
applicationProtocolsstringApplies only to sidecars. If non-empty, a comma separated set of application protocols to consider when determining a filter chain match. This value will be compared against the application protocols of a new connection, when it’s detected by one of the listener filters such as the http_inspector.Accepted values include: h2, http/1.1, http/1.0No
filterFilterMatchThe name of a specific filter to apply the patch to. Set this to envoy.filters.network.http_connection_manager to add a filter or apply a patch to the HTTP connection manager.No
destinationPortuint32The destinationport value used by a filter chain’s match condition. This condition will evaluate to false if the filter chain has no destinationport match.No

name

先添加名字

applyto/ef-ingressgateway-filter-chain-merge.yaml

ef-match-filterchain-name.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        portNumber: 8080
        filterChain:
          name: test
    patch:
      operation: MERGE
      value:
            name: envoy.filters.network.http_connection_manager
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
              "stat_prefix": "test"

sni

先添加server_names

applyto/ef-ingressgateway-filter-chain-merge.yaml

ef-match-filterchain-sni.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
  namespace: istio-system
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      context: GATEWAY
      listener:
        filterChain:
          sni: bookinfo.demo
          filter:
            name: "envoy.filters.network.http_connection_manager"
    patch:
      operation: MERGE
      value:
        typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
          xff_num_trusted_hops: 5
          common_http_protocol_options:
            idle_timeout: 30s

transportProtocol

ef-match-filterchain-transportProtocol.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: HTTP_FILTER
    match:
      context: SIDECAR_INBOUND
      listener:
        portNumber: 9080
        filterChain:
          transportProtocol: raw_buffer
          filter:
            name: "envoy.filters.network.http_connection_manager"
            subFilter:
              name: "envoy.filters.http.router"
    patch:
      operation: INSERT_BEFORE
      value: 
       name: envoy.filters.http.lua
       typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua"
          inlineCode: |
            function envoy_on_response(response_handle)
                response_handle:logInfo(" ========= XXXXX ========== ")
                response_handle:headers():add("X-User-Header", "worked")
            end

applicationProtocols

ef-match-filterchain-applicationProtocols.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: HTTP_FILTER
    match:
      context: SIDECAR_INBOUND
      listener:
        portNumber: 9080
        filterChain:
          applicationProtocols: http/1.1
          filter:
            name: "envoy.filters.network.http_connection_manager"
            subFilter:
              name: "envoy.filters.http.router"
    patch:
      operation: INSERT_BEFORE
      value: 
       name: envoy.filters.http.lua
       typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua"
          inlineCode: |
            function envoy_on_response(response_handle)
                response_handle:logInfo(" ========= XXXXX ========== ")
                response_handle:headers():add("X-User-Header", "worked")
            end

destinationPort

ef-match-filterchain-destinationPort.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: HTTP_FILTER
    match:
      context: SIDECAR_INBOUND
      listener:
        portNumber: 9080
        filterChain:
          destinationPort: 9080
          filter:
            name: "envoy.filters.network.http_connection_manager"
            subFilter:
              name: "envoy.filters.http.router"
    patch:
      operation: INSERT_BEFORE
      value: 
       name: envoy.filters.http.lua
       typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua"
          inlineCode: |
            function envoy_on_response(response_handle)
                response_handle:logInfo(" ========= XXXXX ========== ")
                response_handle:headers():add("X-User-Header", "worked")
            end

filter

FieldTypeDescriptionRequired
namestringThe filter name to match on. For standard Envoy filters, canonical filter names should be used.No
subFilterSubFilterMatchThe next level filter within this filter to match upon. Typically used for HTTP Connection Manager filters and Thrift filters.No

ef-match-filterchain-filter.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: HTTP_FILTER
    match:
      context: SIDECAR_INBOUND
      listener:
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
            subFilter:
              name: "envoy.filters.http.router"
    patch:
      operation: INSERT_BEFORE
      value: 
       name: envoy.filters.http.lua
       typed_config:
          "@type": "type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua"
          inlineCode: |
            function envoy_on_response(response_handle)
                response_handle:logInfo(" ========= XXXXX ========== ")
                response_handle:headers():add("X-User-Header", "worked")
            end

name

ef-match-listener-name.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
  namespace: istio-system
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: LISTENER
    match:
      listener:
        name: 0.0.0.0_8080
    patch:
      operation: MERGE
      value:
        listener_filters:
        - name: envoy.filters.listener.original_src
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.listener.original_src.v3.OriginalSrc
        - name: envoy.filters.listener.tls_inspector

routeConfiguration

FieldTypeDescriptionRequired
portNumberuint32The service port number or gateway server port number for which this route configuration was generated. If omitted, applies to route configurations for all ports.No
portNamestringApplicable only for GATEWAY context. The gateway server port name for which this route configuration was generated.No
gatewaystringThe Istio gateway config’s namespace/name for which this route configuration was generated. Applies only if the context is GATEWAY. Should be in the namespace/name format. Use this field in conjunction with the portNumber and portName to accurately select the Envoy route configuration for a specific HTTPS server within a gateway config object.No
vhostVirtualHostMatchMatch a specific virtual host in a route configuration and apply the patch to the virtual host.No
namestringRoute configuration name to match on. Can be used to match a specific route configuration by name, such as the internally generated http_proxy route configuration for all sidecars.No

portNumber

ef-match-routeConfiguration-portNumber.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: VIRTUAL_HOST
    match:
      context: SIDECAR_INBOUND
      routeConfiguration:
        portNumber: 9080
        vhost:
          name: inbound|http|9080
    patch:
      operation: REMOVE
  - applyTo: VIRTUAL_HOST
    match:
      context: SIDECAR_INBOUND
      routeConfiguration:
        portNumber: 9080
    patch:
      operation: ADD
      value:
            name: inbound|http|9080
            domains:
            - "*"
            routes:
            - match:
                prefix: "/"
              direct_response:
                status: 200
                body:
                  inline_string: "example body\n"

portName

只对https有效,gateway必须在istio-system中

ef-match-routeConfiguration-portName-https.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: VIRTUAL_HOST
    match:
      context: GATEWAY
      routeConfiguration:
        portName: https
    #    gateway: istio/bookinfo-gateway
    patch:
      operation: MERGE
      value:
            name: "mytest:443"
            domains:
            - "mytest.com"
            routes:
            - match:
                prefix: "/"
              direct_response:
                status: 200
                body:
                  inline_string: "example body\n"

gateway

vhost

FieldTypeDescriptionRequired
namestringThe VirtualHosts objects generated by Istio are named as host:port, where the host typically corresponds to the VirtualService’s host field or the hostname of a service in the registry.No
routeRouteMatchMatch a specific route within the virtual host.No
FieldTypeDescriptionRequired
namestringThe Route objects generated by default are named as default. Route objects generated using a virtual service will carry the name used in the virtual service’s HTTP routes.No
actionActionMatch a route with specific action type.No
NameDescription
ANYAll three route actions
ROUTERoute traffic to a cluster / weighted clusters.
REDIRECTRedirect request.
DIRECT_RESPONSEdirectly respond to a request with specific payload.

name

ef-match-routeConfiguration-vhost-name.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_ROUTE
      match:
        context: SIDECAR_INBOUND
        routeConfiguration:
          portNumber: 9080
          vhost:
            name: inbound|http|9080
      patch:
        operation: MERGE
        value:
          match:
            prefix: /
          direct_response:
                status: 200
                body:
                  inline_string: "example body\n"

action

ANY

ef-match-routeConfiguration-vhost-route-action-ANY.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match-2
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_ROUTE
      match:
        context: SIDECAR_INBOUND
        routeConfiguration:
          portNumber: 9080
          vhost:
            name: inbound|http|9080
            route:
              action: ANY
      patch:
        operation: MERGE
        value:
          match:
            prefix: /
          direct_response:
                status: 200
                body:
                  inline_string: "example body3\n"

ROUTE

ef-match-routeConfiguration-vhost-route-action-ROUTE.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_ROUTE
      match:
        context: SIDECAR_INBOUND
        routeConfiguration:
          portNumber: 9080
          vhost:
            name: inbound|http|9080
            route:
              action: ROUTE
      patch:
        operation: MERGE
        value:
          match:
            prefix: /
          direct_response:
                status: 200
                body:
                  inline_string: "example body33\n"

REDIRECT

ef-match-routeConfiguration-vhost-route-action-REDIRECT.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_ROUTE
      match:
        context: SIDECAR_INBOUND
        routeConfiguration:
          portNumber: 9080
          vhost:
            name: inbound|http|9080
            route:
              action: ANY
      patch:
        operation: MERGE
        value:
          match:
            prefix: /mypage
          redirect:
             host_redirect: "127.0.0.1:9080"
             path_redirect: "/productpage"
             response_code: "PERMANENT_REDIRECT"

ef-match-routeConfiguration-vhost-route-action-REDIRECT-2.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match-2
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_ROUTE
      match:
        context: SIDECAR_INBOUND
        routeConfiguration:
          portNumber: 9080
          vhost:
            name: inbound|http|9080
            route:
              action: REDIRECT
      patch:
        operation: MERGE
        value:
          match:
            prefix: /
          direct_response:
                status: 200
                body:
                  inline_string: "example body11\n"

DIRECT_RESPONSE

先运行ef-match-routeConfiguration-vhost-name.yaml

ef-match-routeConfiguration-vhost-route-action-DIRECT_RESPONSE.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match-2
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_ROUTE
      match:
        context: SIDECAR_INBOUND
        routeConfiguration:
          portNumber: 9080
          vhost:
            name: inbound|http|9080
            route:
              action: DIRECT_RESPONSE
      patch:
        operation: MERGE
        value:
          match:
            prefix: /
          direct_response:
                status: 200
                body:
                  inline_string: "example body2\n"

name

ef-match-routeConfiguration-name.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_ROUTE
      match:
        context: SIDECAR_INBOUND
        routeConfiguration:
          name: inbound|9080||
      patch:
        operation: MERGE
        value:
          match:
            prefix: /
          direct_response:
                status: 200
                body:
                  inline_string: "example body44n"

cluster

FieldTypeDescriptionRequired
portNumberuint32The service port for which this cluster was generated. If omitted, applies to clusters for any port.No
servicestringThe fully qualified service name for this cluster. If omitted, applies to clusters for any service. For services defined through service entries, the service name is same as the hosts defined in the service entry.No
subsetstringThe subset associated with the service. If omitted, applies to clusters for any subset of a service.No
namestringThe exact name of the cluster to match. To match a specific cluster by name, such as the internally generated Passthrough cluster, leave all fields in clusterMatch empty, except the name.No

portNumber

ef-match-cluster-portNumber.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:  
  - applyTo: CLUSTER
    match:
      cluster:
        portNumber: 9080
        name: outbound|9080||productpage.istio.svc.cluster.local
    patch:
      operation: MERGE
      value: 
        connect_timeout: 112s

service

ef-match-cluster-service.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:  
  - applyTo: CLUSTER
    match:
      cluster:
        portNumber: 9080
        service: productpage.istio.svc.cluster.local
        name: outbound|9080||productpage.istio.svc.cluster.local
    patch:
      operation: MERGE
      value: 
        connect_timeout: 113s

subset

ef-match-cluster-subset.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:  
  - applyTo: CLUSTER
    match:
      cluster:
        portNumber: 9080
        service: productpage.istio.svc.cluster.local
        subset: v1
    patch:
      operation: MERGE
      value: 
        connect_timeout: 115s

name

ef-match-cluster-name.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: match
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:  
  - applyTo: CLUSTER
    match:
      cluster:
        name: outbound|9080||productpage.istio.svc.cluster.local
    patch:
      operation: MERGE
      value: 
        connect_timeout: 116s

patch

Patch specifies how the selected object should be modified.

FieldTypeDescriptionRequired
operationOperationDetermines how the patch should be applied.No
valueStructThe JSON config of the object being patched. This will be merged using proto merge semantics with the existing proto in the path.No
filterClassFilterClassDetermines the filter insertion order.No

operation

NameDescription
INVALID
MERGEMerge the provided config with the generated config using proto merge semantics. If you are specifying config in its entirety, use REPLACE instead.
ADDAdd the provided config to an existing list (of listeners, clusters, virtual hosts, network filters, or http filters). This operation will be ignored when applyTo is set to ROUTE_CONFIGURATION, or HTTP_ROUTE.
REMOVERemove the selected object from the list (of listeners, clusters, virtual hosts, network filters, routes, or http filters). Does not require a value to be specified. This operation will be ignored when applyTo is set to ROUTE_CONFIGURATION, or HTTP_ROUTE.
INSERT_BEFOREInsert operation on an array of named objects. This operation is typically useful only in the context of filters or routes, where the order of elements matter. Routes should be ordered based on most to least specific matching criteria since the first matching element is selected. For clusters and virtual hosts, order of the element in the array does not matter. Insert before the selected filter or sub filter. If no filter is selected, the specified filter will be inserted at the front of the list.
INSERT_AFTERInsert operation on an array of named objects. This operation is typically useful only in the context of filters or routes, where the order of elements matter. Routes should be ordered based on most to least specific matching criteria since the first matching element is selected. For clusters and virtual hosts, order of the element in the array does not matter. Insert after the selected filter or sub filter. If no filter is selected, the specified filter will be inserted at the end of the list.
INSERT_FIRSTInsert operation on an array of named objects. This operation is typically useful only in the context of filters or routes, where the order of elements matter. Routes should be ordered based on most to least specific matching criteria since the first matching element is selected. For clusters and virtual hosts, order of the element in the array does not matter. Insert first in the list based on the presence of selected filter or not. This is specifically useful when you want your filter first in the list based on a match condition specified in Match clause.
REPLACEReplace contents of a named filter with new contents. REPLACE operation is only valid for HTTP_FILTER and NETWORK_FILTER. If the named filter is not found, this operation has no effect.

INVALID

MERGE

applyto/ef-listener-filter.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
  namespace: istio-system
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: LISTENER
    patch:
      operation: MERGE
      value:
        listener_filters:
        - name: envoy.filters.listener.original_src
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.listener.original_src.v3.OriginalSrc
        - name: envoy.filters.listener.tls_inspector

ADD

applyto/ef-productpage-add-listener.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
  namespace: istio 
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
  - applyTo: LISTENER
    match:
      context: SIDECAR_INBOUND
    patch:
      operation: ADD
      value:
        name: proxy
        address:
          socket_address:
            protocol: TCP
            address: 0.0.0.0
            port_value: 8083
        filter_chains:
        - filters:
          - name: "envoy.filters.network.http_connection_manager"
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
              stat_prefix: ingress_proxy
              route_config:
                name: route_a
                virtual_hosts:
                - name: envoy_cyz
                  domains:
                  - "*"
                  routes:
                  - match:
                      prefix: "/"
                    route:
                      cluster: cluster123
              http_filters:
              - name: "envoy.filters.http.router
                typed_config:
                  "@type": "type.googleapis.com/envoy.extensions.filters.http.router.v3.Router" 
  - applyTo: CLUSTER
    patch:
      operation: ADD
      value: 
        name: "cluster123"
        type: STATIC
        connect_timeout: 0.5s
        lb_policy: ROUND_ROBIN
        load_assignment:
          cluster_name: cluster123
          endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: 127.0.0.1
                    port_value: 9080

REMOVE

applyto/ef-ingressgateway-http-filter-remove.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
  - applyTo: HTTP_FILTER
    match:
      listener:
        portNumber: 8080
        filterChain:
          filter:
            name: "envoy.filters.network.http_connection_manager"
            subFilter:
              name: "envoy.filters.http.fault"
    patch:
      operation: REMOVE

INSERT_BEFORE

applyto/ef-extension-config.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: productpage
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: SIDECAR_INBOUND
        listener:
          filterChain:
            filter:
              name: "envoy.filters.network.http_connection_manager"
              subFilter:
                name: "envoy.filters.http.router"
      patch:
        operation: INSERT_BEFORE
        value:
          name: istio.attributegen
          config_discovery:
            config_source:
              ads: {}
              initial_fetch_timeout: 0s 
            type_urls: [ "type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm"]       
    - applyTo: EXTENSION_CONFIG
      match:
        context: SIDECAR_INBOUND
      patch:
        operation: ADD
        value:
          name: istio.attributegen
          typed_config:
            "@type": type.googleapis.com/udpa.type.v1.TypedStruct
            type_url: type.googleapis.com/envoy.extensions.filters.http.wasm.v3.Wasm
            value:
              config:
                configuration:
                  "@type": "type.googleapis.com/google.protobuf.StringValue"
                  value: |
                    {
                      "attributes": [
                      {
                        "output_attribute": "istio_responseClass",
                        "match": [
                         {
                             "value": "2xx",
                             "condition": "response.code >= 200 && response.code <= 299"
                         }]
                      },
                      {
                        "output_attribute": "istio_operationId",
                        "match": [
                        {
                            "value": "getoperation",
                            "condition": "request.method == 'GET'"
                        }]
                      },
                      {
                        "output_attribute": "istio_grpcResponseStatus",
                        "match": [
                        {
                            "value": "OK",
                            "condition": "response.grpc_status == 0"
                        }]
                      }]
                    }
                vm_config:
                  runtime: envoy.wasm.runtime.null
                  code:
                    local:
                      inline_string: envoy.wasm.attributegen

INSERT_AFTER

applyto/ef-ingressgateway-http-filter-compression-insert-after.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  namespace: istio-system
  name: apply-to
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: GATEWAY
        listener:
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
              subFilter:
                name: istio.metadata_exchange
      patch:
        operation: INSERT_AFTER
        value:
          name: envoy.filters.http.compressor
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.compressor.v3.Compressor
            response_direction_config:
              common_config:
                min_content_length: 100
                content_type:
                - 'text/html'
            compressor_library:
              name: text_optimized
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.compression.gzip.compressor.v3.Gzip
                memory_level: 3
                window_bits: 10
                compression_level: BEST_COMPRESSION
                compression_strategy: DEFAULT_STRATEGY

INSERT_FIRST

applyto/web-grpc/ef-web-grpc.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: apply-to
spec:
  workloadSelector:
    labels:
      app: web-grpc
  configPatches:
  - applyTo: HTTP_FILTER
    match:
        listener:
          destination_port: 50051
          transport_protocol: "tls"
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
              subFilter:
                name: istio.metadata_exchange
    patch:
        operation: INSERT_BEFORE
        value:           
          name: envoy.filters.http.grpc_web
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.grpc_web.v3.GrpcWeb 

REPLACE

applyto/thrift/envoyfilter-thrift-proxy.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  name: thrift-sample-server
spec:
  configPatches:
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: ${thrift-sample-server-vip}_9090    # sed -i .bak "s/\${thrift-sample-server-vip}/`kubectl get svc thrift-sample-server -n thrift -o=jsonpath='{.spec.clusterIP}'`/" istio/envoyfilter-thrift-proxy.yaml
        filterChain:
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: REPLACE
      value:
        name: envoy.filters.network.thrift_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.thrift_proxy.v3.ThriftProxy
          stat_prefix: "outbound|9090||thrift-sample-server.thrift.svc.cluster.local"
          transport: AUTO_TRANSPORT
          protocol: AUTO_PROTOCOL
          thrift_filters:
          - name: envoy.filters.thrift.router
          route_config:
            routes:
            - match:
                # empty string matches any request method name
                method_name: ""
              route:
                weighted_clusters:
                  clusters:
                    - name: "outbound|9090|v1|thrift-sample-server.istio.svc.cluster.local"
                      weight: 50
                    - name: "outbound|9090|v2|thrift-sample-server.istio.svc.cluster.local"
                      weight: 50
  - applyTo: NETWORK_FILTER
    match:
      listener:
        name: virtualInbound
        filterChain:
          destination_port: 9090
          filter:
            name: "envoy.filters.network.tcp_proxy"
    patch:
      operation: REPLACE
      value:
        name: envoy.filters.network.thrift_proxy
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.thrift_proxy.v3.ThriftProxy
          stat_prefix: inbound|9090||
          transport: AUTO_TRANSPORT
          protocol: AUTO_PROTOCOL
          thrift_filters:
          - name: envoy.filters.thrift.router
          route_config:
            routes:
            - match:
                # empty string matches any request method name
                method_name: ""
              route:
                cluster: inbound|9090||

filterClass

未实现

NameDescription
UNSPECIFIEDControl plane decides where to insert the filter. Do not specify FilterClass if the filter is independent of others.
AUTHNInsert filter after Istio authentication filters.
AUTHZInsert filter after Istio authorization filters.
STATSInsert filter before Istio stats filters.

UNSPECIFIED

ef-patch-filterclass-UNSPECIFIED.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  namespace: istio-system
  name: patch
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: GATEWAY
        listener:
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
      patch:
        operation: ADD
        filterClass: UNSPECIFIED
        value:
          name: envoy.filters.http.compressor
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.compressor.v3.Compressor
            response_direction_config:
              common_config:
                min_content_length: 100
                content_type:
                - 'text/html'
            compressor_library:
              name: text_optimized
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.compression.gzip.compressor.v3.Gzip
                memory_level: 3
                window_bits: 10
                compression_level: BEST_COMPRESSION
                compression_strategy: DEFAULT_STRATEGY

添加到了route后面

Error: terminal filter named envoy.filters.http.router of type envoy.filters.http.router must be the last filter in a http filter chain.

AUTHN

ef-patch-filterclass-AUTHN.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  namespace: istio-system
  name: patch
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: GATEWAY
        listener:
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
      patch:
        operation: ADD
        filterClass: AUTHN
        value:
          name: envoy.filters.http.compressor
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.compressor.v3.Compressor
            response_direction_config:
              common_config:
                min_content_length: 100
                content_type:
                - 'text/html'
            compressor_library:
              name: text_optimized
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.compression.gzip.compressor.v3.Gzip
                memory_level: 3
                window_bits: 10
                compression_level: BEST_COMPRESSION
                compression_strategy: DEFAULT_STRATEGY

AUTHZ

ef-patch-filterclass-AUTHZ.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  namespace: istio-system
  name: patch
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: GATEWAY
        listener:
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
      patch:
        operation: ADD
        filterClass: AUTHZ
        value:
          name: envoy.filters.http.compressor
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.compressor.v3.Compressor
            response_direction_config:
              common_config:
                min_content_length: 100
                content_type:
                - 'text/html'
            compressor_library:
              name: text_optimized
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.compression.gzip.compressor.v3.Gzip
                memory_level: 3
                window_bits: 10
                compression_level: BEST_COMPRESSION
                compression_strategy: DEFAULT_STRATEGY

STATS

ef-patch-filterclass-STATS.yaml

apiVersion: networking.istio.io/v1alpha3
kind: EnvoyFilter
metadata:
  namespace: istio-system
  name: patch
spec:
  workloadSelector:
    labels:
      istio: ingressgateway
  configPatches:
    - applyTo: HTTP_FILTER
      match:
        context: GATEWAY
        listener:
          filterChain:
            filter:
              name: envoy.filters.network.http_connection_manager
      patch:
        operation: ADD
        filterClass: STATS
        value:
          name: envoy.filters.http.compressor
          typed_config:
            "@type": type.googleapis.com/envoy.extensions.filters.http.compressor.v3.Compressor
            response_direction_config:
              common_config:
                min_content_length: 100
                content_type:
                - 'text/html'
            compressor_library:
              name: text_optimized
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.compression.gzip.compressor.v3.Gzip
                memory_level: 3
                window_bits: 10
                compression_level: BEST_COMPRESSION
                compression_strategy: DEFAULT_STRATEGY

wasm

1安装wasme
下载wasme
https://github.com/solo-io/wasm/releases
mkdir .wasme/bin -p
mv wasme-linux-amd64 ./.wasme/bin/wasme
chmod +x .wasme/bin/wasme
vi /etc/profile
export PATH=$HOME/.wasme/bin:$PATH
. /etc/profile
2创建应用
wasme init wasme-test 
3build
 wasme build assemblyscript -t webassemblyhub.io/hxpmark/add-header:v0.0.1 .
4push
wasme push webassemblyhub.io/hxpmark/add-header:v0.0.1 --username hxpmark --password test
5部署deploy
kubectl apply -f https://github.com/solo-io/wasme/releases/latest/download/wasme.io_v1_crds.yaml
kubectl apply -f https://github.com/solo-io/wasme/releases/latest/download/wasme-default.yaml
6编写yaml
envoyfilters/wasm/add-header.yaml
apiVersion: wasme.io/v1
kind: FilterDeployment
metadata:
  labels:
    app: wasme
  name: add-header
  namespace: istio
spec:
  deployment:
    istio:
      kind: Deployment
      labels:
        app: productpage
  filter:
    config:
      '@type': type.googleapis.com/google.protobuf.StringValue
      value: world
    image: webassemblyhub.io/hxpmark/add-header:v0.0.1
 
 kubectl apply -f add-header.yaml -n istio
 
7访问
http://bookinfo.demo:30986/productpage
查看响应头

原理:

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hxpjava1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值