├── .dockerignore ├── .gitignore ├── .vscode └── settings.json ├── DEVELOPMENT.md ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── VERSION ├── assets └── images │ └── sr_operator.png ├── controller ├── api │ ├── schema.py │ └── v1 │ │ └── types.py ├── config │ ├── crd.yaml │ ├── manager.yaml │ ├── namespace.yaml │ └── rbac │ │ ├── role.yaml │ │ ├── role_binding.yaml │ │ └── service_account.yaml ├── constants.py ├── generate_api.py ├── kustomization.yaml ├── static-route-handler.py └── utils.py ├── examples ├── curl-test.yaml ├── static-route-ifconfig.me.yaml └── static-route-ipinfo.io.yaml ├── pytest.ini ├── releases └── v1 │ └── k8s-staticroute-operator-v1.0.0.yaml ├── requirements-dev.txt ├── requirements.txt └── tests ├── manifests └── static-route-test.yaml └── test_operator.py /.dockerignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | **/__pycache__/ 3 | **/*.py[cod] 4 | 5 | # Pytest 6 | **/.pytest_cache/ 7 | 8 | # Virtualenv 9 | **/.venv*/ 10 | 11 | # K8S manifests 12 | **/config/ 13 | 14 | # YAML 15 | **/*.yaml 16 | 17 | # Generator script(s) 18 | **/generate_api.py 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # Pytest 6 | .pytest_cache/ 7 | 8 | # Virtualenv 9 | .venv*/ 10 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.formatting.provider": "black" 3 | } 4 | -------------------------------------------------------------------------------- /DEVELOPMENT.md: -------------------------------------------------------------------------------- 1 | # Static Routes Controller Development 2 | 3 | TODO. 4 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.10-alpine 2 | 3 | WORKDIR /controller 4 | COPY requirements.txt controller/ ./ 5 | RUN apk add libcap && \ 6 | pip install -r "requirements.txt" && \ 7 | # python interpreter needs NET_ADMIN privileges to alter routes on the host 8 | setcap 'cap_net_admin+ep' $(readlink -f $(which python)) 9 | USER 405 10 | ENTRYPOINT [ "kopf", "run", "--all-namespaces", "--verbose", "static-route-handler.py"] 11 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | ################################################ 2 | # # 3 | # Kubernetes Static Routes Operator Makefile # 4 | # # 5 | ################################################ 6 | 7 | 8 | # Project related stuff 9 | PROJECT_NAME ?= k8s-staticroute-operator 10 | ORGANIZATION ?= digitalocean 11 | VERSION_MANIFEST ?= VERSION 12 | PROJECT_VERSION ?= $(shell cat $(VERSION_MANIFEST)) 13 | PROJECT_MAJOR_VERSION ?= $(shell echo $(PROJECT_VERSION) | cut -f1 -d.) 14 | RELEASES_FOLDER ?= releases 15 | CONTROLLER_PATH ?= controller 16 | CONTROLLER_CFG_PATH ?= $(CONTROLLER_PATH)/config 17 | API_GENERATOR_SCRIPT ?= $(CONTROLLER_PATH)/generate_api.py 18 | OPERATOR_RELEASE_MANIFEST ?= $(RELEASES_FOLDER)/v$(PROJECT_MAJOR_VERSION)/$(PROJECT_NAME)-v$(PROJECT_VERSION).yaml 19 | 20 | # Commands related stuff 21 | KUBECTL_CMD ?= kubectl 22 | MKDIR_CMD ?= mkdir 23 | RM_CMD ?= rm 24 | AWK_CMD ?= awk 25 | SED_CMD ?= sed 26 | PYTHON3_CMD ?= python3 27 | PIP3_CMD ?= pip3 28 | VIRTUALENV_CMD ?= virtualenv 29 | PYTEST_CMD ?= pytest 30 | KOPF_CMD ?= kopf 31 | 32 | # Python related stuff 33 | VENV_FOLDER ?= .venv 34 | PROJ_REQUIREMENTS_FILE ?= requirements.txt 35 | DEV_REQUIREMENTS_FILE ?= requirements-dev.txt 36 | 37 | # Docker related stuff 38 | CONTROLLER_IMAGE_TAG ?= $(ORGANIZATION)/$(PROJECT_NAME):v$(PROJECT_VERSION) 39 | 40 | # Kubernetes related stuff 41 | CURRENT_K8S_CLUSTER ?= $(shell $(KUBECTL_CMD) config current-context) 42 | 43 | 44 | .DEFAULT_GOAL := help 45 | 46 | .ONESHELL: 47 | ENV_PREFIX=$(shell python3 -c "if __import__('pathlib').Path('$(VENV_FOLDER)/bin/$(PIP3_CMD)').exists(): print('$(VENV_FOLDER)/bin/')") 48 | 49 | 50 | .PHONY: install-venv-package 51 | install-venv-package: 52 | @echo "Installing virtualenv Python package ..." 53 | @$(PIP3_CMD) install virtualenv 54 | 55 | .PHONY: create-venv 56 | create-venv: install-venv-package 57 | @echo "Creating $(VENV_FOLDER) virtual environment ..." 58 | @$(VIRTUALENV_CMD) $(VENV_FOLDER) 59 | 60 | .PHONY: dev-install 61 | dev-install: create-venv ## Install dev dependencies using pip. 62 | @echo "Installing project dependencies into $(VENV_FOLDER) virtual environment ..." 63 | @$(ENV_PREFIX)$(PIP3_CMD) install -r $(DEV_REQUIREMENTS_FILE) 64 | 65 | .PHONY: install 66 | install: create-venv ## Install project dependencies (release). 67 | @echo "Installing project dependencies into $(VENV_FOLDER) virtual environment ..." 68 | @$(ENV_PREFIX)$(PIP3_CMD) install -r $(PROJ_REQUIREMENTS_FILE) 69 | 70 | .PHONY: manifests 71 | manifests: install ## Generate CRD manifests. 72 | @echo "Generating CRD manifests into $(CONTROLLER_CFG_PATH) for project version $(PROJECT_VERSION) ..." 73 | @$(ENV_PREFIX)$(PYTHON3_CMD) $(API_GENERATOR_SCRIPT) --output-path $(CONTROLLER_CFG_PATH) 74 | 75 | .PHONY: release 76 | release: manifests ## Create release artifacts for the project. 77 | @echo "Generating new release manifests for project version $(PROJECT_VERSION) ..." 78 | @$(MKDIR_CMD) -p $(RELEASES_FOLDER)/v$(PROJECT_MAJOR_VERSION) 79 | @$(KUBECTL_CMD) kustomize $(CONTROLLER_PATH) > $(OPERATOR_RELEASE_MANIFEST) 80 | @$(SED_CMD) -i 's//v$(PROJECT_VERSION)/g' $(OPERATOR_RELEASE_MANIFEST) 81 | 82 | .PHONY: docker-image 83 | docker-image: release ## Build controller Docker image for the project. 84 | @echo "Building operator Docker image with version $(PROJECT_VERSION) ..." 85 | @docker build -t $(CONTROLLER_IMAGE_TAG) . 86 | 87 | .PHONY: docker-push 88 | docker-push: docker-image ## Push controller Docker image to Docker Hub. 89 | @echo "Pushing operator Docker image $(CONTROLLER_IMAGE_TAG) to Docker Hub ..." 90 | @docker push $(CONTROLLER_IMAGE_TAG) 91 | 92 | .PHONY: deploy 93 | deploy: docker-push ## Deploy operator to current Kubernetes cluster (uses kubectl current context). 94 | @echo "Deploying $(OPERATOR_RELEASE_MANIFEST) to $(CURRENT_K8S_CLUSTER) ..." 95 | @$(KUBECTL_CMD) apply -f $(OPERATOR_RELEASE_MANIFEST) 96 | 97 | .PHONY: test 98 | test: dev-install ## Test the project using PyTest. 99 | @echo "Starting Pytests for the static routes operator ..." 100 | @$(ENV_PREFIX)/$(PYTEST_CMD) 101 | 102 | .PHONY: uninstall 103 | uninstall: ## Uninstall operator from current Kubernetes cluster (uses kubectl current context). 104 | @echo "Uninstalling operator from $(CURRENT_K8S_CLUSTER) ..." 105 | @$(KUBECTL_CMD) delete -f $(OPERATOR_RELEASE_MANIFEST) 106 | 107 | .PHONY: clean 108 | clean: ## Clean project generated files. 109 | @echo "Cleaning up python $(VENV_FOLDER) virtual environment ..." 110 | @$(RM_CMD) -rf $(VENV_FOLDER) 111 | 112 | .PHONY: help 113 | help: ## Display this help 114 | @$(AWK_CMD) 'BEGIN { \ 115 | FS = ":.*##"; \ 116 | printf "\nUsage:\n make \033[36m\033[0m\n\nTargets:\n" \ 117 | } /^[a-zA-Z_-]+:.*?##/ \ 118 | { printf " \033[36m%-20s\033[0m %s\n", $$1, $$2 }' \ 119 | $(MAKEFILE_LIST) 120 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### DOKS static route operator is available as a managed component (https://docs.digitalocean.com/products/kubernetes/how-to/use-routing-agent/). 2 | 3 | 4 | ### 2/22/2025: We will release a *managed* static route operator (called *routing agent*) for DigitalOcean Kubernetes within a couple of weeks. It will support both 0.0.0.0 default route, and multiple destinations using ECMP!! This repo will become irrelevant and replaced by a managed component. We strongly recommend to wait for the new release if you are starting out now. 5 | 6 | 7 | # Overview 8 | 9 | The main purpose of the Static Routes Operator is to manage entries in the Linux routing table of each worker node based on CRD spec. It is deployed as a `DaemonSet`, hence it will run on each node of your DOKS cluster. 10 | 11 | Below diagram illustrates the operational concept: 12 | 13 | ![Static Routes Controller Overview](assets/images/sr_operator.png) 14 | 15 | ## Table of Contents 16 | 17 | - [Prerequisites](#prerequisites) 18 | - [Deploying the Kubernetes Static Routes Operator](#deploying-the-kubernetes-static-routes-operator) 19 | - [Testing the Setup](#testing-the-setup) 20 | - [Cleaning Up](#cleaning-up) 21 | 22 | ## Prerequisites 23 | 24 | 1. A working DOKS cluster you have access to. 25 | 2. Kubectl CLI installed on your local machine, and configured to point to your DOKS cluster. 26 | 3. NAT GW Droplet configured and running as detailed [here](https://docs.digitalocean.com/products/networking/vpc/how-to/configure-droplet-as-gateway/). 27 | 28 | **Note**: 29 | 30 | **Make sure your NAT GW Droplet is created in the same VPC as your DOKS cluster.** 31 | 32 | ## Deploying the Kubernetes Static Routes Operator 33 | 34 | 1. Deploy the latest release of static routes operator to your DOKS cluster using kubectl: 35 | 36 | ```shell 37 | kubectl apply -f https://raw.githubusercontent.com/digitalocean/k8s-staticroute-operator/main/releases/v1/k8s-staticroute-operator-v1.0.0.yaml 38 | ``` 39 | 40 | **Hint:** 41 | 42 | You can check the latest version in the [releases](releases/) path from the [k8s-staticroute-operator](https://github.com/digitalocean/k8s-staticroute-operator/) GitHub repo. 43 | 44 | 2. Check if operator Pods are up and running: 45 | 46 | ```shell 47 | kubectl get pods -l name=k8s-staticroute-operator -n static-routes 48 | ``` 49 | 50 | Output looks similar to: 51 | 52 | ```text 53 | NAME READY STATUS RESTARTS AGE 54 | k8s-staticroute-operator-9vp7g 1/1 Running 0 22m 55 | k8s-staticroute-operator-mlfff 1/1 Running 0 22m 56 | ``` 57 | 58 | 3. Check operator logs - no exceptions should be reported: 59 | 60 | ```shell 61 | kubectl logs -f ds/k8s-staticroute-operator -n static-routes 62 | ``` 63 | 64 | Output looks similar to: 65 | 66 | ```text 67 | [2022-08-24 14:42:13,625] kopf._core.reactor.r [DEBUG ] Starting Kopf 1.35.6. 68 | [2022-08-24 14:42:13,625] kopf._core.engines.a [INFO ] Initial authentication has been initiated. 69 | [2022-08-24 14:42:13,626] kopf.activities.auth [DEBUG ] Activity 'login_via_pykube' is invoked. 70 | [2022-08-24 14:42:13,628] kopf.activities.auth [DEBUG ] Pykube is configured in cluster with service account. 71 | [2022-08-24 14:42:13,629] kopf.activities.auth [INFO ] Activity 'login_via_pykube' succeeded. 72 | [2022-08-24 14:42:13,629] kopf.activities.auth [DEBUG ] Activity 'login_via_client' is invoked. 73 | [2022-08-24 14:42:13,631] kopf.activities.auth [DEBUG ] Client is configured in cluster with service account. 74 | [2022-08-24 14:42:13,632] kopf.activities.auth [INFO ] Activity 'login_via_client' succeeded. 75 | [2022-08-24 14:42:13,632] kopf._core.engines.a [INFO ] Initial authentication has finished. 76 | [2022-08-24 14:42:13,789] kopf._cogs.clients.w [DEBUG ] Starting the watch-stream for customresourcedefinitions.v1.apiextensions.k8s.io cluster-wide. 77 | [2022-08-24 14:42:13,791] kopf._cogs.clients.w [DEBUG ] Starting the watch-stream for staticroutes.v1.networking.digitalocean.com cluster-wide. 78 | ... 79 | ``` 80 | 81 | ## Testing the Setup 82 | 83 | Each sample CRD provided creates a static route to two different websites which report back your public IP - [ifconfig.me/ip](http://ifconfig.me/ip), and [ipinfo.io/ip](http://ipinfo.io/ip). 84 | 85 | Typical static route definition looks like below: 86 | 87 | ```yaml 88 | apiVersion: networking.digitalocean.com/v1 89 | kind: StaticRoute 90 | metadata: 91 | name: static-route-ifconfig.me 92 | spec: 93 | destinations: 94 | - "34.160.111.145" 95 | gateway: "10.116.0.5" 96 | ``` 97 | 98 | Explanations for the above configuration: 99 | 100 | - `spec.destinations` - A list of host IPs (or subnet CIDRs) to route through the gateway. 101 | - `spec.gateway` - Gateway IP address used for routing the host(s)/subnet(s). 102 | 103 | To test the setup, download a sample manifest from the [examples](examples) location: 104 | 105 | ```shell 106 | # Example for ifconfig.me 107 | curl -O https://raw.githubusercontent.com/digitalocean/k8s-staticroute-operator/main/examples/static-route-ifconfig.me.yaml 108 | 109 | # Example for ipinfo.io 110 | curl -O https://raw.githubusercontent.com/digitalocean/k8s-staticroute-operator/main/examples/static-route-ipinfo.io.yaml 111 | ``` 112 | 113 | After downloading the manifests, make sure to replace the `<>` placeholders in each manifest file. Then, apply each manifest using kubectl: 114 | 115 | ```shell 116 | # Example for ifconfig.me 117 | kubectl apply -f static-route-ifconfig.me.yaml 118 | 119 | # Example for ipinfo.io 120 | kubectl apply -f static-route-ipinfo.io.yaml 121 | ``` 122 | 123 | **Hint:** 124 | 125 | Above command will create the static route custom resources in the default namespace. In production environments (and not only), it's best to have a dedicated namespace with RBAC set (based on what people or teams need to have access). 126 | 127 | Next, check if the static route resources were created: 128 | 129 | ```shell 130 | kubectl get staticroutes -o wide 131 | ``` 132 | 133 | The output looks similar to: 134 | 135 | ```text 136 | NAME DESTINATIONS GATEWAY AGE 137 | static-route-ifconfig.me ["34.160.111.145"] 10.116.0.5 7m2s 138 | static-route-ipinfo.io ["34.117.59.81"] 10.116.0.5 4s 139 | ``` 140 | 141 | Now, check if the custom static routes were applied on each worker node, after SSH-ing: 142 | 143 | ```shell 144 | route -n 145 | ``` 146 | 147 | The output looks similar to (the irrelevant lines were omitted from the output for better visibility): 148 | 149 | ```text 150 | Kernel IP routing table 151 | Destination Gateway Genmask Flags Metric Ref Use Iface 152 | 0.0.0.0 206.81.0.1 0.0.0.0 UG 0 0 0 eth0 153 | ... 154 | 34.117.59.81 10.116.0.5 255.255.255.255 UGH 0 0 0 eth1 155 | 34.160.111.145 10.116.0.5 255.255.255.255 UGH 0 0 0 eth1 156 | ... 157 | ``` 158 | 159 | **Note:** 160 | 161 | In the above example the NAT GW private IP used for testing is `10.116.0.5`. 162 | 163 | Next, deploy the [curl-test](examples/curl-test.yaml) Pod to test the setup: 164 | 165 | ```shell 166 | kubectl apply -f https://raw.githubusercontent.com/digitalocean/k8s-staticroute-operator/main/examples/curl-test.yaml 167 | ``` 168 | 169 | Finally, test if the curl-test pod replies back your NAT GW public IP for each route: 170 | 171 | ```shell 172 | # Test ifconfig.me/ip endpoint 173 | kubectl exec -it curl-test -- curl ifconfig.me/ip 174 | ``` 175 | 176 | ```shell 177 | # Test the ipinfo.io/ip endpoint 178 | kubectl exec -it curl-test -- curl ipinfo.io/ip 179 | ``` 180 | 181 | ## Cleaning Up 182 | 183 | To clean up the operator and associated resources, please run the following kubectl command (make sure you're using the same release version as in the install step): 184 | 185 | ```shell 186 | kubectl delete -f deploy https://raw.githubusercontent.com/digitalocean/k8s-staticroute-operator/main/releases/v1/k8s-staticroute-operator-v1.0.0.yaml 187 | ``` 188 | 189 | **Note:** 190 | Above command will delete the associated namespace as well (`static-routes`). Make sure to backup your CRDs first, if needed later. 191 | 192 | The output looks similar to: 193 | 194 | ```text 195 | customresourcedefinition.apiextensions.k8s.io "staticroutes.networking.digitalocean.com" deleted 196 | serviceaccount "k8s-staticroute-operator" deleted 197 | clusterrole.rbac.authorization.k8s.io "k8s-staticroute-operator" deleted 198 | clusterrolebinding.rbac.authorization.k8s.io "k8s-staticroute-operator" deleted 199 | daemonset.apps "k8s-staticroute-operator" deleted 200 | ``` 201 | 202 | Check the routes on each worker node, after SSH-ing: 203 | 204 | ```shell 205 | route -n 206 | ``` 207 | 208 | The custom static routes should not be present in the routing table output. 209 | 210 | Finally, the `curl-test` pod should report back the public IP of the worker node where it runs: 211 | 212 | ```shell 213 | # Inspect the node where the curl-test Pod runs: 214 | kubectl get pod curl-test -o wide 215 | ``` 216 | 217 | The output looks similar to (write down the node name from the `NODE` column): 218 | 219 | ```shell 220 | NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES 221 | curl-test 1/1 Running 2 (45m ago) 165m 10.244.0.140 basicnp-7micg 222 | ``` 223 | 224 | Above example reports - `basicnp-7micg`. 225 | 226 | Check the worker node public IP: 227 | 228 | ```shell 229 | kubectl get nodes -o wide 230 | ``` 231 | 232 | The output looks similar to (note the public IP of the associated node where the `curl-test` Pod runs): 233 | 234 | ```text 235 | NAME STATUS ROLES AGE VERSION INTERNAL-IP EXTERNAL-IP OS-IMAGE KERNEL-VERSION CONTAINER-RUNTIME 236 | basicnp-7micg Ready 3h20m v1.23.9 10.116.0.2 206.189.231.90 Debian GNU/Linux 10 (buster) 5.10.0-0.bpo.15-amd64 containerd://1.4.13 237 | basicnp-7micw Ready 3h20m v1.23.9 10.116.0.3 206.81.2.154 Debian GNU/Linux 10 (buster) 5.10.0-0.bpo.15-amd64 containerd://1.4.13 238 | ``` 239 | 240 | Above example reports - `206.189.231.90`. 241 | 242 | Exec the `ifconfig.me/ip` curl: 243 | 244 | ```shell 245 | kubectl exec -it curl-test -- curl ifconfig.me/ip 246 | ``` 247 | 248 | The output looks similar to: 249 | 250 | ```text 251 | 206.189.231.90 252 | ``` 253 | 254 | ### Failing over gateways 255 | 256 | In order to protect against gateway failures, it is recommended to prepare a standby gateway droplet and failover when necessary. While the operator does not support true HA, failing over enables to minimize the window of disruption. 257 | 258 | Requirements: 259 | 260 | 1. Have one (or more) gateway droplets fully configured and ready to take traffic. (This may entail allow-listing the droplet's IP address with downstream receivers.) 261 | 1. Implement a method to identify when a gateway droplet is failing. This could be as simple as probing the droplet repeatedly from inside the cluster and considering it down if the probes fail repeatedly, to aggregating multiple signals from observability systems and coming to an availability determination. The exact implementation depends on the user's needs and should ideally yield a good signal-to-noise ratio. 262 | 1. All operator instances are up and running correctly at the time of the failover. (More specifically, at step (3) of the failover procedure outlined below.) 263 | 264 | Let's assume that we have a single destination IP address 34.160.111.145 that the active (or primary) gateway with IP addess 10.116.0.5 is transmitting traffic for. The corresponding `StaticRoute` would look like this 265 | 266 | ```yaml 267 | # ./primary.yaml 268 | apiVersion: networking.digitalocean.com/v1 269 | kind: StaticRoute 270 | metadata: 271 | name: primary 272 | spec: 273 | destinations: 274 | - "34.160.111.145" 275 | gateway: "10.116.0.5" 276 | ``` 277 | 278 | and stored in the file `primary.yaml`. 279 | 280 | Our standby (or secondary) gateway has IP adress 10.116.0.12 and is prepared to serve traffic for the same destination IP address. Its `StaticRoute` definition is identical to the previous one, only differing in the gateway IP address (and the object name): 281 | 282 | ```yaml 283 | # ./secondary.yaml 284 | apiVersion: networking.digitalocean.com/v1 285 | kind: StaticRoute 286 | metadata: 287 | name: secondary 288 | spec: 289 | destinations: 290 | - "34.160.111.145" 291 | gateway: "10.116.0.12" 292 | ``` 293 | 294 | Let's further assume the above is stored in the file `secondary.yaml`. 295 | 296 | The actual failover procedure then consists of the following steps: 297 | 298 | 1. Identify that the active gateway with IP address 10.116.0.5 is failing. (As described above, the details are implementation-specific and out of scope for the operator.) 299 | 1. Delete the currently active `StaticRoute`: `kubectl delete -f primary.yaml` 300 | 1. Wait 30 to 60 seconds to give each operator instance enough time to process the object deletion; that is, respond by removing the route from all nodes. 301 | 1. Apply the standby `StaticRoute`: `kubectl apply -f secondary.yaml` 302 | 303 | The operator should pick up the new standby `StaticRoute` and put in the corresponding routing table entries. Afterwards, the failover has completed. 304 | 305 | **Important:** Do _not_ update an existing `StaticRoute` for a new gateway IP address (e.g., run `kubectl edit staticroute primary` to modify just the `spec.gateway` field) -- this is currently not supported and leads to failures. Issue digitalocean/k8s-staticroute-operator#23 tracks closing this gap. 306 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 1.0.0 2 | -------------------------------------------------------------------------------- /assets/images/sr_operator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/digitalocean/k8s-staticroute-operator/6579eb64d98977c4d2345a9a81b9a0c315a4b043/assets/images/sr_operator.png -------------------------------------------------------------------------------- /controller/api/schema.py: -------------------------------------------------------------------------------- 1 | from apischema.json_schema import deserialization_schema 2 | import yaml 3 | import json 4 | 5 | # WIP 6 | # More or less primitive way of doing serialization 7 | class OpenAPIV3Schema: 8 | @classmethod 9 | def api_schema(cls): 10 | return deserialization_schema( 11 | cls, all_refs=False, additional_properties=True, with_schema=False 12 | ) 13 | 14 | @classmethod 15 | def singular(cls): 16 | return cls.__name__.lower() 17 | 18 | @classmethod 19 | def plural(cls): 20 | return f"{cls.singular()}s" 21 | 22 | @classmethod 23 | def crd_schema(cls): 24 | crd = { 25 | "apiVersion": "apiextensions.k8s.io/v1", 26 | "kind": "CustomResourceDefinition", 27 | "metadata": { 28 | "name": f"{cls.plural()}.{cls.__group__}", 29 | }, 30 | "spec": { 31 | "group": cls.__group__, 32 | "scope": cls.__scope__, 33 | "names": { 34 | "kind": cls.__name__, 35 | "singular": cls.singular(), 36 | "plural": cls.plural(), 37 | "shortNames": cls.__short_names__, 38 | }, 39 | "versions": [ 40 | { 41 | "name": cls.__version__, 42 | "served": True, 43 | "storage": True, 44 | "schema": { 45 | "openAPIV3Schema": { 46 | "type": "object", 47 | "properties": { 48 | "spec": cls.api_schema(), 49 | "status": { 50 | "x-kubernetes-preserve-unknown-fields": True, 51 | "type": "object", 52 | }, 53 | }, 54 | }, 55 | }, 56 | "additionalPrinterColumns": cls.__additional_printer_columns__, 57 | }, 58 | ], 59 | }, 60 | } 61 | return yaml.dump( 62 | yaml.load(json.dumps(crd), Loader=yaml.Loader), 63 | Dumper=yaml.Dumper, 64 | ) 65 | -------------------------------------------------------------------------------- /controller/api/v1/types.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass, field 2 | from apischema import schema 3 | from typing import NewType 4 | from ..schema import OpenAPIV3Schema 5 | 6 | 7 | # Static route API representation 8 | # Final CRD is generated upon below dataclass via `make manifests` command 9 | # WIP 10 | 11 | 12 | @dataclass 13 | class StaticRoute(OpenAPIV3Schema): 14 | __group__ = "networking.digitalocean.com" 15 | __version__ = "v1" 16 | __scope__ = "Cluster" 17 | __short_names__ = ["sr"] 18 | 19 | __additional_printer_columns__ = [ 20 | { 21 | "name": "Age", 22 | "type": "date", 23 | "priority": 0, 24 | "jsonPath": ".metadata.creationTimestamp", 25 | }, 26 | { 27 | "name": "Destinations", 28 | "type": "string", 29 | "priority": 1, 30 | "description": "Destination host(s)/subnet(s)", 31 | "jsonPath": ".spec.destinations", 32 | }, 33 | { 34 | "name": "Gateway", 35 | "type": "string", 36 | "priority": 1, 37 | "description": "Gateway to route through", 38 | "jsonPath": ".spec.gateway", 39 | }, 40 | ] 41 | 42 | Destination = NewType("Destination", str) 43 | schema( 44 | pattern="^([0-9]{1,3}\.){3}[0-9]{1,3}$|^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$", 45 | )(Destination) 46 | 47 | destinations: list[Destination] = field( 48 | metadata=schema( 49 | description="Destination host(s)/subnet(s) to route through the gateway (required)", 50 | ) 51 | ) 52 | gateway: str = field( 53 | metadata=schema( 54 | description="Gateway to route through (required)", 55 | pattern="^([0-9]{1,3}\.){3}[0-9]{1,3}$", 56 | ) 57 | ) 58 | -------------------------------------------------------------------------------- /controller/config/crd.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apiextensions.k8s.io/v1 2 | kind: CustomResourceDefinition 3 | metadata: 4 | name: staticroutes.networking.digitalocean.com 5 | spec: 6 | group: networking.digitalocean.com 7 | names: 8 | kind: StaticRoute 9 | plural: staticroutes 10 | shortNames: 11 | - sr 12 | singular: staticroute 13 | scope: Cluster 14 | versions: 15 | - additionalPrinterColumns: 16 | - jsonPath: .metadata.creationTimestamp 17 | name: Age 18 | priority: 0 19 | type: date 20 | - description: Destination host(s)/subnet(s) 21 | jsonPath: .spec.destinations 22 | name: Destinations 23 | priority: 1 24 | type: string 25 | - description: Gateway to route through 26 | jsonPath: .spec.gateway 27 | name: Gateway 28 | priority: 1 29 | type: string 30 | name: v1 31 | schema: 32 | openAPIV3Schema: 33 | properties: 34 | spec: 35 | properties: 36 | destinations: 37 | description: Destination host(s)/subnet(s) to route through the gateway 38 | (required) 39 | items: 40 | pattern: ^([0-9]{1,3}\.){3}[0-9]{1,3}$|^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$ 41 | type: string 42 | type: array 43 | gateway: 44 | description: Gateway to route through (required) 45 | pattern: ^([0-9]{1,3}\.){3}[0-9]{1,3}$ 46 | type: string 47 | required: 48 | - destinations 49 | - gateway 50 | type: object 51 | status: 52 | type: object 53 | x-kubernetes-preserve-unknown-fields: true 54 | type: object 55 | served: true 56 | storage: true 57 | -------------------------------------------------------------------------------- /controller/config/manager.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: DaemonSet 3 | metadata: 4 | name: k8s-staticroute-operator 5 | spec: 6 | selector: 7 | matchLabels: 8 | name: k8s-staticroute-operator 9 | template: 10 | metadata: 11 | labels: 12 | name: k8s-staticroute-operator 13 | spec: 14 | serviceAccountName: k8s-staticroute-operator 15 | hostNetwork: true 16 | tolerations: 17 | - operator: Exists 18 | containers: 19 | - name: k8s-staticroute-operator 20 | image: digitalocean/k8s-staticroute-operator: 21 | imagePullPolicy: Always 22 | resources: 23 | requests: 24 | memory: "100Mi" 25 | limits: 26 | memory: "150Mi" 27 | securityContext: 28 | runAsNonRoot: true 29 | readOnlyRootFilesystem: true 30 | capabilities: 31 | add: 32 | - NET_ADMIN 33 | env: 34 | - name: OPERATOR_NAME 35 | value: "k8s-staticroute-operator" 36 | - name: NODE_HOSTNAME 37 | valueFrom: 38 | fieldRef: 39 | fieldPath: spec.nodeName 40 | -------------------------------------------------------------------------------- /controller/config/namespace.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | name: static-routes 5 | -------------------------------------------------------------------------------- /controller/config/rbac/role.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: rbac.authorization.k8s.io/v1 3 | kind: ClusterRole 4 | metadata: 5 | name: k8s-staticroute-operator 6 | rules: 7 | # Framework: knowing which other operators are running (i.e. peering). 8 | - apiGroups: [networking.digitalocean.com] 9 | resources: [clusterkopfpeerings] 10 | verbs: [list, watch, patch, get] 11 | 12 | # Framework: runtime observation of namespaces & CRDs (addition/deletion). 13 | - apiGroups: [apiextensions.k8s.io] 14 | resources: [customresourcedefinitions] 15 | verbs: [list, watch] 16 | - apiGroups: [""] 17 | resources: [namespaces] 18 | verbs: [list, watch] 19 | 20 | # Framework: posting the events about the handlers progress/errors. 21 | - apiGroups: [""] 22 | resources: [events] 23 | verbs: [create] 24 | 25 | # Application: watching & handling for the custom resource we declare. 26 | - apiGroups: [networking.digitalocean.com] 27 | resources: [staticroutes] 28 | verbs: [list, watch, patch] 29 | -------------------------------------------------------------------------------- /controller/config/rbac/role_binding.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | kind: ClusterRoleBinding 3 | apiVersion: rbac.authorization.k8s.io/v1 4 | metadata: 5 | name: k8s-staticroute-operator 6 | subjects: 7 | - kind: ServiceAccount 8 | name: k8s-staticroute-operator 9 | roleRef: 10 | kind: ClusterRole 11 | name: k8s-staticroute-operator 12 | apiGroup: rbac.authorization.k8s.io 13 | -------------------------------------------------------------------------------- /controller/config/rbac/service_account.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: ServiceAccount 4 | metadata: 5 | name: k8s-staticroute-operator 6 | -------------------------------------------------------------------------------- /controller/constants.py: -------------------------------------------------------------------------------- 1 | DEFAULT_GW_CIDR = "0.0.0.0/0" 2 | NOT_USABLE_IP_ADDRESS = "0.0.0.0" 3 | 4 | ROUTE_READY_MSG = "Ready" 5 | ROUTE_NOT_READY_MSG = "NotReady" 6 | ROUTE_EVT_MSG = { 7 | "add": {"success": "RouteCreateSucceeded", "failure": "RouteCreateFailed"}, 8 | "del": {"success": "RouteDeleteSucceeded", "failure": "RouteDeleteFailed"}, 9 | } 10 | -------------------------------------------------------------------------------- /controller/generate_api.py: -------------------------------------------------------------------------------- 1 | from api.v1.types import StaticRoute 2 | import argparse 3 | import os 4 | 5 | if __name__ == "__main__": 6 | parser = argparse.ArgumentParser() 7 | parser.add_argument( 8 | "--output-path", 9 | help="Output CRD files to specified folder path, else use current folder", 10 | default=".", 11 | ) 12 | args = parser.parse_args() 13 | 14 | if not os.path.exists(args.output_path): 15 | os.makedirs(args.output_path) 16 | with open(f"{args.output_path}/crd.yaml", "w") as file: 17 | file.writelines(StaticRoute.crd_schema()) 18 | -------------------------------------------------------------------------------- /controller/kustomization.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | # Making sure all resources are created in a dedicated namespace 5 | # Also specific labels and annotations are added for later identification 6 | namespace: static-routes 7 | commonAnnotations: 8 | provider: digitalocean 9 | 10 | # Apply all required resources: RBACs, CRD definitions, operator running context (DaemonSet) 11 | resources: 12 | - config/namespace.yaml 13 | - config/rbac/service_account.yaml 14 | - config/rbac/role.yaml 15 | - config/rbac/role_binding.yaml 16 | - config/crd.yaml 17 | - config/manager.yaml 18 | -------------------------------------------------------------------------------- /controller/static-route-handler.py: -------------------------------------------------------------------------------- 1 | import kopf 2 | from pyroute2 import IPRoute 3 | from api.v1.types import StaticRoute 4 | from constants import DEFAULT_GW_CIDR 5 | from constants import NOT_USABLE_IP_ADDRESS 6 | from constants import ROUTE_EVT_MSG 7 | from constants import ROUTE_READY_MSG 8 | from constants import ROUTE_NOT_READY_MSG 9 | from utils import valid_ip_address 10 | 11 | 12 | # =================================== Static route management =========================================== 13 | # 14 | # Works the same way as the Linux `ip route` command: 15 | # - "add": Adds a new entry in the Linux routing table (must not exist beforehand) 16 | # - "change": Changes an entry from the the Linux routing table (must exist beforehand) 17 | # - "delete": Deletes an entry from the Linux routing table (must exist beforehand) 18 | # - "replace": Replaces an entry from the Linux routing table if it exists, creates a new one otherwise 19 | # 20 | # ======================================================================================================= 21 | 22 | 23 | def manage_static_route(operation, destination, gateway, logger=None): 24 | operation_success = False 25 | message = "" 26 | 27 | # Check if destination/gateway IP address/CIDR is valid first 28 | if not valid_ip_address(destination) or not valid_ip_address(gateway): 29 | message = f"Invalid IP address specified for route - dest: {destination}, gateway: {gateway}!" 30 | if logger is not None: 31 | logger.error(message) 32 | return (False, message) 33 | 34 | # We don't want to mess with default GW settings, or with the '0.0.0.0' IP address 35 | if destination == DEFAULT_GW_CIDR or destination == NOT_USABLE_IP_ADDRESS: 36 | message = f"Route {operation} request denied - dest: {destination}, gateway: {gateway}!" 37 | if logger is not None: 38 | logger.error(message) 39 | return (False, message) 40 | 41 | with IPRoute() as ipr: 42 | try: 43 | ipr.route(operation, dst=destination, gateway=gateway) 44 | operation_success = True 45 | message = f"Success - Dest: {destination}, gateway: {gateway}, operation: {operation}." 46 | if logger is not None: 47 | logger.info(message) 48 | except Exception as ex: 49 | operation_success = False 50 | message = f"Route {operation} failed! Error message: {ex}" 51 | if logger is not None: 52 | logger.error(message) 53 | 54 | return (operation_success, message) 55 | 56 | 57 | def process_static_routes(routes, operation, event_ctx=None, logger=None): 58 | status = [] 59 | 60 | for route in routes: 61 | operation_succeeded, message = manage_static_route( 62 | operation=operation, 63 | destination=route["destination"], 64 | gateway=route["gateway"], 65 | logger=logger, 66 | ) 67 | 68 | if not operation_succeeded: 69 | status.append( 70 | { 71 | "destination": route["destination"], 72 | "gateway": route["gateway"], 73 | "status": ROUTE_NOT_READY_MSG, 74 | } 75 | ) 76 | if event_ctx is not None: 77 | kopf.exception( 78 | event_ctx, 79 | reason=ROUTE_EVT_MSG[operation]["failure"], 80 | message=message, 81 | ) 82 | continue 83 | 84 | status.append( 85 | { 86 | "destination": route["destination"], 87 | "gateway": route["gateway"], 88 | "status": ROUTE_READY_MSG, 89 | } 90 | ) 91 | if event_ctx is not None: 92 | kopf.info( 93 | event_ctx, reason=ROUTE_EVT_MSG[operation]["success"], message=message 94 | ) 95 | 96 | return status 97 | 98 | 99 | # ============================== Create Handler ===================================== 100 | # 101 | # Default behavior is to "add" the static route(s) specified in our CRD 102 | # If the static route already exists, it will not be overwritten. 103 | # 104 | # =================================================================================== 105 | 106 | 107 | @kopf.on.resume(StaticRoute.__group__, StaticRoute.__version__, StaticRoute.__name__) 108 | @kopf.on.create(StaticRoute.__group__, StaticRoute.__version__, StaticRoute.__name__) 109 | def create_fn(body, spec, logger, **_): 110 | destinations = spec.get("destinations", []) 111 | gateway = spec["gateway"] 112 | routes_to_add_spec = [ 113 | {"destination": destination, "gateway": gateway} for destination in destinations 114 | ] 115 | 116 | return process_static_routes( 117 | routes=routes_to_add_spec, operation="add", event_ctx=body, logger=logger 118 | ) 119 | 120 | 121 | # ============================== Update Handler ===================================== 122 | # 123 | # Default behavior is to update/replace the static route(s) specified in our CRD 124 | # 125 | # =================================================================================== 126 | 127 | 128 | @kopf.on.update(StaticRoute.__group__, StaticRoute.__version__, StaticRoute.__name__) 129 | def update_fn(body, old, new, logger, **_): 130 | old_gateway = old["spec"]["gateway"] 131 | new_gateway = new["spec"]["gateway"] 132 | old_destinations = old["spec"].get("destinations", []) 133 | new_destinations = new["spec"].get("destinations", []) 134 | destinations_to_delete = list(set(old_destinations) - set(new_destinations)) 135 | destinations_to_add = list(set(new_destinations) - set(old_destinations)) 136 | 137 | routes_to_delete_spec = [ 138 | {"destination": destination, "gateway": old_gateway} 139 | for destination in destinations_to_delete 140 | ] 141 | 142 | process_static_routes( 143 | routes=routes_to_delete_spec, operation="del", event_ctx=body, logger=logger 144 | ) 145 | 146 | routes_to_add_spec = [ 147 | {"destination": destination, "gateway": new_gateway} 148 | for destination in destinations_to_add 149 | ] 150 | 151 | return process_static_routes( 152 | routes=routes_to_add_spec, operation="add", event_ctx=body, logger=logger 153 | ) 154 | 155 | 156 | # ============================== Delete Handler ===================================== 157 | # 158 | # Default behavior is to delete the static route(s) specified in our CRD only! 159 | # 160 | # =================================================================================== 161 | 162 | 163 | @kopf.on.delete(StaticRoute.__group__, StaticRoute.__version__, StaticRoute.__name__) 164 | def delete(body, spec, logger, **_): 165 | destinations = spec.get("destinations", []) 166 | gateway = spec["gateway"] 167 | routes_to_delete_spec = [ 168 | {"destination": destination, "gateway": gateway} for destination in destinations 169 | ] 170 | 171 | return process_static_routes( 172 | routes=routes_to_delete_spec, operation="del", event_ctx=body, logger=logger 173 | ) 174 | -------------------------------------------------------------------------------- /controller/utils.py: -------------------------------------------------------------------------------- 1 | import ipaddress 2 | 3 | 4 | # checks for both standard IP address, and CIDR notation 5 | def valid_ip_address(address): 6 | try: 7 | ip_object = ipaddress.ip_network(address) 8 | except ValueError: 9 | return False 10 | 11 | return True 12 | -------------------------------------------------------------------------------- /examples/curl-test.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Pod 3 | metadata: 4 | name: curl-test 5 | spec: 6 | containers: 7 | - name: curl 8 | image: curlimages/curl:7.80.0 9 | command: 10 | - sleep 11 | - "3600" 12 | imagePullPolicy: IfNotPresent 13 | restartPolicy: Always 14 | -------------------------------------------------------------------------------- /examples/static-route-ifconfig.me.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.digitalocean.com/v1 2 | kind: StaticRoute 3 | metadata: 4 | name: static-route-ifconfig.me 5 | spec: 6 | destinations: 7 | - "34.160.111.145" 8 | gateway: "" 9 | -------------------------------------------------------------------------------- /examples/static-route-ipinfo.io.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.digitalocean.com/v1 2 | kind: StaticRoute 3 | metadata: 4 | name: static-route-ipinfo.io 5 | spec: 6 | destinations: 7 | - "34.117.59.81" 8 | gateway: "" 9 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | testpaths = tests 3 | console_output_style = classic 4 | -------------------------------------------------------------------------------- /releases/v1/k8s-staticroute-operator-v1.0.0.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Namespace 3 | metadata: 4 | annotations: 5 | provider: digitalocean 6 | name: static-routes 7 | --- 8 | apiVersion: apiextensions.k8s.io/v1 9 | kind: CustomResourceDefinition 10 | metadata: 11 | annotations: 12 | provider: digitalocean 13 | name: staticroutes.networking.digitalocean.com 14 | spec: 15 | group: networking.digitalocean.com 16 | names: 17 | kind: StaticRoute 18 | plural: staticroutes 19 | shortNames: 20 | - sr 21 | singular: staticroute 22 | scope: Cluster 23 | versions: 24 | - additionalPrinterColumns: 25 | - jsonPath: .metadata.creationTimestamp 26 | name: Age 27 | priority: 0 28 | type: date 29 | - description: Destination host(s)/subnet(s) 30 | jsonPath: .spec.destinations 31 | name: Destinations 32 | priority: 1 33 | type: string 34 | - description: Gateway to route through 35 | jsonPath: .spec.gateway 36 | name: Gateway 37 | priority: 1 38 | type: string 39 | name: v1 40 | schema: 41 | openAPIV3Schema: 42 | properties: 43 | spec: 44 | properties: 45 | destinations: 46 | description: Destination host(s)/subnet(s) to route through the gateway 47 | (required) 48 | items: 49 | pattern: ^([0-9]{1,3}\.){3}[0-9]{1,3}$|^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$ 50 | type: string 51 | type: array 52 | gateway: 53 | description: Gateway to route through (required) 54 | pattern: ^([0-9]{1,3}\.){3}[0-9]{1,3}$ 55 | type: string 56 | required: 57 | - destinations 58 | - gateway 59 | type: object 60 | status: 61 | type: object 62 | x-kubernetes-preserve-unknown-fields: true 63 | type: object 64 | served: true 65 | storage: true 66 | --- 67 | apiVersion: v1 68 | kind: ServiceAccount 69 | metadata: 70 | annotations: 71 | provider: digitalocean 72 | name: k8s-staticroute-operator 73 | namespace: static-routes 74 | --- 75 | apiVersion: rbac.authorization.k8s.io/v1 76 | kind: ClusterRole 77 | metadata: 78 | annotations: 79 | provider: digitalocean 80 | name: k8s-staticroute-operator 81 | rules: 82 | - apiGroups: 83 | - networking.digitalocean.com 84 | resources: 85 | - clusterkopfpeerings 86 | verbs: 87 | - list 88 | - watch 89 | - patch 90 | - get 91 | - apiGroups: 92 | - apiextensions.k8s.io 93 | resources: 94 | - customresourcedefinitions 95 | verbs: 96 | - list 97 | - watch 98 | - apiGroups: 99 | - "" 100 | resources: 101 | - namespaces 102 | verbs: 103 | - list 104 | - watch 105 | - apiGroups: 106 | - "" 107 | resources: 108 | - events 109 | verbs: 110 | - create 111 | - apiGroups: 112 | - networking.digitalocean.com 113 | resources: 114 | - staticroutes 115 | verbs: 116 | - list 117 | - watch 118 | - patch 119 | --- 120 | apiVersion: rbac.authorization.k8s.io/v1 121 | kind: ClusterRoleBinding 122 | metadata: 123 | annotations: 124 | provider: digitalocean 125 | name: k8s-staticroute-operator 126 | roleRef: 127 | apiGroup: rbac.authorization.k8s.io 128 | kind: ClusterRole 129 | name: k8s-staticroute-operator 130 | subjects: 131 | - kind: ServiceAccount 132 | name: k8s-staticroute-operator 133 | namespace: static-routes 134 | --- 135 | apiVersion: apps/v1 136 | kind: DaemonSet 137 | metadata: 138 | annotations: 139 | provider: digitalocean 140 | name: k8s-staticroute-operator 141 | namespace: static-routes 142 | spec: 143 | selector: 144 | matchLabels: 145 | name: k8s-staticroute-operator 146 | template: 147 | metadata: 148 | annotations: 149 | provider: digitalocean 150 | labels: 151 | name: k8s-staticroute-operator 152 | spec: 153 | containers: 154 | - env: 155 | - name: OPERATOR_NAME 156 | value: k8s-staticroute-operator 157 | - name: NODE_HOSTNAME 158 | valueFrom: 159 | fieldRef: 160 | fieldPath: spec.nodeName 161 | image: digitalocean/k8s-staticroute-operator:v1.0.0 162 | imagePullPolicy: Always 163 | name: k8s-staticroute-operator 164 | resources: 165 | limits: 166 | memory: 150Mi 167 | requests: 168 | memory: 100Mi 169 | securityContext: 170 | capabilities: 171 | add: 172 | - NET_ADMIN 173 | readOnlyRootFilesystem: true 174 | runAsNonRoot: true 175 | hostNetwork: true 176 | serviceAccountName: k8s-staticroute-operator 177 | tolerations: 178 | - operator: Exists 179 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | pytest == 7.1.3 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyroute2 == 0.7.2 2 | kopf[full-auth] == 1.35.6 3 | apischema == 0.17.5 4 | pyyaml == 6.0 5 | -------------------------------------------------------------------------------- /tests/manifests/static-route-test.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.digitalocean.com/v1 2 | kind: StaticRoute 3 | metadata: 4 | name: static-route-test 5 | spec: 6 | destinations: 7 | - "10.42.10.0" 8 | gateway: "10.0.2.100" 9 | -------------------------------------------------------------------------------- /tests/test_operator.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | from kopf.testing import KopfRunner 3 | import time 4 | 5 | ##################################### 6 | # # 7 | # Not ready yet! Work in progress. # 8 | # # 9 | ##################################### 10 | 11 | def setup_function(): 12 | # Create CRD 13 | subprocess.run( 14 | "kubectl apply -f controller/config/crd.yaml", 15 | shell=True, 16 | check=True 17 | ) 18 | time.sleep(1) # give it some time to react 19 | 20 | 21 | def teardown_function(): 22 | # Delete static route CR used for testing 23 | subprocess.run( 24 | "kubectl delete -f tests/manifests/static-route-test.yaml", 25 | shell=True, 26 | check=True 27 | ) 28 | time.sleep(1) # give it some time to react 29 | 30 | # Delete CRD from cluster 31 | subprocess.run( 32 | "kubectl delete -f controller/config/crd.yaml", 33 | shell=True, 34 | check=True 35 | ) 36 | time.sleep(1) # give it some time to react 37 | pass 38 | 39 | 40 | def test_operator(): 41 | with KopfRunner(['run', '--all-namespaces', '--verbose', 'controller/static-route-handler.py']) as runner: 42 | time.sleep(10) # wait a little bit until controller starts 43 | 44 | # Test static route CR 45 | subprocess.run( 46 | "kubectl apply -f tests/manifests/static-route-test.yaml", 47 | shell=True, 48 | check=True 49 | ) 50 | time.sleep(1) # give it some time to react 51 | 52 | assert runner.exit_code == 0 53 | assert runner.exception is None 54 | assert 'Route - dst: 10.42.10.0, gateway: 10.0.2.100 created successfully!' in runner.stdout 55 | --------------------------------------------------------------------------------