├── .github └── workflows │ └── docker-image.yml ├── .gitignore ├── Cargo.toml ├── Dockerfile ├── LICENSE ├── README.md ├── cmd.sh ├── deploy ├── config_map.yaml ├── ingress.yaml ├── pingora-ingress-ctl-src.yaml ├── pingora_ingress_ctl.yaml └── role.yaml └── src ├── infra ├── mod.rs └── url_tree.rs ├── main.rs ├── pkg ├── ingress.rs ├── mod.rs └── pod.rs └── service ├── config.rs ├── http_proxy.rs └── mod.rs /.github/workflows/docker-image.yml: -------------------------------------------------------------------------------- 1 | name: Docker Image CI 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | jobs: 10 | 11 | build: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | name: Build the Docker image 18 | 19 | - name: Log in to Docker Hub 20 | uses: docker/login-action@v1 21 | with: 22 | username: ${{ secrets.DOCKER_HUB_USERNAME }} 23 | password: ${{ secrets.DOCKER_HUB_TOKEN }} 24 | 25 | - name: Build Docker Image 26 | run: | 27 | fullCommit="${{ github.event.commits[0].id }}" && \ 28 | docker build . --file Dockerfile --tag wdshihaoren/pingora-ingress:"${fullCommit: 0:8}" 29 | 30 | - name: Push Docker Image 31 | run: | 32 | fullCommit="${{ github.event.commits[0].id }}" && \ 33 | docker push wdshihaoren/pingora-ingress:"${fullCommit: 0:8}" 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/ 4 | target/ 5 | 6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 7 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 8 | Cargo.lock 9 | 10 | # These are backup files generated by rustfmt 11 | **/*.rs.bk 12 | 13 | # MSVC Windows builds of rustc generate these, which store debugging information 14 | *.pdb 15 | .idea -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pingora-ingress" 3 | version = "0.1.0" 4 | edition = "2021" 5 | authors = ["Teshin <1443965173@qq.com>"] 6 | repository = "https://github.com/woshihaoren4/pingora-ingress" 7 | keywords = ["pingora","ingress"] 8 | description = "pingora to k8s gateway" 9 | license = "Apache-2.0" 10 | readme = "README.md" 11 | 12 | [dependencies] 13 | wd_log = "0.3.0" 14 | wd_tools = {version = "0.12",features = ["point-free","sync"]} 15 | tokio = {version = "1.30.0",features = ["full"]} 16 | kube = { version = "0.90.0", features = ["runtime", "derive"] } 17 | k8s-openapi = { version = "0.21.1", features = ["v1_24"] } 18 | anyhow = "1.0.82" 19 | futures = "0.3.30" 20 | async-channel = "2.2.1" 21 | serde = { version = "1.0.198",features = ["derive"] } 22 | serde_json = "1.0.116" 23 | async-trait="0.1" 24 | pingora = { version = "0.1", features = [ "lb" ] } 25 | url = "2.5.0" -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | #FROM rust:1.75 as build 2 | #WORKDIR /pingora-ingress 3 | ##COPY build.toml .cargo/config.toml 4 | ##COPY vendor vendor 5 | ##COPY Cargo.toml Cargo.lock ./ 6 | #COPY . . 7 | #RUN cargo build --release 8 | 9 | 10 | FROM frolvlad/alpine-glibc:latest 11 | #FROM alpine:3.16 12 | #ENV RUST_LOG warn 13 | EXPOSE 80 443 14 | WORKDIR /root/ 15 | #COPY --from=build /pingora-ingress/target/release/pingora-ingress . 16 | COPY target/x86_64-unknown-linux-musl/release/pingora-ingress . 17 | 18 | CMD ["./pingora-ingress", "run"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pingora_ingress 2 | 3 | Use the pingora framework as the gateway to k8s. It monitors changes to ingress and updates automatically. 4 | 5 | ## Quick start 6 | 7 | [Reference blog](https://juejin.cn/post/7363484574158815269) 8 | 9 | ## Plan 10 | 11 | This is only an early version, and it will be improved in the future 12 | 13 | ## License 14 | 15 | This project is licensed under the Apache 2.0 general use license. You're free to integrate, fork, and play with this code as you feel fit without consulting the author, as long as you provide proper credit to the author in your works. 16 | 17 | -------------------------------------------------------------------------------- /cmd.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | function build_docker_image() { 4 | echo "start compile application..." 5 | if [ ! -e ".cargo/config.toml" ] ; then 6 | echo "mkdir .cargo;touch .cargo/config.toml" 7 | mkdir .cargo;touch .cargo/config.toml 8 | fi 9 | cargo_config_content=' 10 | [target.x86_64-unknown-linux-musl] 11 | linker = "x86_64-linux-musl-gcc"' 12 | echo "$cargo_config_content" > .cargo/config.toml 13 | echo -e "write cargo config file :\n<---$cargo_config_content\n<---" 14 | 15 | echo "clean bin file:rm target/x86_64-unknown-linux-musl/release/pingora-ingress" 16 | rm target/x86_64-unknown-linux-musl/release/pingora-ingress 17 | 18 | compile_cmd="cargo build --release --target=x86_64-unknown-linux-musl" 19 | echo $compile_cmd 20 | ${compile_cmd} 21 | echo "compile success" 22 | 23 | echo "rm -rf .cargo" 24 | rm -rf .cargo 25 | echo "cargo config file clear success." 26 | 27 | echo "start build image use docker..." 28 | if [ -n "$2" ]; then 29 | version=$2 30 | else 31 | timestamp=$(date +%s%N) 32 | version=${timestamp:2:8} 33 | fi 34 | tag="wdshihaoren/pingora-ingress:$version" 35 | build_cmd="docker build -f ./Dockerfile -t $tag ./" 36 | echo $build_cmd 37 | ${build_cmd} 38 | 39 | echo "docker build success image:$tag" 40 | docker_push_cmd="docker push $tag" 41 | echo $docker_push_cmd 42 | ${docker_push_cmd} 43 | 44 | echo "docker push success" 45 | } 46 | 47 | case $1 in 48 | docker) 49 | build_docker_image "$@" 50 | ;; 51 | run) 52 | cargo run "$@" 53 | ;; 54 | esac 55 | 56 | -------------------------------------------------------------------------------- /deploy/config_map.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: pingora-ingress-ctl-cm 5 | namespace: qa 6 | data: 7 | config.yaml: |- 8 | --- 9 | version: 1 10 | threads: 2 11 | pid_file: /tmp/load_balancer.pid 12 | error_log: /tmp/load_balancer_err.log 13 | upgrade_sock: /tmp/load_balancer.sock -------------------------------------------------------------------------------- /deploy/ingress.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | labels: 5 | control-class: pingora 6 | name: pingora-ingress 7 | namespace: qa 8 | spec: 9 | ingressClassName: pingora 10 | rules: 11 | - host: test.com 12 | http: 13 | paths: 14 | - backend: 15 | service: 16 | name: echo-server-cluster-src 17 | port: 18 | number: 6789 19 | path: /api/v1 20 | pathType: Prefix 21 | -------------------------------------------------------------------------------- /deploy/pingora-ingress-ctl-src.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: pingora-ingress-ctl-src 5 | namespace: qa 6 | spec: 7 | externalTrafficPolicy: Cluster 8 | internalTrafficPolicy: Cluster 9 | ipFamilies: 10 | - IPv4 11 | ipFamilyPolicy: SingleStack 12 | ports: 13 | - name: http 14 | nodePort: 30003 15 | port: 30003 16 | protocol: TCP 17 | targetPort: 30003 18 | selector: 19 | app: pingora-ingress-ctl 20 | sessionAffinity: None 21 | type: NodePort -------------------------------------------------------------------------------- /deploy/pingora_ingress_ctl.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: pingora-ingress-ctl 5 | namespace: qa 6 | spec: 7 | selector: 8 | matchLabels: 9 | app: pingora-ingress-ctl 10 | progressDeadlineSeconds: 600 11 | replicas: 1 12 | revisionHistoryLimit: 10 13 | strategy: 14 | rollingUpdate: 15 | maxSurge: 25% 16 | maxUnavailable: 25% 17 | type: RollingUpdate 18 | template: 19 | metadata: 20 | creationTimestamp: null 21 | labels: 22 | app: pingora-ingress-ctl 23 | spec: 24 | containers: 25 | # - args: 26 | # - '-c' 27 | # - /config/config.yaml 28 | - command: 29 | - ./pingora-ingress 30 | image: wdshihaoren/pingora-ingress:14294998 31 | imagePullPolicy: Always 32 | name: container-0 33 | ports: 34 | - containerPort: 30003 35 | name: http 36 | protocol: TCP 37 | resources: 38 | limits: 39 | cpu: 500m 40 | requests: 41 | cpu: 200m 42 | terminationMessagePath: /dev/termination-log 43 | terminationMessagePolicy: File 44 | # volumeMounts: 45 | # - mountPath: config 46 | # name: config 47 | # readOnly: true 48 | dnsPolicy: ClusterFirst 49 | restartPolicy: Always 50 | schedulerName: default-scheduler 51 | securityContext: {} 52 | serviceAccount: ring-sa 53 | serviceAccountName: ring-sa 54 | terminationGracePeriodSeconds: 30 55 | # volumes: 56 | # - configMap: 57 | # defaultMode: 420 58 | # name: pingora-ingress-ctl-cm 59 | # name: config -------------------------------------------------------------------------------- /deploy/role.yaml: -------------------------------------------------------------------------------- 1 | # 创建sa账户 2 | # kubectl create serviceaccount ring-sa 3 | # kubectl get sa ring-sa 4 | # kubectl describe sa ring-sa 5 | 6 | apiVersion: v1 7 | kind: ServiceAccount 8 | metadata: 9 | name: ring-sa 10 | --- 11 | 12 | kind: ClusterRole 13 | apiVersion: rbac.authorization.k8s.io/v1 14 | metadata: 15 | name: ring-clu-role 16 | rules: 17 | - apiGroups: [""] 18 | resources: ["services","events","pods"] 19 | verbs: ["get","watch","list"] 20 | - apiGroups: ["networking.k8s.io"] 21 | resources: ["ingresses","ingresses/status","ingressclasses"] 22 | verbs: ["get","watch","list"] 23 | --- 24 | 25 | apiVersion: rbac.authorization.k8s.io/v1 26 | kind: ClusterRoleBinding 27 | metadata: 28 | name: ring-clu-role-bind 29 | subjects: 30 | - kind: ServiceAccount 31 | name: ring-sa 32 | namespace: qa 33 | # apiGroup: rbac.authorization.k8s.io 34 | roleRef: 35 | kind: ClusterRole 36 | name: ring-clu-role 37 | apiGroup: rbac.authorization.k8s.io -------------------------------------------------------------------------------- /src/infra/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod url_tree; -------------------------------------------------------------------------------- /src/infra/url_tree.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::sync::Arc; 3 | 4 | #[derive(Clone,Debug)] 5 | pub struct Node{ 6 | path:String, 7 | data:Option>, 8 | next:HashMap> 9 | } 10 | 11 | impl Default for Node { 12 | fn default() -> Self { 13 | Self{path:String::new(),data:None,next:HashMap::new()} 14 | } 15 | } 16 | 17 | impl Node{ 18 | pub fn insert_path(&mut self,path:&str,data:Arc){ 19 | if path == ""{ 20 | self.data = Some(data); 21 | return; 22 | } 23 | let ps = path.split('/').map(|x|if x == ""{ "*" }else { x}).rev().collect::>(); 24 | self.insert(ps,data); 25 | } 26 | pub fn find_by_path(&self,path:&str)->Option>{ 27 | let ps = path.split('/').rev().collect::>(); 28 | self.find(ps) 29 | } 30 | pub fn insert(&mut self, mut ps:Vec<&str>, data:Arc){ 31 | let path = if let Some(s) = ps.pop(){ 32 | s 33 | }else{ 34 | return; 35 | }; 36 | //先判断路径是否匹配 37 | if self.path.is_empty() { 38 | self.path = path.to_string(); 39 | }else if self.path.as_str() == path { 40 | 41 | }else{ 42 | panic!("Url.Tree.Node.insert unknown path:{}",path); 43 | } 44 | //看下一个 45 | let next = if let Some(p) = ps.last(){ 46 | self.next.get_mut(*p) 47 | }else{//不存在下一个,则修改当前 48 | self.data = Some(data); 49 | return; 50 | }; 51 | if let Some(next) = next{ 52 | //存在下一个则继续判断 53 | next.insert(ps,data); 54 | }else{ 55 | //不存在则新建 56 | let mut next = Node::::default(); 57 | next.insert(ps, data); 58 | self.next.insert(next.path.clone(),next); 59 | } 60 | } 61 | pub fn find(&self,mut ps:Vec<&str>)->Option>{ 62 | let path = if let Some(s) = ps.pop(){ 63 | s 64 | }else{ 65 | return None 66 | }; 67 | 68 | if self.path == "*" { 69 | 70 | }else if path != self.path { 71 | return self.data.clone() 72 | } 73 | 74 | if let Some(p) = ps.last(){ 75 | if let Some(next) = self.next.get(*p){ 76 | let res = next.find(ps); 77 | if res.is_some() { 78 | return res 79 | } 80 | }else if let Some(next ) = self.next.get("*"){ 81 | let res = next.find(ps); 82 | if res.is_some() { 83 | return res 84 | } 85 | } 86 | } 87 | return self.data.clone() 88 | } 89 | } 90 | 91 | 92 | #[cfg(test)] 93 | mod test{ 94 | use std::sync::Arc; 95 | use crate::infra::url_tree::Node; 96 | 97 | #[test] 98 | fn test_node(){ 99 | let mut root = Node::default(); 100 | 101 | root.insert_path("/api/v1/task/create",Arc::new("avtc")); 102 | root.insert_path("/api/v1/task/delete",Arc::new("avtd")); 103 | root.insert_path("/api/v2/update",Arc::new("avu")); 104 | root.insert_path("/api/v2/",Arc::new("av2")); 105 | root.insert_path("/api",Arc::new("api")); 106 | root.insert_path("/",Arc::new("default")); 107 | root.insert_path("",Arc::new("null")); 108 | 109 | let res = root.find_by_path("/api/v1/task/create").unwrap(); 110 | assert_eq!(*res,"avtc"); 111 | 112 | let res = root.find_by_path("/api/v1/task/create/1234").unwrap(); 113 | assert_eq!(*res,"avtc"); 114 | 115 | let res = root.find_by_path("/api/v1/task").unwrap(); 116 | assert_eq!(*res,"api"); 117 | 118 | let res = root.find_by_path("/api/v2/task/update").unwrap(); 119 | assert_eq!(*res,"av2"); 120 | 121 | let res = root.find_by_path("/api/v2").unwrap(); 122 | assert_eq!(*res,"api"); 123 | 124 | let res = root.find_by_path("/api").unwrap(); 125 | assert_eq!(*res,"api"); 126 | 127 | let res = root.find_by_path("/").unwrap(); 128 | assert_eq!(*res,"default"); 129 | 130 | let res = root.find_by_path("").unwrap(); 131 | assert_eq!(*res,"null"); 132 | 133 | root.insert_path("/api/v2/",Arc::new("api2")); 134 | let res = root.find_by_path("/api/v2/xxx").unwrap(); 135 | assert_eq!(*res,"api2"); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod pkg; 2 | mod infra; 3 | mod service; 4 | 5 | fn main(){ 6 | wd_log::log_info_ln!("start work..."); 7 | service::start_pingora(); 8 | wd_log::log_info_ln!("application over!!!"); 9 | } 10 | -------------------------------------------------------------------------------- /src/pkg/ingress.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use async_channel::Receiver; 3 | use k8s_openapi::api::networking::v1::{HTTPIngressPath, Ingress, IngressRule, IngressServiceBackend, IngressTLS}; 4 | use kube::{Api, Client}; 5 | use futures::prelude::*; 6 | use kube::runtime::{watcher, WatchStreamExt}; 7 | use kube::runtime::watcher::{ Event}; 8 | use serde::{Deserialize, Serialize}; 9 | use wd_tools::PFSome; 10 | 11 | const INGRESS_CLASS_NAME_PINGORA:&'static str = "pingora"; 12 | 13 | #[derive(Debug,Clone,Serialize,Deserialize)] 14 | pub struct IngressEvent{ 15 | pub ty:u8, //1:init 2:update 3:delete 16 | pub default_backend:Option, 17 | pub hosts:Vec, 18 | pub sni:IngSni, 19 | #[serde(skip)] 20 | pub ing:Option>, 21 | } 22 | impl IngressEvent{ 23 | pub fn init(mut self)->Self{ 24 | match self.ing.as_ref().unwrap() { 25 | Event::Applied(ref k) => { 26 | let (default_backend,hosts,sni) = IngressEvent::ing_to_host_backend(k); 27 | self.ty = 2; 28 | self.default_backend = default_backend; 29 | self.hosts = hosts; 30 | self.sni = sni; 31 | }, 32 | Event::Deleted(ref k) => { 33 | let (default_backend,hosts,sni) = IngressEvent::ing_to_host_backend(k); 34 | self.ty = 3; 35 | self.default_backend = default_backend; 36 | self.hosts = hosts; 37 | self.sni = sni; 38 | }, 39 | Event::Restarted(ref k) => { 40 | let mut default_backend = None; 41 | let mut hosts = vec![]; 42 | let mut sni = IngSni::default(); 43 | for i in k.iter(){ 44 | let (db, mut hs,is) = IngressEvent::ing_to_host_backend(i); 45 | if db.is_some() { 46 | default_backend = db; 47 | } 48 | hosts.append(&mut hs); 49 | sni.append(is); 50 | } 51 | self.ty = 1; 52 | self.default_backend = default_backend; 53 | self.hosts = hosts; 54 | self.sni = sni; 55 | }, 56 | }; 57 | 58 | self 59 | } 60 | pub fn ing_to_host_backend(ing:&Ingress)->(Option,Vec,IngSni){ 61 | let i = if let Some(ref i) = ing.spec{ 62 | i 63 | }else{ 64 | return (None,vec![],IngSni::default()) 65 | }; 66 | if let Some(ref n) = i.ingress_class_name { 67 | if n != INGRESS_CLASS_NAME_PINGORA { 68 | return (None,vec![],IngSni::default()) 69 | } 70 | } 71 | let default_backend = if let Some(ref d) = i.default_backend{ 72 | if let Some(ref s) = d.service{Some(IngRule::from(s))}else{None} 73 | }else{None}; 74 | let mut hosts = vec![]; 75 | if let Some(ref i) = i.rules{ 76 | for i in i.iter(){ 77 | let ih = IngHost::from(i); 78 | if !ih.rules.is_empty() { 79 | hosts.push(ih); 80 | } 81 | } 82 | } 83 | let sni = if let Some(ref s) = i.tls{ 84 | IngSni::from_ingress_tls(s) 85 | }else{ 86 | IngSni::default() 87 | }; 88 | (default_backend,hosts,sni) 89 | } 90 | pub fn json(&self)->String{ 91 | serde_json::to_string(self).unwrap_or_else(|e| { 92 | wd_log::log_error_ln!("IngressEvent json error:{}",e); 93 | "".to_string() 94 | }) 95 | } 96 | } 97 | impl From> for IngressEvent { 98 | fn from(value: Event) -> Self { 99 | let ie = IngressEvent{ 100 | ty: 0, 101 | default_backend: None, 102 | hosts: vec![], 103 | sni: Default::default(), 104 | ing: Some(value), 105 | }; 106 | ie.init() 107 | } 108 | } 109 | #[derive(Default,Debug,Clone,Serialize,Deserialize)] 110 | pub struct IngSni{ 111 | pub sni : HashMap 112 | } 113 | impl IngSni{ 114 | pub fn from_ingress_tls(tls:&Vec)->IngSni{ 115 | let mut sni = HashMap::new(); 116 | for i in tls.iter(){ 117 | let secret = if let Some(ref s) = i.secret_name { 118 | s.clone() 119 | }else{ 120 | continue 121 | }; 122 | if let Some(ref hs) = i.hosts{ 123 | for j in hs.iter(){ 124 | sni.insert(j.clone(),secret.clone()); 125 | } 126 | } 127 | } 128 | Self{sni} 129 | } 130 | pub fn append(&mut self,other:Self){ 131 | self.sni.extend(other.sni); 132 | } 133 | } 134 | 135 | #[derive(Default,Debug,Clone,Serialize,Deserialize)] 136 | pub struct IngHost{ 137 | pub host:String, 138 | pub rules:Vec, 139 | } 140 | 141 | impl From<&IngressRule> for IngHost { 142 | fn from(value: &IngressRule) -> Self { 143 | let host = if let Some(ref s) = value.host{ 144 | s.clone() 145 | }else{"".to_string()}; 146 | let mut rules = vec![]; 147 | if let Some(ref list) = value.http{ 148 | for p in list.paths.iter(){ 149 | if let Some(r) = IngRule::new_from_path(p){ 150 | rules.push(r) 151 | } 152 | } 153 | } 154 | Self{host,rules} 155 | } 156 | } 157 | 158 | #[derive(Default,Debug,Clone,Serialize,Deserialize)] 159 | pub struct IngRule{ 160 | pub path: String, 161 | pub ty:u8, //1:prefix 2:exact 3:specific 162 | pub backend: String, 163 | pub port:i32, 164 | } 165 | 166 | impl From<&IngressServiceBackend> for IngRule { 167 | fn from(value: &IngressServiceBackend) -> Self { 168 | let mut this = Self{ 169 | path: "".to_string(), 170 | ty: 1, 171 | backend: value.name.clone(), 172 | port: 80, 173 | }; 174 | if let Some(ref i) = value.port{ 175 | if let Some(i) = i.number{ 176 | this.port = i 177 | } 178 | } 179 | this 180 | } 181 | } 182 | impl IngRule{ 183 | pub fn new_from_path(value:&HTTPIngressPath)->Option{ 184 | let ty = match value.path_type.as_str().to_lowercase().as_str() { 185 | "prefix" => 1u8, 186 | "exact" => 2u8, 187 | "implementationspecific" => 3u8, 188 | _ => 99u8, 189 | }; 190 | let path = value.path.clone().unwrap_or("".to_string()); 191 | let mut this = if let Some(ref s) = value.backend.service{ 192 | IngRule::from(s) 193 | }else{ 194 | return None 195 | }; 196 | this.ty = ty; 197 | this.path = path; 198 | this.some() 199 | } 200 | } 201 | 202 | #[derive(Default,Debug,Clone)] 203 | pub struct WatchIngress{ 204 | namespace:Option, 205 | selector_labels:Option, 206 | } 207 | 208 | impl WatchIngress { 209 | #[allow(dead_code)] 210 | pub fn from_namespace>(ns:S)->Self{ 211 | let namespace = Some(ns.into()); 212 | Self{namespace, 213 | .. Default::default()} 214 | } 215 | pub fn add_label_selector(mut self,key:&str,value:&str)->Self{ 216 | self.selector_labels = match self.selector_labels { 217 | None => Some(format!("{}={}",key,value)), 218 | Some(s) => {Some(format!("{},{}={}",s,key,value))} 219 | };self 220 | } 221 | pub async fn start_watch(&self)-> anyhow::Result> { 222 | let (sender,receiver) = async_channel::bounded(8); 223 | 224 | 225 | let client = Client::try_default().await?; 226 | let api:Api = match self.namespace { 227 | None =>{ 228 | Api::all(client) 229 | } , 230 | Some(ref s) => Api::namespaced(client,s) 231 | }; 232 | 233 | let mut wc = watcher::Config::default(); 234 | if let Some(ref s) = self.selector_labels{ 235 | wc = wc.labels(s) 236 | }; 237 | let mut watch = watcher(api, wc) 238 | // .applied_objects() 239 | .default_backoff().boxed(); 240 | tokio::spawn(async move { 241 | while let Some(result) = watch.next().await{ 242 | let event = match result{ 243 | Ok(o) => o, 244 | Err(e) => { 245 | wd_log::log_error_ln!("watch ingress event error:{:?}",e); 246 | continue 247 | } 248 | }; 249 | let event = IngressEvent::from(event); 250 | if let Err(e) = sender.send(event).await{ 251 | wd_log::log_error_ln!("watch ingress event to sender error:{:?}",e) 252 | } 253 | } 254 | }); 255 | // let mut watch = watcher(api, wc).boxed(); 256 | // #[allow(irrefutable_let_patterns)] 257 | // while let res = watch.try_next().await { 258 | // if let Ok(Some(event)) = res{ 259 | // wd_log::log_info_ln!("event-->{:?}",event); 260 | // }else{ 261 | // wd_log::log_warn_ln!("watch unknown error"); 262 | // } 263 | // } 264 | Ok(receiver) 265 | } 266 | 267 | } -------------------------------------------------------------------------------- /src/pkg/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod ingress; 2 | pub mod pod; -------------------------------------------------------------------------------- /src/pkg/pod.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::fs::read_to_string; 3 | use k8s_openapi::api::core::v1::Pod; 4 | use kube::{Api, Client}; 5 | use wd_tools::PFErr; 6 | 7 | pub struct PodApi{ 8 | 9 | } 10 | 11 | impl PodApi{ 12 | pub async fn get_self_pod_info()->anyhow::Result{ 13 | let pod_name = PodApi::pod_name(); 14 | if pod_name.is_empty() { 15 | return anyhow::anyhow!("pod name not found").err() 16 | }else{ 17 | wd_log::log_debug_ln!("pod name[{}]",pod_name); 18 | } 19 | let namespace = PodApi::namespace(); 20 | if namespace.is_empty(){ 21 | return anyhow::anyhow!("namespace not found").err() 22 | }else{ 23 | wd_log::log_debug_ln!("namespace name[{}]",namespace); 24 | } 25 | 26 | let client = Client::try_default().await?; 27 | let api = Api::::namespaced(client,namespace.as_str()); 28 | 29 | let pod = api.get(pod_name.as_str()).await?; 30 | 31 | Ok(pod) 32 | } 33 | 34 | pub fn pod_name()->String{ 35 | if let Ok(n) = env::var("HOSTNAME") { 36 | return n 37 | } 38 | if let Ok(n) = read_to_string("/etc/hostname"){ 39 | return n.replace("\n","") 40 | } 41 | "".into() 42 | } 43 | pub fn namespace()->String{ 44 | if let Ok(n) = env::var("NAMESPACE") { 45 | return n 46 | } 47 | if let Ok(n) = read_to_string("/run/secrets/kubernetes.io/serviceaccount/namespace"){ 48 | return n.replace("\n","") 49 | } 50 | "".into() 51 | } 52 | } 53 | 54 | 55 | #[cfg(test)] 56 | mod test{ 57 | use k8s_openapi::api::core::v1::{Namespace, Pod}; 58 | use kube::{Api, Client}; 59 | 60 | #[tokio::test] 61 | pub async fn test_pod_info(){ 62 | let client = Client::try_default().await.unwrap(); 63 | 64 | let api = Api::::namespaced(client,"qa"); 65 | 66 | let pod = api.get("pingora-ingress-ctl-f4bd748c8-p7khx").await.unwrap(); 67 | 68 | println!("pod=>{:?}",pod); 69 | } 70 | } -------------------------------------------------------------------------------- /src/service/config.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use crate::pkg::pod; 3 | 4 | #[derive(Debug,Serialize,Deserialize)] 5 | pub struct Config{ 6 | #[serde(default="Config::port_df")] 7 | pub port:i32, 8 | #[serde(default="String::default")] 9 | pub log_level:String, 10 | } 11 | 12 | impl Config{ 13 | fn port_df()->i32{ 14 | 30666 15 | } 16 | pub fn json(&self)->String{ 17 | serde_json::to_string(self).unwrap() 18 | } 19 | } 20 | 21 | 22 | impl Config{ 23 | pub async fn from_pod()->Self{ 24 | let mut cfg = serde_json::from_str::("{}").unwrap(); 25 | let pod = match pod::PodApi::get_self_pod_info().await { 26 | Ok(o) => o, 27 | Err(e) => { 28 | wd_log::log_error_ln!("load config failed:{:?}",e); 29 | return cfg 30 | } 31 | }; 32 | if let Some(ref an) = pod.metadata.annotations { 33 | if let Some(level) = an.get("pga-log-level"){ 34 | cfg.log_level = level.to_string(); 35 | } 36 | }; 37 | if let Some(ref spec) = pod.spec{ 38 | for i in spec.containers.iter(){ 39 | if let Some(ref ports) = i.ports{ 40 | for j in ports.iter(){ 41 | if let Some(ref n) = j.name{ 42 | if n=="http"{ 43 | cfg.port = j.container_port 44 | } 45 | } 46 | } 47 | } 48 | } 49 | } 50 | cfg 51 | } 52 | } -------------------------------------------------------------------------------- /src/service/http_proxy.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::sync::Arc; 3 | use async_channel::Receiver; 4 | use wd_tools::sync::Acl; 5 | use crate::infra::url_tree::Node; 6 | use crate::pkg::ingress::{IngressEvent, IngRule}; 7 | use pingora::prelude::*; 8 | use wd_tools::PFArc; 9 | 10 | #[derive(Default)] 11 | pub struct HttpProxyControl{ 12 | router : Acl>, 13 | } 14 | impl HttpProxyControl { 15 | pub async fn new_ing_event_watch(recv:Receiver)->Self{ 16 | let router = Acl::default(); 17 | let rt = router.clone(); 18 | tokio::spawn(async move{ 19 | while let Ok(e) = recv.recv().await{ 20 | wd_log::log_info_ln!("watch ingress event=>{}",e.json()); 21 | HttpProxyControl::ing_event_to_router(e,rt.clone()); 22 | } 23 | wd_log::log_info_ln!("IngressEvent receiver channel over"); 24 | }); 25 | Self{router} 26 | } 27 | fn ing_event_to_router(ing:IngressEvent,acl:Acl>){ 28 | let IngressEvent{ 29 | ty, default_backend, hosts, sni, .. 30 | } = ing; 31 | let mut map = (*acl.share()).clone(); 32 | match ty { 33 | 1 | 2=>{ //init | update 34 | if let Some(db) = default_backend { 35 | map.insert("*".into(), Router::from_default_backend(db)); 36 | } 37 | for i in hosts{ 38 | if !map.contains_key(i.host.as_str()) { 39 | map.insert(i.host.clone(),Router::from_host(i.host.clone())); 40 | } 41 | let router = map.get_mut(i.host.as_str()).unwrap(); 42 | wd_log::log_debug_ln!("update host:[{}]",i.host.as_str()); 43 | router.update_from_ing_rule(i.rules); 44 | } 45 | } 46 | 3=>{ //delete 47 | if let Some(db) = default_backend { 48 | wd_log::log_debug_ln!("delete default_backend:[{}]",db.backend); 49 | map.remove("*"); 50 | } 51 | for i in hosts{ 52 | wd_log::log_debug_ln!("delete host:[{}]",i.host.as_str()); 53 | map.remove(i.host.as_str()); 54 | } 55 | } 56 | _=>{ 57 | wd_log::log_info_ln!("unknown ingress event type:{:?}",ty); 58 | return; 59 | } 60 | } 61 | for (host,i) in sni.sni{ 62 | if let Some(router) = map.get_mut(host.as_str()){ 63 | router.sni = i; 64 | } 65 | } 66 | acl.update(move |_|{ 67 | map 68 | }); 69 | } 70 | } 71 | 72 | #[derive(Default,Clone,Debug)] 73 | pub struct Router{ 74 | pub sni:String, 75 | pub host:String, 76 | pub default_backend:Option>, 77 | pub exact:HashMap>, 78 | pub prefix:Node, 79 | } 80 | #[derive(Clone,Debug)] 81 | pub struct RouterNode{ 82 | pub backend: String, 83 | pub port:i32, 84 | } 85 | impl From for RouterNode{ 86 | fn from(value: IngRule) -> Self { 87 | let backend = value.backend; 88 | let port = value.port; 89 | Self{backend,port} 90 | } 91 | } 92 | 93 | impl RouterNode { 94 | pub fn new>(backend:B,port:i32)->Self{ 95 | let backend = backend.into(); 96 | Self{backend,port} 97 | } 98 | 99 | } 100 | impl Router{ 101 | pub fn from_host>(host:S)->Self{ 102 | let host = host.into(); 103 | Self{host,..Default::default()} 104 | } 105 | pub fn from_default_backend(ir:IngRule)->Self{ 106 | let mut rt = Router::default(); 107 | rt.default_backend = Some(Arc::new(RouterNode::from(ir))); 108 | rt 109 | } 110 | pub fn update_from_ing_rule(&mut self,rules:Vec){ 111 | for rule in rules{ 112 | let IngRule{ path, backend, port,ty } = rule; 113 | match ty { 114 | 1=>{ //prefix 115 | wd_log::log_debug_ln!("insert prefix rule: path[{}] service[{}] port[{}]",path,backend,port); 116 | self.prefix.insert_path(path.as_str(),RouterNode::new(backend,port).arc()); 117 | } 118 | 2=>{ //exact 119 | wd_log::log_debug_ln!("insert exact rule: path[{}] service[{}] port[{}]",path,backend,port); 120 | self.exact.insert(path,RouterNode::new(backend,port).arc()); 121 | } 122 | _=>{ 123 | wd_log::log_warn_ln!("RouterNode do not support specific path:{}",path); 124 | } 125 | } 126 | } 127 | } 128 | } 129 | 130 | #[derive(Default)] 131 | pub struct HttpProxyCtx{ 132 | service:Option>, 133 | sni:String, 134 | } 135 | 136 | #[async_trait::async_trait] 137 | impl ProxyHttp for HttpProxyControl{ 138 | type CTX = HttpProxyCtx; 139 | 140 | fn new_ctx(&self) -> Self::CTX { 141 | HttpProxyCtx::default() 142 | } 143 | 144 | 145 | 146 | 147 | async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Self::CTX) -> Result> { 148 | let peer = if let Some(ref s) = ctx.service { 149 | Box::new(HttpPeer::new((s.backend.as_str(),s.port as u16), !ctx.sni.is_empty(), ctx.sni.clone())) 150 | }else{ 151 | return Error::err(ErrorType::HTTPStatus(404)); 152 | }; 153 | 154 | // let peer = Box::new(HttpPeer::new(("1.1.1.1",80u16), true, "one.one.one.one".to_string())); 155 | Ok(peer) 156 | } 157 | 158 | async fn request_filter(&self, session: &mut Session, ctx: &mut Self::CTX) -> Result where Self::CTX: Send + Sync { 159 | let mut host = if let Some(s) = session.req_header().headers.get("Host") { 160 | if let Ok(s) = s.to_str(){ 161 | s 162 | }else{ 163 | return Error::err(ErrorType::InvalidHTTPHeader) 164 | } 165 | }else { 166 | return Error::err(ErrorType::InvalidHTTPHeader) 167 | }; 168 | if host.contains(":") { 169 | let list:Vec<&str> = host.split(":").collect(); 170 | host = list[0]; 171 | } 172 | let path = session.req_header().uri.path(); 173 | 174 | wd_log::log_debug_ln!("request host[{}] path[{}]",host,path); 175 | 176 | let routers = self.router.share(); 177 | for i in 0..100{ 178 | if i != 0 { 179 | let list:Vec<&str> = host.splitn(1,'.').collect(); 180 | if list.len() == 1 || list.is_empty() { 181 | break 182 | } 183 | host = list[1]; 184 | } 185 | if let Some(r) = routers.get(host) { 186 | ctx.sni = r.sni.clone(); 187 | if let Some(s) = r.exact.get(path) { 188 | ctx.service = Some(s.clone()); 189 | }else if let Some(s) = r.prefix.find_by_path(path){ 190 | ctx.service = Some(s); 191 | } 192 | break 193 | } 194 | } 195 | //尝试兜底 196 | if ctx.service.is_none() { 197 | if let Some(r) = routers.get("*") { 198 | ctx.sni = r.sni.clone(); 199 | ctx.service = r.default_backend.clone(); 200 | } 201 | } 202 | //如果没找到 203 | if ctx.service.is_none(){ 204 | return Error::err(ErrorType::HTTPStatus(404)); 205 | } 206 | Ok(false) 207 | } 208 | } -------------------------------------------------------------------------------- /src/service/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod http_proxy; 2 | mod config; 3 | 4 | use pingora::prelude::*; 5 | use http_proxy::*; 6 | use crate::pkg::ingress; 7 | use crate::service::config::Config; 8 | 9 | pub fn start_pingora(){ 10 | //监听pod 11 | let rt = tokio::runtime::Builder::new_multi_thread() 12 | .enable_all() 13 | .build().unwrap(); 14 | let (hpc,cfg) = rt.block_on(async { 15 | let recv = ingress::WatchIngress::default() 16 | .add_label_selector("control-class", "pingora") 17 | .start_watch().await.unwrap(); 18 | let hpc = HttpProxyControl::new_ing_event_watch(recv).await; 19 | let cfg = Config::from_pod().await; 20 | (hpc,cfg) 21 | }); 22 | 23 | wd_log::log_info_ln!("config=>{}",cfg.json()); 24 | 25 | let mut my_server = Server::new(Some(Opt::default())).unwrap(); 26 | my_server.bootstrap(); 27 | 28 | let mut gateway = http_proxy_service(&my_server.configuration,hpc); 29 | gateway.add_tcp(format!("0.0.0.0:{}",cfg.port).as_str()); 30 | 31 | my_server.add_service(gateway); 32 | 33 | my_server.run_forever(); 34 | } --------------------------------------------------------------------------------