├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── Dockerfile ├── Dockerfile.amd64 ├── Dockerfile.arm64 ├── Dockerfile.ppc64le ├── Dockerfile.s390x ├── LICENSE ├── Makefile ├── README.md ├── glide.lock ├── glide.yaml ├── ipam.go ├── k8s.go └── main.go /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Expected Behavior 4 | 5 | 6 | 7 | ## Current Behavior 8 | 9 | 10 | 11 | ## Possible Solution 12 | 13 | 14 | 15 | ## Steps to Reproduce (for bugs) 16 | 17 | 18 | 1. 19 | 2. 20 | 3. 21 | 4. 22 | 23 | ## Context 24 | 25 | 26 | 27 | ## Your Environment 28 | 29 | * Calico-node/calicoctl version: 30 | * Orchestrator version (e.g. kubernetes, rkt, swarm, mesos): 31 | * Operating System and version: 32 | * Link to your project (optional): 33 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 10 | 11 | ## Todos 12 | - [ ] Tests 13 | - [ ] Documentation 14 | - [ ] Release note 15 | 16 | ## Release Note 17 | 23 | 24 | ```release-note 25 | None required 26 | ``` 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | .go-pkg-cache/ 3 | .idea/ 4 | .editorconfig 5 | vendor/ 6 | gobgp/ 7 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | Dockerfile.amd64 -------------------------------------------------------------------------------- /Dockerfile.amd64: -------------------------------------------------------------------------------- 1 | FROM scratch 2 | 3 | LABEL maintainer="tom@tigera.io" 4 | 5 | ADD bin/amd64/gobgp /gobgp 6 | ADD bin/amd64/calico-bgp-daemon /calico-bgp-daemon 7 | 8 | ENTRYPOINT ["/calico-bgp-daemon"] 9 | -------------------------------------------------------------------------------- /Dockerfile.arm64: -------------------------------------------------------------------------------- 1 | FROM scratch 2 | 3 | LABEL maintainer="tom@tigera.io" 4 | 5 | ADD bin/arm64/gobgp /gobgp 6 | ADD bin/arm64/calico-bgp-daemon /calico-bgp-daemon 7 | 8 | ENTRYPOINT ["/calico-bgp-daemon"] 9 | -------------------------------------------------------------------------------- /Dockerfile.ppc64le: -------------------------------------------------------------------------------- 1 | FROM scratch 2 | 3 | LABEL maintainer="tom@tigera.io" 4 | 5 | ADD bin/ppc64le/gobgp /gobgp 6 | ADD bin/ppc64le/calico-bgp-daemon /calico-bgp-daemon 7 | 8 | ENTRYPOINT ["/calico-bgp-daemon"] 9 | -------------------------------------------------------------------------------- /Dockerfile.s390x: -------------------------------------------------------------------------------- 1 | FROM scratch 2 | 3 | LABEL maintainer="tom@tigera.io" 4 | 5 | ADD bin/s390x/gobgp /gobgp 6 | ADD bin/s390x/calico-bgp-daemon /calico-bgp-daemon 7 | 8 | ENTRYPOINT ["/calico-bgp-daemon"] 9 | -------------------------------------------------------------------------------- /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 | # Shortcut targets 2 | default: build 3 | 4 | ## Build binary for current platform 5 | all: build 6 | 7 | ## Run the tests for the current platform/architecture 8 | test: ut test-install-cni 9 | ############################################################################### 10 | # Both native and cross architecture builds are supported. 11 | # The target architecture is select by setting the ARCH variable. 12 | # When ARCH is undefined it is set to the detected host architecture. 13 | # When ARCH differs from the host architecture a crossbuild will be performed. 14 | ARCHES=$(patsubst Dockerfile.%,%,$(wildcard Dockerfile.*)) 15 | 16 | # BUILDARCH is the host architecture 17 | # ARCH is the target architecture 18 | # we need to keep track of them separately 19 | BUILDARCH ?= $(shell uname -m) 20 | 21 | # canonicalized names for host architecture 22 | ifeq ($(BUILDARCH),aarch64) 23 | BUILDARCH=arm64 24 | endif 25 | ifeq ($(BUILDARCH),x86_64) 26 | BUILDARCH=amd64 27 | endif 28 | 29 | # unless otherwise set, I am building for my own architecture, i.e. not cross-compiling 30 | ARCH ?= $(BUILDARCH) 31 | 32 | # canonicalized names for target architecture 33 | ifeq ($(ARCH),aarch64) 34 | override ARCH=arm64 35 | endif 36 | ifeq ($(ARCH),x86_64) 37 | override ARCH=amd64 38 | endif 39 | ############################################################################### 40 | GO_BUILD_VER ?= v0.16 41 | 42 | CALICO_BUILD?=calico/go-build:$(GO_BUILD_VER) 43 | SRC_FILES=$(shell find . -type f -name '*.go' -not -path "./vendor/*" -not -path "./gobgp/*") 44 | GOBGPD_VERSION?=$(shell git describe --tags --dirty) 45 | CONTAINER_NAME?=calico/gobgpd 46 | PACKAGE_NAME?=github.com/projectcalico/calico-bgp-daemon 47 | LOCAL_USER_ID?=$(shell id -u $$USER) 48 | BIN=bin/$(ARCH) 49 | 50 | clean: 51 | rm -rf vendor 52 | rm -rf gobgp 53 | rm -rf $(BIN) 54 | 55 | ############################################################################### 56 | # Building the binary 57 | ############################################################################### 58 | build: $(BIN)/calico-bgp-daemon 59 | build-all: $(addprefix sub-build-,$(ARCHES)) 60 | sub-build-%: 61 | $(MAKE) build ARCH=$* 62 | 63 | vendor: glide.lock 64 | mkdir -p $(HOME)/.glide 65 | # To build without Docker just run "glide install -strip-vendor" 66 | docker run --rm \ 67 | -v $(CURDIR):/go/src/$(PACKAGE_NAME):rw \ 68 | -v $(HOME)/.glide:/home/user/.glide:rw \ 69 | -e LOCAL_USER_ID=$(LOCAL_USER_ID) \ 70 | $(CALICO_BUILD) /bin/sh -c ' \ 71 | cd /go/src/$(PACKAGE_NAME) && \ 72 | glide install -strip-vendor' 73 | 74 | # instead of 'go get', run `git clone` and then `dep ensure && go build` so the files are cached 75 | gobgp: 76 | git clone -b v1.33 https://github.com/osrg/gobgp gobgp 77 | 78 | gobgp/vendor: gobgp 79 | docker run --rm \ 80 | -v $(CURDIR)/gobgp:/go/src/github.com/osrg/gobgp \ 81 | -w /go/src/github.com/osrg/gobgp \ 82 | -e LOCAL_USER_ID=$(LOCAL_USER_ID) \ 83 | -e ARCH=$(ARCH) \ 84 | -e GOARCH=$(ARCH) \ 85 | $(CALICO_BUILD) dep ensure 86 | 87 | $(BIN)/gobgp: gobgp gobgp/vendor 88 | mkdir -p $(@D) 89 | docker run --rm \ 90 | -v $(CURDIR)/gobgp:/go/src/github.com/osrg/gobgp \ 91 | -v $(CURDIR)/$(BIN):/outbin \ 92 | -w /go/src/github.com/osrg/gobgp \ 93 | -e LOCAL_USER_ID=$(LOCAL_USER_ID) \ 94 | -e ARCH=$(ARCH) \ 95 | -e GOARCH=$(ARCH) \ 96 | $(CALICO_BUILD) go build -v -o /outbin/gobgp github.com/osrg/gobgp/gobgp 97 | 98 | $(BIN)/calico-bgp-daemon: $(SRC_FILES) vendor $(BIN)/gobgp 99 | -mkdir -p $(@D) 100 | -mkdir -p .go-pkg-cache 101 | docker run --rm \ 102 | -v $(CURDIR):/go/src/$(PACKAGE_NAME) \ 103 | -e LOCAL_USER_ID=$(LOCAL_USER_ID) \ 104 | -v $(CURDIR)/.go-pkg-cache:/go-cache/:rw \ 105 | -e GOCACHE=/go-cache \ 106 | -e GOARCH=$(ARCH) \ 107 | $(CALICO_BUILD) sh -c '\ 108 | cd /go/src/$(PACKAGE_NAME) && \ 109 | go build -v -o $(BIN)/calico-bgp-daemon \ 110 | -ldflags "-X main.VERSION=$(GOBGPD_VERSION) -s -w" main.go ipam.go k8s.go' 111 | 112 | ############################################################################### 113 | # Building the image 114 | ############################################################################### 115 | image-all: $(addprefix sub-image-,$(ARCHES)) 116 | sub-image-%: 117 | $(MAKE) image ARCH=$* 118 | 119 | image: $(CONTAINER_NAME) 120 | $(CONTAINER_NAME): build 121 | docker build -t $(CONTAINER_NAME):latest-$(ARCH) -f Dockerfile.$(ARCH) . 122 | 123 | # ensure we have a real imagetag 124 | imagetag: 125 | ifndef IMAGETAG 126 | $(error IMAGETAG is undefined - run using make IMAGETAG=X.Y.Z) 127 | endif 128 | 129 | ## push one arch 130 | push: imagetag 131 | docker push $(CONTAINER_NAME):$(IMAGETAG)-$(ARCH) 132 | docker push quay.io/$(CONTAINER_NAME):$(IMAGETAG)-$(ARCH) 133 | ifeq ($(ARCH),amd64) 134 | docker push $(CONTAINER_NAME):$(IMAGETAG) 135 | docker push quay.io/$(CONTAINER_NAME):$(IMAGETAG) 136 | endif 137 | 138 | push-all: imagetag $(addprefix sub-push-,$(ARCHES)) 139 | sub-push-%: 140 | $(MAKE) push ARCH=$* IMAGETAG=$(IMAGETAG) 141 | 142 | ## tag images of one arch 143 | tag-images: imagetag 144 | docker tag $(CONTAINER_NAME):latest-$(ARCH) $(CONTAINER_NAME):$(IMAGETAG)-$(ARCH) 145 | docker tag $(CONTAINER_NAME):latest-$(ARCH) quay.io/$(CONTAINER_NAME):$(IMAGETAG)-$(ARCH) 146 | ifeq ($(ARCH),amd64) 147 | docker tag $(CONTAINER_NAME):latest-$(ARCH) $(CONTAINER_NAME):$(IMAGETAG) 148 | docker tag $(CONTAINER_NAME):latest-$(ARCH) quay.io/$(CONTAINER_NAME):$(IMAGETAG) 149 | endif 150 | 151 | ## tag images of all archs 152 | tag-images-all: imagetag $(addprefix sub-tag-images-,$(ARCHES)) 153 | sub-tag-images-%: 154 | $(MAKE) tag-images ARCH=$* IMAGETAG=$(IMAGETAG) 155 | 156 | ############################################################################### 157 | # Static checks 158 | ############################################################################### 159 | .PHONY: static-checks 160 | ## Perform static checks on the code. 161 | static-checks: vendor 162 | docker run --rm \ 163 | -e LOCAL_USER_ID=$(LOCAL_USER_ID) \ 164 | -v $(CURDIR):/go/src/$(PACKAGE_NAME) \ 165 | $(CALICO_BUILD) sh -c '\ 166 | cd /go/src/$(PACKAGE_NAME) && \ 167 | gometalinter --deadline=300s --disable-all --enable=goimports --vendor -s gobgp ./...' 168 | 169 | .PHONY: fix 170 | ## Fix static checks 171 | fix: 172 | goimports -w $(SRC_FILES) 173 | 174 | ############################################################################### 175 | # CI 176 | ############################################################################### 177 | .PHONY: ci 178 | ## Run what CI runs 179 | ci: static-checks 180 | 181 | ## Deploys images to registry 182 | cd: image 183 | ifndef CONFIRM 184 | $(error CONFIRM is undefined - run using make CONFIRM=true) 185 | endif 186 | ifndef BRANCH_NAME 187 | $(error BRANCH_NAME is undefined - run using make BRANCH_NAME=var or set an environment variable) 188 | endif 189 | $(MAKE) tag-images push IMAGETAG=${BRANCH_NAME} 190 | $(MAKE) tag-images push IMAGETAG=$(shell git describe --tags --dirty --always --long) 191 | 192 | ############################################################################### 193 | # Release 194 | ############################################################################### 195 | release: clean 196 | ifndef VERSION 197 | $(error VERSION is undefined - run using make release VERSION=vX.Y.Z) 198 | endif 199 | git tag $(VERSION) 200 | $(MAKE) $(CONTAINER_NAME) 201 | # Check that the version output appears on a line of its own (the -x option to grep). 202 | # Tests that the "git tag" makes it into the binary. Main point is to catch "-dirty" builds 203 | @echo "Checking if the tag made it into the binary" 204 | docker run --rm $(CONTAINER_NAME):latest-$(ARCH) -v | grep -x $(VERSION) || (echo "Reported version:" `docker run --rm $(CONTAINER_NAME):latest-$(ARCH) -v` "\nExpected version: $(VERSION)" && exit 1) 205 | 206 | $(MAKE) tag IMAGETAG=$(VERSION) ARCH=$(ARCH) 207 | $(MAKE) tag IMAGETAG=latest ARCH=$(ARCH) 208 | $(MAKE) push IMAGETAG=$(VERSION) ARCH=$(ARCH) 209 | $(MAKE) push IMAGETAG=latest ARCH=$(ARCH) 210 | 211 | @echo "Now create a release on Github and attach the $(BIN)/gobgpd and $(BIN)/gobgp binaries" 212 | @echo "git push origin $(VERSION)" 213 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://semaphoreci.com/api/v1/calico/calico-bgp-daemon/branches/master/badge.svg)](https://semaphoreci.com/calico/calico-bgp-daemon) 2 | 3 | # calico-bgp-daemon 4 | 5 | GoBGP based Calico BGP Daemon. This is a (currently experimental) BGP agent to use as an alternative 6 | to BIRD in the calico/node container image. 7 | -------------------------------------------------------------------------------- /glide.lock: -------------------------------------------------------------------------------- 1 | hash: a11c390e4326539e32a54ef6e71fbe5fae8adf7f6a836bb4a8ae4b81dc13efd0 2 | updated: 2017-10-04T00:59:10.714193307Z 3 | imports: 4 | - name: cloud.google.com/go 5 | version: 3b1ae45394a234c385be014e9a488f2bb6eef821 6 | subpackages: 7 | - compute/metadata 8 | - internal 9 | - name: github.com/armon/go-radix 10 | version: 4239b77079c7b5d1243b7b4736304ce8ddb6f0f2 11 | - name: github.com/coreos/etcd 12 | version: ac1c7eba21545c4ee025f2c340e143cacb53c754 13 | subpackages: 14 | - client 15 | - pkg/fileutil 16 | - pkg/pathutil 17 | - pkg/tlsutil 18 | - pkg/transport 19 | - pkg/types 20 | - name: github.com/coreos/go-oidc 21 | version: be73733bb8cc830d0205609b95d125215f8e9c70 22 | subpackages: 23 | - http 24 | - jose 25 | - key 26 | - oauth2 27 | - oidc 28 | - name: github.com/coreos/go-systemd 29 | version: 48702e0da86bd25e76cfef347e2adeb434a0d0a6 30 | subpackages: 31 | - daemon 32 | - journal 33 | - util 34 | - name: github.com/coreos/pkg 35 | version: 3ac0863d7acf3bc44daf49afef8919af12f704ef 36 | subpackages: 37 | - capnslog 38 | - health 39 | - httputil 40 | - timeutil 41 | - name: github.com/davecgh/go-spew 42 | version: 5215b55f46b2b919f50a1df0eaa5886afe4e3b3d 43 | subpackages: 44 | - spew 45 | - name: github.com/docker/distribution 46 | version: cd27f179f2c10c5d300e6d09025b538c475b0d51 47 | subpackages: 48 | - digest 49 | - reference 50 | - name: github.com/eapache/channels 51 | version: 47238d5aae8c0fefd518ef2bee46290909cf8263 52 | - name: github.com/eapache/queue 53 | version: 44cc805cf13205b55f69e14bcb69867d1ae92f98 54 | - name: github.com/emicklei/go-restful 55 | version: 09691a3b6378b740595c1002f40c34dd5f218a22 56 | subpackages: 57 | - log 58 | - swagger 59 | - name: github.com/fsnotify/fsnotify 60 | version: a904159b9206978bb6d53fcc7a769e5cd726c737 61 | - name: github.com/ghodss/yaml 62 | version: 73d445a93680fa1a78ae23a5839bad48f32ba1ee 63 | - name: github.com/go-openapi/jsonpointer 64 | version: 46af16f9f7b149af66e5d1bd010e3574dc06de98 65 | - name: github.com/go-openapi/jsonreference 66 | version: 13c6e3589ad90f49bd3e3bbe2c2cb3d7a4142272 67 | - name: github.com/go-openapi/spec 68 | version: 6aced65f8501fe1217321abf0749d354824ba2ff 69 | - name: github.com/go-openapi/swag 70 | version: 1d0bd113de87027671077d3c71eb3ac5d7dbba72 71 | - name: github.com/gogo/protobuf 72 | version: 909568be09de550ed094403c2bf8a261b5bb730a 73 | subpackages: 74 | - proto 75 | - sortkeys 76 | - name: github.com/golang/glog 77 | version: 44145f04b68cf362d9c4df2182967c2275eaefed 78 | - name: github.com/golang/protobuf 79 | version: 4bd1920723d7b7c925de087aa32e2187708897f7 80 | subpackages: 81 | - jsonpb 82 | - proto 83 | - name: github.com/google/gofuzz 84 | version: 44d81051d367757e1c7c6a5a86423ece9afcf63c 85 | - name: github.com/hashicorp/hcl 86 | version: 630949a3c5fa3c613328e1b8256052cbc2327c9b 87 | subpackages: 88 | - hcl/ast 89 | - hcl/parser 90 | - hcl/scanner 91 | - hcl/strconv 92 | - hcl/token 93 | - json/parser 94 | - json/scanner 95 | - json/token 96 | - name: github.com/howeyc/gopass 97 | version: 3ca23474a7c7203e0a0a070fd33508f6efdb9b3d 98 | - name: github.com/imdario/mergo 99 | version: 6633656539c1639d9d78127b7d47c622b5d7b6dc 100 | - name: github.com/influxdata/influxdb 101 | version: c83c742b49f2a22ab997081c19ea0fb44f2bb8fc 102 | subpackages: 103 | - client/v2 104 | - models 105 | - pkg/escape 106 | - name: github.com/jonboulle/clockwork 107 | version: 2eee05ed794112d45db504eb05aa693efd2b8b09 108 | - name: github.com/juju/ratelimit 109 | version: 77ed1c8a01217656d2080ad51981f6e99adaa177 110 | - name: github.com/kelseyhightower/envconfig 111 | version: 91921eb4cf999321cdbeebdba5a03555800d493b 112 | - name: github.com/magiconair/properties 113 | version: b3b15ef068fd0b17ddf408a23669f20811d194d2 114 | - name: github.com/mailru/easyjson 115 | version: d5b7844b561a7bc640052f1b935f7b800330d7e0 116 | subpackages: 117 | - buffer 118 | - jlexer 119 | - jwriter 120 | - name: github.com/mitchellh/mapstructure 121 | version: db1efb556f84b25a0a13a04aad883943538ad2e0 122 | - name: github.com/osrg/gobgp 123 | version: bbd1d99396fef6503e308d1851ecf91c31006635 124 | subpackages: 125 | - api 126 | - config 127 | - packet/bgp 128 | - packet/bmp 129 | - packet/mrt 130 | - packet/rtr 131 | - server 132 | - table 133 | - zebra 134 | - name: github.com/pelletier/go-buffruneio 135 | version: c37440a7cf42ac63b919c752ca73a85067e05992 136 | - name: github.com/pelletier/go-toml 137 | version: 361678322880708ac144df8575e6f01144ba1404 138 | - name: github.com/projectcalico/go-json 139 | version: 6219dc7339ba20ee4c57df0a8baac62317d19cb1 140 | subpackages: 141 | - json 142 | - name: github.com/projectcalico/go-yaml 143 | version: 955bc3e451ef0c9df8b9113bf2e341139cdafab2 144 | - name: github.com/projectcalico/go-yaml-wrapper 145 | version: 598e54215bee41a19677faa4f0c32acd2a87eb56 146 | - name: github.com/projectcalico/libcalico-go 147 | version: 09904c3edaef8e571a38cba4195d555537b8fcc2 148 | subpackages: 149 | - lib/api 150 | - lib/api/unversioned 151 | - lib/backend 152 | - lib/backend/api 153 | - lib/backend/compat 154 | - lib/backend/etcd 155 | - lib/backend/k8s 156 | - lib/backend/k8s/custom 157 | - lib/backend/k8s/resources 158 | - lib/backend/model 159 | - lib/client 160 | - lib/converter 161 | - lib/errors 162 | - lib/hash 163 | - lib/hwm 164 | - lib/ipip 165 | - lib/net 166 | - lib/numorstring 167 | - lib/scope 168 | - lib/selector 169 | - lib/selector/parser 170 | - lib/selector/tokenizer 171 | - lib/validator 172 | - name: github.com/PuerkitoBio/purell 173 | version: 8a290539e2e8629dbc4e6bad948158f790ec31f4 174 | - name: github.com/PuerkitoBio/urlesc 175 | version: 5bd2802263f21d8788851d5305584c82a5c75d7e 176 | - name: github.com/satori/go.uuid 177 | version: b061729afc07e77a8aa4fad0a2fd840958f1942a 178 | - name: github.com/sirupsen/logrus 179 | version: c078b1e43f58d563c74cebe63c85789e76ddb627 180 | - name: github.com/spf13/afero 181 | version: 9be650865eab0c12963d8753212f4f9c66cdcf12 182 | subpackages: 183 | - mem 184 | - name: github.com/spf13/cast 185 | version: f820543c3592e283e311a60d2a600a664e39f6f7 186 | - name: github.com/spf13/jwalterweatherman 187 | version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66 188 | - name: github.com/spf13/pflag 189 | version: 08b1a584251b5b62f458943640fc8ebd4d50aaa5 190 | - name: github.com/spf13/viper 191 | version: 7538d73b4eb9511d85a9f1dfef202eeb8ac260f4 192 | - name: github.com/ugorji/go 193 | version: ded73eae5db7e7a0ef6f55aace87a2873c5d2b74 194 | subpackages: 195 | - codec 196 | - name: github.com/vishvananda/netlink 197 | version: fe3b5664d23a11b52ba59bece4ff29c52772a56b 198 | subpackages: 199 | - nl 200 | - name: github.com/vishvananda/netns 201 | version: 54f0e4339ce73702a0607f49922aaa1e749b418d 202 | - name: golang.org/x/crypto 203 | version: 1351f936d976c60a0a48d728281922cf63eafb8d 204 | subpackages: 205 | - bcrypt 206 | - blowfish 207 | - ssh/terminal 208 | - name: golang.org/x/net 209 | version: f2499483f923065a842d38eb4c7f1927e6fc6e6d 210 | subpackages: 211 | - context 212 | - context/ctxhttp 213 | - http2 214 | - http2/hpack 215 | - idna 216 | - internal/timeseries 217 | - lex/httplex 218 | - trace 219 | - name: golang.org/x/oauth2 220 | version: 3c3a985cb79f52a3190fbc056984415ca6763d01 221 | subpackages: 222 | - google 223 | - internal 224 | - jws 225 | - jwt 226 | - name: golang.org/x/sys 227 | version: 8f0908ab3b2457e2e15403d3697c9ef5cb4b57a9 228 | subpackages: 229 | - unix 230 | - name: golang.org/x/text 231 | version: 19e51611da83d6be54ddafce4a4af510cb3e9ea4 232 | subpackages: 233 | - cases 234 | - internal 235 | - internal/tag 236 | - language 237 | - runes 238 | - secure/bidirule 239 | - secure/precis 240 | - transform 241 | - unicode/bidi 242 | - unicode/norm 243 | - width 244 | - name: google.golang.org/appengine 245 | version: 4f7eeb5305a4ba1966344836ba4af9996b7b4e05 246 | subpackages: 247 | - internal 248 | - internal/app_identity 249 | - internal/base 250 | - internal/datastore 251 | - internal/log 252 | - internal/modules 253 | - internal/remote_api 254 | - internal/urlfetch 255 | - urlfetch 256 | - name: google.golang.org/grpc 257 | version: 777daa17ff9b5daef1cfdf915088a2ada3332bf0 258 | subpackages: 259 | - codes 260 | - credentials 261 | - grpclog 262 | - internal 263 | - metadata 264 | - naming 265 | - peer 266 | - transport 267 | - name: gopkg.in/go-playground/validator.v8 268 | version: 5f57d2222ad794d0dffb07e664ea05e2ee07d60c 269 | - name: gopkg.in/inf.v0 270 | version: 3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4 271 | - name: gopkg.in/tchap/go-patricia.v2 272 | version: 666120de432aea38ab06bd5c818f04f4129882c9 273 | subpackages: 274 | - patricia 275 | - name: gopkg.in/tomb.v2 276 | version: d5d1b5820637886def9eef33e03a27a9f166942c 277 | - name: gopkg.in/yaml.v2 278 | version: 53feefa2559fb8dfa8d81baad31be332c97d6c77 279 | - name: k8s.io/apimachinery 280 | version: b317fa7ec8e0e7d1f77ac63bf8c3ec7b29a2a215 281 | subpackages: 282 | - pkg/api/errors 283 | - pkg/api/meta 284 | - pkg/api/resource 285 | - pkg/apimachinery 286 | - pkg/apimachinery/announced 287 | - pkg/apimachinery/registered 288 | - pkg/apis/meta/v1 289 | - pkg/apis/meta/v1/unstructured 290 | - pkg/conversion 291 | - pkg/conversion/queryparams 292 | - pkg/fields 293 | - pkg/labels 294 | - pkg/openapi 295 | - pkg/runtime 296 | - pkg/runtime/schema 297 | - pkg/runtime/serializer 298 | - pkg/runtime/serializer/json 299 | - pkg/runtime/serializer/protobuf 300 | - pkg/runtime/serializer/recognizer 301 | - pkg/runtime/serializer/streaming 302 | - pkg/runtime/serializer/versioning 303 | - pkg/selection 304 | - pkg/types 305 | - pkg/util/diff 306 | - pkg/util/errors 307 | - pkg/util/framer 308 | - pkg/util/intstr 309 | - pkg/util/json 310 | - pkg/util/net 311 | - pkg/util/rand 312 | - pkg/util/runtime 313 | - pkg/util/sets 314 | - pkg/util/validation 315 | - pkg/util/validation/field 316 | - pkg/util/wait 317 | - pkg/util/yaml 318 | - pkg/version 319 | - pkg/watch 320 | - third_party/forked/golang/reflect 321 | - name: k8s.io/client-go 322 | version: 4a3ab2f5be5177366f8206fd79ce55ca80e417fa 323 | subpackages: 324 | - discovery 325 | - kubernetes 326 | - kubernetes/scheme 327 | - kubernetes/typed/apps/v1beta1 328 | - kubernetes/typed/authentication/v1 329 | - kubernetes/typed/authentication/v1beta1 330 | - kubernetes/typed/authorization/v1 331 | - kubernetes/typed/authorization/v1beta1 332 | - kubernetes/typed/autoscaling/v1 333 | - kubernetes/typed/autoscaling/v2alpha1 334 | - kubernetes/typed/batch/v1 335 | - kubernetes/typed/batch/v2alpha1 336 | - kubernetes/typed/certificates/v1beta1 337 | - kubernetes/typed/core/v1 338 | - kubernetes/typed/extensions/v1beta1 339 | - kubernetes/typed/policy/v1beta1 340 | - kubernetes/typed/rbac/v1alpha1 341 | - kubernetes/typed/rbac/v1beta1 342 | - kubernetes/typed/settings/v1alpha1 343 | - kubernetes/typed/storage/v1 344 | - kubernetes/typed/storage/v1beta1 345 | - pkg/api 346 | - pkg/api/install 347 | - pkg/api/v1 348 | - pkg/apis/apps 349 | - pkg/apis/apps/install 350 | - pkg/apis/apps/v1beta1 351 | - pkg/apis/authentication 352 | - pkg/apis/authentication/install 353 | - pkg/apis/authentication/v1 354 | - pkg/apis/authentication/v1beta1 355 | - pkg/apis/authorization 356 | - pkg/apis/authorization/install 357 | - pkg/apis/authorization/v1 358 | - pkg/apis/authorization/v1beta1 359 | - pkg/apis/autoscaling 360 | - pkg/apis/autoscaling/install 361 | - pkg/apis/autoscaling/v1 362 | - pkg/apis/autoscaling/v2alpha1 363 | - pkg/apis/batch 364 | - pkg/apis/batch/install 365 | - pkg/apis/batch/v1 366 | - pkg/apis/batch/v2alpha1 367 | - pkg/apis/certificates 368 | - pkg/apis/certificates/install 369 | - pkg/apis/certificates/v1beta1 370 | - pkg/apis/extensions 371 | - pkg/apis/extensions/install 372 | - pkg/apis/extensions/v1beta1 373 | - pkg/apis/policy 374 | - pkg/apis/policy/install 375 | - pkg/apis/policy/v1beta1 376 | - pkg/apis/rbac 377 | - pkg/apis/rbac/install 378 | - pkg/apis/rbac/v1alpha1 379 | - pkg/apis/rbac/v1beta1 380 | - pkg/apis/settings 381 | - pkg/apis/settings/install 382 | - pkg/apis/settings/v1alpha1 383 | - pkg/apis/storage 384 | - pkg/apis/storage/install 385 | - pkg/apis/storage/v1 386 | - pkg/apis/storage/v1beta1 387 | - pkg/util 388 | - pkg/util/parsers 389 | - pkg/version 390 | - plugin/pkg/client/auth 391 | - plugin/pkg/client/auth/gcp 392 | - plugin/pkg/client/auth/oidc 393 | - rest 394 | - rest/watch 395 | - third_party/forked/golang/template 396 | - tools/auth 397 | - tools/cache 398 | - tools/clientcmd 399 | - tools/clientcmd/api 400 | - tools/clientcmd/api/latest 401 | - tools/clientcmd/api/v1 402 | - tools/metrics 403 | - transport 404 | - util/cert 405 | - util/clock 406 | - util/flowcontrol 407 | - util/homedir 408 | - util/integer 409 | - util/jsonpath 410 | testImports: [] 411 | -------------------------------------------------------------------------------- /glide.yaml: -------------------------------------------------------------------------------- 1 | package: github.com/projectcalico/calico-bgp-daemon 2 | import: 3 | - package: github.com/sirupsen/logrus 4 | version: v0.11.2 5 | - package: github.com/coreos/etcd 6 | version: v3.1.1 7 | subpackages: 8 | - client 9 | - pkg/transport 10 | - package: github.com/osrg/gobgp 11 | version: v1.22 12 | subpackages: 13 | - api 14 | - config 15 | - packet/bgp 16 | - server 17 | - table 18 | - package: github.com/projectcalico/libcalico-go 19 | version: v1.6.1 20 | subpackages: 21 | - lib/api 22 | - lib/client 23 | - lib/numorstring 24 | - lib/scope 25 | - package: github.com/vishvananda/netlink 26 | - package: golang.org/x/net 27 | subpackages: 28 | - context 29 | - package: gopkg.in/tomb.v2 30 | - package: k8s.io/client-go 31 | version: 4a3ab2f5be5177366f8206fd79ce55ca80e417fa 32 | -------------------------------------------------------------------------------- /ipam.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2017 Nippon Telegraph and Telephone Corporation. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 | // implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package main 17 | 18 | import ( 19 | "encoding/json" 20 | "fmt" 21 | "reflect" 22 | "strings" 23 | "sync" 24 | 25 | etcd "github.com/coreos/etcd/client" 26 | "github.com/osrg/gobgp/table" 27 | log "github.com/sirupsen/logrus" 28 | "golang.org/x/net/context" 29 | ) 30 | 31 | type ipPool struct { 32 | CIDR string `json:"cidr"` 33 | IPIP string `json:"ipip"` 34 | Mode string `json:"ipip_mode"` 35 | } 36 | 37 | func (lhs *ipPool) equal(rhs *ipPool) bool { 38 | if lhs == rhs { 39 | return true 40 | } 41 | if lhs == nil || rhs == nil { 42 | return false 43 | } 44 | return lhs.CIDR == rhs.CIDR && lhs.IPIP == rhs.IPIP && lhs.Mode == rhs.Mode 45 | } 46 | 47 | // Contain returns true if this ipPool contains 'prefix' 48 | func (p *ipPool) contain(prefix string) bool { 49 | k := table.CidrToRadixkey(prefix) 50 | l := table.CidrToRadixkey(p.CIDR) 51 | return strings.HasPrefix(k, l) 52 | } 53 | 54 | type ipamCache struct { 55 | mu sync.RWMutex 56 | m map[string]*ipPool 57 | etcdAPI etcd.KeysAPI 58 | updateHandler func(*ipPool) error 59 | ready bool 60 | readyCond *sync.Cond 61 | } 62 | 63 | // match checks whether we have an IP pool which contains the given prefix. 64 | // If we have, it returns the pool. 65 | func (c *ipamCache) match(prefix string) *ipPool { 66 | if !c.ready { 67 | c.readyCond.L.Lock() 68 | for !c.ready { 69 | c.readyCond.Wait() 70 | } 71 | c.readyCond.L.Unlock() 72 | } 73 | c.mu.RLock() 74 | defer c.mu.RUnlock() 75 | for _, p := range c.m { 76 | if p.contain(prefix) { 77 | return p 78 | } 79 | } 80 | return nil 81 | } 82 | 83 | // update updates the internal map with IPAM updates when the update 84 | // is new addtion to the map or changes the existing item, it calls 85 | // updateHandler 86 | func (c *ipamCache) update(nodeEtcd interface{}, del bool) error { 87 | if reflect.TypeOf(nodeEtcd) != reflect.TypeOf(&etcd.Node{}) { 88 | log.Panicf("unknown parameter type: %s", reflect.TypeOf(nodeEtcd)) 89 | } 90 | node := nodeEtcd.(*etcd.Node) 91 | c.mu.Lock() 92 | defer c.mu.Unlock() 93 | log.Printf("update ipam cache: %s, %v, %t", node.Key, node.Value, del) 94 | if node.Dir { 95 | return nil 96 | } 97 | p := &ipPool{} 98 | if err := json.Unmarshal([]byte(node.Value), p); err != nil { 99 | return err 100 | } 101 | if p.CIDR == "" { 102 | return fmt.Errorf("empty cidr: %s", node.Value) 103 | } 104 | q := c.m[p.CIDR] 105 | if del { 106 | delete(c.m, p.CIDR) 107 | return nil 108 | } else if p.equal(q) { 109 | return nil 110 | } 111 | 112 | c.m[p.CIDR] = p 113 | 114 | if c.updateHandler != nil { 115 | return c.updateHandler(p) 116 | } 117 | return nil 118 | } 119 | 120 | func (c *ipamCache) syncsubr(n *etcd.Node) error { 121 | for _, node := range n.Nodes { 122 | if node.Dir { 123 | if err := c.syncsubr(node); err != nil { 124 | return err 125 | } 126 | } else { 127 | if err := c.update(node, false); err != nil { 128 | return err 129 | } 130 | } 131 | } 132 | return nil 133 | } 134 | 135 | // sync synchronizes the contents under /calico/v1/ipam 136 | func (c *ipamCache) sync() error { 137 | res, err := c.etcdAPI.Get(context.Background(), CALICO_IPAM, &etcd.GetOptions{Recursive: true}) 138 | if err != nil { 139 | return err 140 | } 141 | 142 | var index uint64 143 | index = res.Index 144 | for _, node := range res.Node.Nodes { 145 | if node.ModifiedIndex > index { 146 | index = node.ModifiedIndex 147 | } 148 | if err = c.syncsubr(node); err != nil { 149 | return err 150 | } 151 | } 152 | c.ready = true 153 | c.readyCond.Broadcast() 154 | 155 | watcher := c.etcdAPI.Watcher(CALICO_IPAM, &etcd.WatcherOptions{Recursive: true, AfterIndex: index}) 156 | for { 157 | res, err := watcher.Next(context.Background()) 158 | if err != nil { 159 | return err 160 | } 161 | del := false 162 | node := res.Node 163 | switch res.Action { 164 | case "set", "create", "update", "compareAndSwap": 165 | case "delete": 166 | del = true 167 | node = res.PrevNode 168 | default: 169 | log.Printf("unhandled action: %s", res.Action) 170 | continue 171 | } 172 | if err = c.update(node, del); err != nil { 173 | return err 174 | } 175 | } 176 | return nil 177 | } 178 | 179 | // create new IPAM cache 180 | func newIPAMCache(api etcd.KeysAPI, updateHandler func(*ipPool) error) *ipamCache { 181 | cond := sync.NewCond(&sync.Mutex{}) 182 | return &ipamCache{ 183 | m: make(map[string]*ipPool), 184 | updateHandler: updateHandler, 185 | etcdAPI: api, 186 | readyCond: cond, 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /k8s.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013 Kelsey Hightower 2 | // 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | // this software and associated documentation files (the "Software"), to deal in 5 | // the Software without restriction, including without limitation the rights to 6 | // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | // of the Software, and to permit persons to whom the Software is furnished to do 8 | // so, subject to the following conditions: 9 | // 10 | // The above copyright notice and this permission notice shall be included in all 11 | // copies or substantial portions of the Software. 12 | // 13 | // Copyright (C) 2017 VA Linux Systems Japan K.K. 14 | // Copyright (C) 2017 Fumihiko Kakuma 15 | // 16 | // Licensed under the Apache License, Version 2.0 (the "License"); you may 17 | // not use this file except in compliance with the License. You may obtain 18 | // a copy of the License at 19 | // 20 | // http://www.apache.org/licenses/LICENSE-2.0 21 | // 22 | // Unless required by applicable law or agreed to in writing, software 23 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 24 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 25 | // License for the specific language governing permissions and limitations 26 | // under the License. 27 | // 28 | // NOTE: 29 | // Some codes of this file are from backends/k8s/client.go on 30 | // https://github.com/projectcalico/confd repository. 31 | 32 | package main 33 | 34 | import ( 35 | "encoding/json" 36 | "errors" 37 | "fmt" 38 | "os" 39 | "reflect" 40 | "strings" 41 | "sync" 42 | "time" 43 | 44 | backendapi "github.com/projectcalico/libcalico-go/lib/backend/api" 45 | "github.com/projectcalico/libcalico-go/lib/backend/compat" 46 | "github.com/projectcalico/libcalico-go/lib/backend/k8s/resources" 47 | "github.com/projectcalico/libcalico-go/lib/backend/model" 48 | "github.com/projectcalico/libcalico-go/lib/numorstring" 49 | 50 | svbgpconfig "github.com/osrg/gobgp/config" 51 | svbgptable "github.com/osrg/gobgp/table" 52 | log "github.com/sirupsen/logrus" 53 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 54 | "k8s.io/client-go/kubernetes" 55 | kapiv1 "k8s.io/client-go/pkg/api/v1" 56 | "k8s.io/client-go/tools/clientcmd" 57 | ) 58 | 59 | const ( 60 | Act_add = "add" 61 | Act_upd = "upd" 62 | Act_del = "del" 63 | Act_same = "same" 64 | ) 65 | 66 | type ActionList struct { 67 | Add []string 68 | Upd []string 69 | Del []string 70 | Same []string 71 | } 72 | 73 | func CompareMap(lasts map[string]string, currs map[string]string) ActionList { 74 | act := ActionList{} 75 | for key, last := range lasts { 76 | if cur, ok := currs[key]; ok == false { 77 | act.Del = append(act.Del, key) 78 | } else if last != cur { 79 | act.Upd = append(act.Upd, key) 80 | } else { 81 | act.Same = append(act.Same, key) 82 | } 83 | } 84 | for key, _ := range currs { 85 | if _, ok := lasts[key]; ok == false { 86 | act.Add = append(act.Add, key) 87 | } 88 | } 89 | return act 90 | } 91 | 92 | // populateFromKVPairs populates the vars KV map from the supplied set of 93 | // KVPairs. This uses the libcalico-go compat module and serialization functions 94 | // to write out the KVPairs in etcdv2 format. This works in conjunction with the 95 | // etcdVarClient defined below which provides a "mock" etcd backend which actually 96 | // just writes out data to the vars map. 97 | func populateFromKVPairs(kvps []*model.KVPair, vars map[string]string) { 98 | // Create a etcdVarClient to write the KVP results in the vars map, using the 99 | // compat adaptor to write the values in etcdv2 format. 100 | client := compat.NewAdaptor(&etcdVarClient{vars: vars}) 101 | for _, kvp := range kvps { 102 | if _, err := client.Apply(kvp); err != nil { 103 | log.Error("Failed to convert k8s data to etcdv2 equivalent: %s = %s", kvp.Key, kvp.Value) 104 | } 105 | } 106 | } 107 | 108 | type IntervalProcessor struct { 109 | interval int 110 | k8scli *k8sClient 111 | ipam *ipamCacheK8s 112 | } 113 | 114 | func (p *IntervalProcessor) IntervalLoop() error { 115 | if err := p.k8scli.updatePrefix(); err != nil { 116 | return err 117 | } 118 | if err := p.k8scli.initialNeighborConfigSetting(); err != nil { 119 | return err 120 | } 121 | for { 122 | log.Debug("polling") 123 | if err := p.ipam.sync(); err != nil { 124 | log.Debugf("ipam sync err: %s", err) 125 | return err 126 | } 127 | if err := p.k8scli.checkBGPConfig(); err != nil { 128 | log.Debugf("bgpconfig err: %s", err) 129 | return err 130 | } 131 | time.Sleep(time.Duration(p.interval) * time.Second) 132 | } 133 | } 134 | 135 | type k8sClient struct { 136 | node string 137 | server *Server 138 | k8scli *kubernetes.Clientset 139 | nodeBgpPeerClient resources.K8sNodeResourceClient 140 | nodeBgpCfgClient resources.K8sNodeResourceClient 141 | lastBgpconfig map[string]string 142 | } 143 | 144 | // create new Kubernetes client 145 | func NewK8sClient(s *Server) (*k8sClient, error) { 146 | loadingRules := clientcmd.ClientConfigLoadingRules{} 147 | config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( 148 | &loadingRules, &clientcmd.ConfigOverrides{}).ClientConfig() 149 | if err != nil { 150 | return nil, err 151 | } 152 | 153 | // Create the clientset 154 | cs, err := kubernetes.NewForConfig(config) 155 | if err != nil { 156 | return nil, err 157 | } 158 | return &k8sClient{ 159 | node: os.Getenv(NODENAME), 160 | server: s, 161 | k8scli: cs, 162 | nodeBgpPeerClient: resources.NewNodeBGPPeerClient(cs), 163 | nodeBgpCfgClient: resources.NewNodeBGPConfigClient(cs), 164 | }, nil 165 | } 166 | 167 | func (c *k8sClient) updatePrefix() error { 168 | var paths []*svbgptable.Path 169 | node, err := c.k8scli.Nodes().Get(c.node, metav1.GetOptions{}) 170 | if err != nil { 171 | return err 172 | } 173 | cidr := node.Spec.PodCIDR 174 | path, err := c.server.makePath(cidr, false) 175 | log.Debugf("Set prefix: %#v", path) 176 | paths = append(paths, path) 177 | if err = c.server.updatePrefixSet(paths); err != nil { 178 | return err 179 | } 180 | if _, err := c.server.bgpServer.AddPath("", paths); err != nil { 181 | return err 182 | } 183 | c.server.prefixReady <- 1 184 | return nil 185 | } 186 | 187 | func (c *k8sClient) initialNeighborConfigSetting() error { 188 | bgpconfig, err := c.getBGPConfig() 189 | if err != nil { 190 | return err 191 | } 192 | c.lastBgpconfig = bgpconfig 193 | neighborConfigs, err := c.getNeighborConfigs(c.lastBgpconfig) 194 | if err != nil { 195 | return err 196 | } 197 | for _, n := range neighborConfigs { 198 | if err = c.server.bgpServer.AddNeighbor(n); err != nil { 199 | return err 200 | } 201 | } 202 | return nil 203 | } 204 | 205 | // getNeighborConfigs returns the complete list of BGP neighbor configuration 206 | // which the node should peer. 207 | func (c *k8sClient) getNeighborConfigs(bgpconfig map[string]string) ([]*svbgpconfig.Neighbor, error) { 208 | var neighbors []*svbgpconfig.Neighbor 209 | if mesh, ok := bgpconfig[GlobalNodeMesh]; ok == false { 210 | return nil, errors.New("mesh data not found") 211 | } else if mesh == `{"enabled":true}` { 212 | log.Debug("enable mesh") 213 | ns, err := c.server.getMeshNeighborConfigs() 214 | if err != nil { 215 | return nil, err 216 | } 217 | neighbors = append(neighbors, ns...) 218 | } 219 | // --- Global peers --- 220 | if ns, err := c.server.getGlobalNeighborConfigs(); err != nil { 221 | return nil, err 222 | } else { 223 | neighbors = append(neighbors, ns...) 224 | } 225 | // --- Node-specific peers --- 226 | if ns, err := c.server.getNodeSpecificNeighborConfigs(); err != nil { 227 | return nil, err 228 | } else { 229 | neighbors = append(neighbors, ns...) 230 | } 231 | log.Debugf("neighbors=%s", neighbors) 232 | return neighbors, nil 233 | } 234 | 235 | // checkBGPConfig checks the difference from the last BGP config information. 236 | // But in a case of the following changing, return error. 237 | // /calico/bgp/v1/host/$NODENAME or /calico/global/as_num 238 | func (c *k8sClient) checkBGPConfig() error { 239 | curBgpconfig, err := c.getBGPConfig() 240 | if err != nil { 241 | return nil 242 | } 243 | log.Debugf("checkBGPConfig lastBgpconfig: %s", c.lastBgpconfig) 244 | if reflect.DeepEqual(c.lastBgpconfig, curBgpconfig) { 245 | return nil 246 | } 247 | act := CompareMap(c.lastBgpconfig, curBgpconfig) 248 | log.Debugf("checkBGPConfig action list: %#v", act) 249 | for _, key := range act.Add { 250 | if err := c.updateBGPConfig(Act_add, key, curBgpconfig); err != nil { 251 | return err 252 | } 253 | } 254 | for _, key := range act.Upd { 255 | if err := c.updateBGPConfig(Act_upd, key, curBgpconfig); err != nil { 256 | return err 257 | } 258 | } 259 | for _, key := range act.Del { 260 | if err := c.updateBGPConfig(Act_del, key, c.lastBgpconfig); err != nil { 261 | return err 262 | } 263 | } 264 | c.lastBgpconfig = curBgpconfig 265 | return nil 266 | } 267 | 268 | func (c *k8sClient) updateBGPConfig(action string, key string, bgpconfig map[string]string) error { 269 | 270 | handleNonMeshNeighbor := func(neighborType string, peer string) error { 271 | n, err := getNeighborConfigFromPeer(peer, neighborType) 272 | if err != nil { 273 | return err 274 | } 275 | switch action { 276 | case Act_del: 277 | return c.server.bgpServer.DeleteNeighbor(n) 278 | case Act_add, Act_upd: 279 | return c.server.bgpServer.AddNeighbor(n) 280 | } 281 | log.Printf("Unhandled action: %s", action) 282 | return nil 283 | } 284 | 285 | var err error = nil 286 | value := bgpconfig[key] 287 | switch { 288 | case strings.HasPrefix(key, fmt.Sprintf("%s/peer_", GlobalBGP)): 289 | err = handleNonMeshNeighbor("global", value) 290 | case strings.HasPrefix(key, fmt.Sprintf("%s/%s/peer_", AllNodes, c.node)): 291 | err = handleNonMeshNeighbor("node", value) 292 | case strings.HasPrefix(key, fmt.Sprintf("%s/%s", AllNodes, c.node)): 293 | log.Println("Local host config update. Restart") 294 | os.Exit(1) 295 | case strings.HasPrefix(key, AllNodes): 296 | elems := strings.Split(key, "/") 297 | if len(elems) < 4 { 298 | log.Printf("Unhandled key: %s", key) 299 | return nil 300 | } 301 | deleteNeighbor := func(address string) error { 302 | if address == "" { 303 | return nil 304 | } 305 | n := &svbgpconfig.Neighbor{ 306 | Config: svbgpconfig.NeighborConfig{ 307 | NeighborAddress: address, 308 | }, 309 | } 310 | return c.server.bgpServer.DeleteNeighbor(n) 311 | } 312 | host := elems[len(elems)-2] 313 | switch elems[len(elems)-1] { 314 | case "ip_addr_v4", "ip_addr_v6": 315 | switch action { 316 | case Act_del: 317 | if err = deleteNeighbor(value); err != nil { 318 | return err 319 | } 320 | case Act_add, Act_upd: 321 | if action == Act_upd { 322 | if err = deleteNeighbor(c.lastBgpconfig[key]); err != nil { 323 | return err 324 | } 325 | } 326 | if value == "" { 327 | return nil 328 | } 329 | asn, err := c.server.getPeerASN(host) 330 | if err != nil { 331 | return err 332 | } 333 | n := &svbgpconfig.Neighbor{ 334 | Config: svbgpconfig.NeighborConfig{ 335 | NeighborAddress: value, 336 | PeerAs: uint32(asn), 337 | Description: fmt.Sprintf("Mesh_%s", underscore(value)), 338 | }, 339 | } 340 | if err = c.server.bgpServer.AddNeighbor(n); err != nil { 341 | return err 342 | } 343 | } 344 | case "as_num": 345 | var asn numorstring.ASNumber 346 | if action == Act_upd { 347 | asn, err = numorstring.ASNumberFromString(value) 348 | if err != nil { 349 | return err 350 | } 351 | } else { 352 | asn, err = c.server.getNodeASN() 353 | if err != nil { 354 | return err 355 | } 356 | } 357 | for _, version := range []string{"v4", "v6"} { 358 | ip, ok := bgpconfig[fmt.Sprintf("%s/%s/ip_addr_%s", AllNodes, host, version)] 359 | if ok == false { 360 | return errors.New("ip address data not found") 361 | } 362 | if ip == "" { 363 | continue 364 | } 365 | if err = deleteNeighbor(ip); err != nil { 366 | return err 367 | } 368 | n := &svbgpconfig.Neighbor{ 369 | Config: svbgpconfig.NeighborConfig{ 370 | NeighborAddress: ip, 371 | PeerAs: uint32(asn), 372 | Description: fmt.Sprintf("Mesh_%s", underscore(value)), 373 | }, 374 | } 375 | if err = c.server.bgpServer.AddNeighbor(n); err != nil { 376 | return err 377 | } 378 | } 379 | default: 380 | log.Printf("Unhandled key: %s", key) 381 | } 382 | case strings.HasPrefix(key, fmt.Sprintf("%s/as_num", GlobalBGP)): 383 | log.Println("Global AS number update. Restart") 384 | os.Exit(1) 385 | case strings.HasPrefix(key, fmt.Sprintf("%s/node_mesh", GlobalBGP)): 386 | mesh, err := c.server.isMeshMode() 387 | if err != nil { 388 | return err 389 | } 390 | ns, err := c.server.getMeshNeighborConfigs() 391 | if err != nil { 392 | return err 393 | } 394 | for _, n := range ns { 395 | if mesh { 396 | err = c.server.bgpServer.AddNeighbor(n) 397 | } else { 398 | err = c.server.bgpServer.DeleteNeighbor(n) 399 | } 400 | if err != nil { 401 | return err 402 | } 403 | } 404 | } 405 | return err 406 | } 407 | 408 | func (c *k8sClient) getBGPConfig() (map[string]string, error) { 409 | var bgpconfig = make(map[string]string) 410 | 411 | calicoK8sCl := c.server.client.Backend 412 | 413 | // Set default values for fields that we always expect to have. 414 | bgpconfig[GlobalLogging] = "info" 415 | bgpconfig[GlobalASN] = "64512" 416 | bgpconfig[GlobalNodeMesh] = `{"enabled":true}` 417 | 418 | // Global data consists of both global config and global peers. 419 | kvps, err := calicoK8sCl.List(model.GlobalBGPConfigListOptions{}) 420 | if err != nil { 421 | return nil, err 422 | } 423 | populateFromKVPairs(kvps, bgpconfig) 424 | 425 | kvps, err = calicoK8sCl.List(model.GlobalBGPPeerListOptions{}) 426 | if err != nil { 427 | return nil, err 428 | } 429 | populateFromKVPairs(kvps, bgpconfig) 430 | 431 | nodes, err := c.k8scli.Nodes().List(metav1.ListOptions{}) 432 | if err != nil { 433 | return nil, err 434 | } 435 | for _, kNode := range nodes.Items { 436 | err := c.populateNodeDetails(&kNode, bgpconfig) 437 | if err != nil { 438 | return nil, err 439 | } 440 | } 441 | 442 | log.Debugf("Get bgp config: %s", bgpconfig) 443 | return bgpconfig, err 444 | } 445 | 446 | // populateNodeDetails populates the given kvps map with values we track from the k8s Node object. 447 | func (c *k8sClient) populateNodeDetails(kNode *kapiv1.Node, vars map[string]string) error { 448 | kvps := []*model.KVPair{} 449 | 450 | // Start with the main Node configuration 451 | cNode, err := resources.K8sNodeToCalico(kNode) 452 | if err != nil { 453 | log.Error("Failed to parse k8s Node into Calico Node") 454 | return err 455 | } 456 | kvps = append(kvps, cNode) 457 | 458 | // Add per-node BGP config (each of the per-node resource clients also implements 459 | // the CustomK8sNodeResourceList interface, used to extract per-node resources from 460 | // the Node resource. 461 | if cfg, err := c.nodeBgpCfgClient.ExtractResourcesFromNode(kNode); err != nil { 462 | log.Error("Failed to parse BGP configs from node resource - skip config data") 463 | } else { 464 | kvps = append(kvps, cfg...) 465 | } 466 | 467 | if peers, err := c.nodeBgpPeerClient.ExtractResourcesFromNode(kNode); err != nil { 468 | log.Error("Failed to parse BGP peers from node resource - skip config data") 469 | } else { 470 | kvps = append(kvps, peers...) 471 | } 472 | 473 | // Populate the vars map from the KVPairs. 474 | populateFromKVPairs(kvps, vars) 475 | 476 | return nil 477 | } 478 | 479 | // etcdVarClient implements the libcalico-go backend api.Client interface. It is used to 480 | // write the KVPairs retrieved from the Kubernetes datastore driver into the KV map 481 | // using etcdv2 naming scheme. 482 | type etcdVarClient struct { 483 | vars map[string]string 484 | } 485 | 486 | func (c *etcdVarClient) Create(kvp *model.KVPair) (*model.KVPair, error) { 487 | log.Fatal("Create should not be invoked") 488 | return nil, nil 489 | } 490 | 491 | func (c *etcdVarClient) Update(kvp *model.KVPair) (*model.KVPair, error) { 492 | log.Fatal("Update should not be invoked") 493 | return nil, nil 494 | } 495 | 496 | func (c *etcdVarClient) Apply(kvp *model.KVPair) (*model.KVPair, error) { 497 | path, err := model.KeyToDefaultPath(kvp.Key) 498 | if err != nil { 499 | log.Error("Unable to create path from Key: %s", kvp.Key) 500 | return nil, err 501 | } 502 | value, err := model.SerializeValue(kvp) 503 | if err != nil { 504 | log.Error("Unable to serialize value: %s", kvp.Key) 505 | return nil, err 506 | } 507 | c.vars[path] = string(value) 508 | return kvp, nil 509 | } 510 | 511 | func (c *etcdVarClient) Delete(kvp *model.KVPair) error { 512 | // Delete may be invoked as part of the Apply processing for multi-key resource. 513 | // However, since we start from an empty map each time, we never need to delete entries, 514 | // so just ignore this request. 515 | log.Debug("Delete ignored") 516 | return nil 517 | } 518 | 519 | func (c *etcdVarClient) Get(key model.Key) (*model.KVPair, error) { 520 | log.Fatal("Get should not be invoked") 521 | return nil, nil 522 | } 523 | 524 | func (c *etcdVarClient) List(list model.ListInterface) ([]*model.KVPair, error) { 525 | log.Fatal("List should not be invoked") 526 | return nil, nil 527 | } 528 | 529 | func (c *etcdVarClient) Syncer(callbacks backendapi.SyncerCallbacks) backendapi.Syncer { 530 | log.Fatal("Syncer should not be invoked") 531 | return nil 532 | } 533 | 534 | func (c *etcdVarClient) EnsureInitialized() error { 535 | log.Fatal("EnsureIntialized should not be invoked") 536 | return nil 537 | } 538 | 539 | func (c *etcdVarClient) EnsureCalicoNodeInitialized(node string) error { 540 | log.Fatal("EnsureCalicoNodeInitialized should not be invoked") 541 | return nil 542 | } 543 | 544 | type ipamCacheK8s struct { 545 | mu sync.RWMutex 546 | m map[string]*ipPool 547 | server *Server 548 | updateHandler func(*ipPool) error 549 | lastIPPool map[string]string 550 | } 551 | 552 | // create new IPAM cache 553 | func NewIPAMCacheK8s(s *Server, updateHandler func(*ipPool) error) *ipamCacheK8s { 554 | return &ipamCacheK8s{ 555 | m: make(map[string]*ipPool), 556 | server: s, 557 | updateHandler: updateHandler, 558 | } 559 | } 560 | 561 | // match checks whether we have an IP pool which contains the given prefix. 562 | // If we have, it returns the pool. 563 | func (c *ipamCacheK8s) match(prefix string) *ipPool { 564 | c.mu.RLock() 565 | defer c.mu.RUnlock() 566 | for _, p := range c.m { 567 | if p.contain(prefix) { 568 | return p 569 | } 570 | } 571 | return nil 572 | } 573 | 574 | // update updates the internal map with IPAM updates when the update 575 | // is new addtion to the map or changes the existing item, it calls 576 | // updateHandler 577 | func (c *ipamCacheK8s) update(ipPoolData interface{}, del bool) error { 578 | if reflect.TypeOf(ipPoolData) != reflect.TypeOf("") { 579 | log.Panicf("unknown parameter type: %s", reflect.TypeOf(ipPoolData)) 580 | } 581 | ippool := ipPoolData.(string) 582 | c.mu.Lock() 583 | defer c.mu.Unlock() 584 | log.Printf("update ipam cache: %s %t", ippool, del) 585 | if ippool == "" { 586 | return nil 587 | } 588 | p := &ipPool{} 589 | if err := json.Unmarshal([]byte(ippool), p); err != nil { 590 | return err 591 | } 592 | if p.CIDR == "" { 593 | return fmt.Errorf("empty cidr: %s", ippool) 594 | } 595 | q := c.m[p.CIDR] 596 | if del { 597 | delete(c.m, p.CIDR) 598 | return nil 599 | } else if p.equal(q) { 600 | return nil 601 | } 602 | 603 | c.m[p.CIDR] = p 604 | 605 | if c.updateHandler != nil { 606 | return c.updateHandler(p) 607 | } 608 | return nil 609 | } 610 | 611 | func (c *ipamCacheK8s) getIPPools() (map[string]string, error) { 612 | var ippools = make(map[string]string) 613 | kvps, err := c.server.client.Backend.List(model.IPPoolListOptions{}) 614 | if err != nil { 615 | return nil, err 616 | } 617 | populateFromKVPairs(kvps, ippools) 618 | log.Debugf("Get ip pool: %s", ippools) 619 | return ippools, nil 620 | } 621 | 622 | // sync synchronizes the contents under /calico/v1/ipam 623 | func (c *ipamCacheK8s) sync() error { 624 | currIPPool, err := c.getIPPools() 625 | if err != nil { 626 | return err 627 | } 628 | log.Debugf("sync lastIPPool: %s", c.lastIPPool) 629 | if reflect.DeepEqual(c.lastIPPool, currIPPool) { 630 | return nil 631 | } 632 | act := CompareMap(c.lastIPPool, currIPPool) 633 | log.Debugf("sync action list: %#v", act) 634 | for _, key := range append(act.Add, act.Upd...) { 635 | if err := c.update(currIPPool[key], false); err != nil { 636 | return err 637 | } 638 | } 639 | for _, key := range act.Del { 640 | if err := c.update(c.lastIPPool[key], true); err != nil { 641 | return err 642 | } 643 | } 644 | c.lastIPPool = currIPPool 645 | return nil 646 | } 647 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2016-2017 Nippon Telegraph and Telephone Corporation. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 | // implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package main 17 | 18 | import ( 19 | "encoding/json" 20 | "flag" 21 | "fmt" 22 | "net" 23 | "os" 24 | "strconv" 25 | "strings" 26 | "syscall" 27 | "time" 28 | 29 | etcd "github.com/coreos/etcd/client" 30 | "github.com/coreos/etcd/pkg/transport" 31 | bgpapi "github.com/osrg/gobgp/api" 32 | bgpconfig "github.com/osrg/gobgp/config" 33 | bgp "github.com/osrg/gobgp/packet/bgp" 34 | bgpserver "github.com/osrg/gobgp/server" 35 | bgptable "github.com/osrg/gobgp/table" 36 | calicoapi "github.com/projectcalico/libcalico-go/lib/api" 37 | calicocli "github.com/projectcalico/libcalico-go/lib/client" 38 | "github.com/projectcalico/libcalico-go/lib/numorstring" 39 | calicoscope "github.com/projectcalico/libcalico-go/lib/scope" 40 | log "github.com/sirupsen/logrus" 41 | "github.com/vishvananda/netlink" 42 | "golang.org/x/net/context" 43 | "gopkg.in/tomb.v2" 44 | ) 45 | 46 | const ( 47 | NODENAME = "NODENAME" 48 | INTERVAL = "BGPD_INTERVAL" 49 | AS = "AS" 50 | CALICO_PREFIX = "/calico" 51 | CALICO_BGP = CALICO_PREFIX + "/bgp/v1" 52 | CALICO_AGGR = CALICO_PREFIX + "/ipam/v2/host" 53 | CALICO_IPAM = CALICO_PREFIX + "/v1/ipam" 54 | 55 | IpPoolV4 = CALICO_IPAM + "/v4/pool" 56 | GlobalBGP = CALICO_BGP + "/global" 57 | GlobalASN = GlobalBGP + "/as_num" 58 | GlobalNodeMesh = GlobalBGP + "/node_mesh" 59 | GlobalLogging = GlobalBGP + "/loglevel" 60 | AllNodes = CALICO_BGP + "/host" 61 | 62 | PollingInterval = 300 63 | defaultDialTimeout = 30 * time.Second 64 | 65 | aggregatedPrefixSetName = "aggregated" 66 | hostPrefixSetName = "host" 67 | 68 | RTPROT_GOBGP = 0x11 69 | ) 70 | 71 | type IpamCache interface { 72 | match(string) *ipPool 73 | update(interface{}, bool) error 74 | sync() error 75 | } 76 | 77 | // VERSION is filled out during the build process (using git describe output) 78 | var VERSION string 79 | 80 | func underscore(ip string) string { 81 | return strings.Map(func(r rune) rune { 82 | switch r { 83 | case '.', ':': 84 | return '_' 85 | } 86 | return r 87 | }, ip) 88 | } 89 | 90 | func errorButKeyNotFound(err error) error { 91 | if e, ok := err.(etcd.Error); ok && e.Code == etcd.ErrorCodeKeyNotFound { 92 | return nil 93 | } 94 | return err 95 | } 96 | 97 | func getEtcdConfig(cfg *calicoapi.CalicoAPIConfig) (etcd.Config, error) { 98 | var config etcd.Config 99 | etcdcfg := cfg.Spec.EtcdConfig 100 | etcdEndpoints := etcdcfg.EtcdEndpoints 101 | if etcdEndpoints == "" { 102 | etcdEndpoints = fmt.Sprintf("%s://%s", etcdcfg.EtcdScheme, etcdcfg.EtcdAuthority) 103 | } 104 | tls := transport.TLSInfo{ 105 | CAFile: etcdcfg.EtcdCACertFile, 106 | CertFile: etcdcfg.EtcdCertFile, 107 | KeyFile: etcdcfg.EtcdKeyFile, 108 | } 109 | t, err := transport.NewTransport(tls, defaultDialTimeout) 110 | if err != nil { 111 | return config, err 112 | } 113 | config.Endpoints = strings.Split(etcdEndpoints, ",") 114 | config.Transport = t 115 | return config, nil 116 | } 117 | 118 | // recursiveNexthopLookup returns bgpNexthop's actual nexthop 119 | // In GCE environment, the interface address is /32 and the BGP nexthop is 120 | // off-subnet. This function looks up kernel RIB and returns a nexthop to 121 | // reach the BGP nexthop. 122 | // When the BGP nexthop can be reached with a connected route, 123 | // this function returns the BGP nexthop. 124 | func recursiveNexthopLookup(bgpNexthop net.IP) (net.IP, error) { 125 | routes, err := netlink.RouteGet(bgpNexthop) 126 | if err != nil { 127 | return nil, err 128 | } 129 | if len(routes) == 0 { 130 | return nil, fmt.Errorf("no route for path: %s", bgpNexthop) 131 | } 132 | r := routes[0] 133 | if r.Gw != nil { 134 | return r.Gw, nil 135 | } 136 | // bgpNexthop can be reached by a connected route 137 | return bgpNexthop, nil 138 | } 139 | 140 | func cleanUpRoutes() error { 141 | log.Println("Clean up injected routes") 142 | filter := &netlink.Route{ 143 | Protocol: RTPROT_GOBGP, 144 | } 145 | list4, err := netlink.RouteListFiltered(netlink.FAMILY_V4, filter, netlink.RT_FILTER_PROTOCOL) 146 | if err != nil { 147 | return err 148 | } 149 | list6, err := netlink.RouteListFiltered(netlink.FAMILY_V6, filter, netlink.RT_FILTER_PROTOCOL) 150 | if err != nil { 151 | return err 152 | } 153 | for _, route := range append(list4, list6...) { 154 | netlink.RouteDel(&route) 155 | } 156 | return nil 157 | } 158 | 159 | type Server struct { 160 | t tomb.Tomb 161 | bgpServer *bgpserver.BgpServer 162 | datastore calicoapi.DatastoreType 163 | client *calicocli.Client 164 | etcd etcd.KeysAPI 165 | process *IntervalProcessor 166 | ipv4 net.IP 167 | ipv6 net.IP 168 | ipam IpamCache 169 | reloadCh chan []*bgptable.Path 170 | prefixReady chan int 171 | } 172 | 173 | func NewServer() (*Server, error) { 174 | config, err := calicocli.LoadClientConfigFromEnvironment() 175 | if err != nil { 176 | return nil, err 177 | } 178 | 179 | calicoCli, err := calicocli.New(*config) 180 | if err != nil { 181 | return nil, err 182 | } 183 | 184 | node, err := calicoCli.Nodes().Get(calicoapi.NodeMetadata{Name: os.Getenv(NODENAME)}) 185 | if err != nil { 186 | return nil, err 187 | } 188 | 189 | if node.Spec.BGP == nil { 190 | return nil, fmt.Errorf("Calico is running in policy-only mode") 191 | } 192 | var ipv4, ipv6 net.IP 193 | if ipnet := node.Spec.BGP.IPv4Address; ipnet != nil { 194 | ipv4 = ipnet.IP 195 | } 196 | if ipnet := node.Spec.BGP.IPv6Address; ipnet != nil { 197 | ipv6 = ipnet.IP 198 | } 199 | 200 | bgpServer := bgpserver.NewBgpServer() 201 | 202 | datastoreType := config.Spec.DatastoreType 203 | server := Server{ 204 | bgpServer: bgpServer, 205 | datastore: datastoreType, 206 | client: calicoCli, 207 | ipv4: ipv4, 208 | ipv6: ipv6, 209 | reloadCh: make(chan []*bgptable.Path), 210 | prefixReady: make(chan int), 211 | } 212 | 213 | if datastoreType == calicoapi.EtcdV2 { 214 | etcdConfig, err := getEtcdConfig(config) 215 | if err != nil { 216 | return nil, err 217 | } 218 | cli, err := etcd.New(etcdConfig) 219 | if err != nil { 220 | return nil, err 221 | } 222 | server.etcd = etcd.NewKeysAPI(cli) 223 | } else if datastoreType == calicoapi.Kubernetes { 224 | k8s, err := NewK8sClient(&server) 225 | if err != nil { 226 | return nil, err 227 | } 228 | ipam := NewIPAMCacheK8s(&server, server.ipamUpdateHandler) 229 | server.ipam = ipam 230 | interval := PollingInterval 231 | i, err := strconv.Atoi(os.Getenv(INTERVAL)) 232 | if err == nil { 233 | interval = i 234 | } 235 | server.process = &IntervalProcessor{ 236 | interval: interval, 237 | k8scli: k8s, 238 | ipam: ipam, 239 | } 240 | } else { 241 | log.Fatal("unsupported datastore type: ", datastoreType) 242 | } 243 | 244 | return &server, nil 245 | } 246 | 247 | func (s *Server) Serve() { 248 | s.t.Go(func() error { 249 | s.bgpServer.Serve() 250 | return nil 251 | }) 252 | 253 | bgpAPIServer := bgpapi.NewGrpcServer(s.bgpServer, ":50051") 254 | s.t.Go(bgpAPIServer.Serve) 255 | 256 | globalConfig, err := s.getGlobalConfig() 257 | if err != nil { 258 | log.Fatal(err) 259 | } 260 | 261 | if err := s.bgpServer.Start(globalConfig); err != nil { 262 | log.Fatal("failed to start BGP server:", err) 263 | } 264 | 265 | if err := s.initialPolicySetting(); err != nil { 266 | log.Fatal(err) 267 | } 268 | 269 | if s.datastore == calicoapi.EtcdV2 { 270 | s.ipam = newIPAMCache(s.etcd, s.ipamUpdateHandler) 271 | // sync IPAM and call ipamUpdateHandler 272 | s.t.Go(func() error { return fmt.Errorf("syncIPAM: %s", s.ipam.sync()) }) 273 | // watch prefix assigned and announce to other BGP peers 274 | s.t.Go(func() error { return fmt.Errorf("watchPrefix: %s", s.watchPrefix()) }) 275 | // watch BGP configuration 276 | s.t.Go(func() error { return fmt.Errorf("watchBGPConfig: %s", s.watchBGPConfig()) }) 277 | } else if s.datastore == calicoapi.Kubernetes { 278 | s.t.Go(func() error { return fmt.Errorf("k8s interval loop: %s", s.process.IntervalLoop()) }) 279 | } 280 | // watch routes from other BGP peers and update FIB 281 | s.t.Go(func() error { return fmt.Errorf("watchBGPPath: %s", s.watchBGPPath()) }) 282 | 283 | // watch routes added by kernel and announce to other BGP peers 284 | s.t.Go(func() error { return fmt.Errorf("watchKernelRoute: %s", s.watchKernelRoute()) }) 285 | 286 | <-s.t.Dying() 287 | 288 | if err := cleanUpRoutes(); err != nil { 289 | log.Fatalf("%s, also failed to clean up routes which we injected: %s", s.t.Err(), err) 290 | } 291 | log.Fatal(s.t.Err()) 292 | 293 | } 294 | 295 | func isCrossSubnet(gw net.IP, subnet net.IPNet) bool { 296 | p := &ipPool{CIDR: subnet.String()} 297 | result := !p.contain(gw.String() + "/32") 298 | return result 299 | } 300 | 301 | func (s *Server) ipamUpdateHandler(pool *ipPool) error { 302 | filter := &netlink.Route{ 303 | Protocol: RTPROT_GOBGP, 304 | } 305 | list, err := netlink.RouteListFiltered(netlink.FAMILY_V4, filter, netlink.RT_FILTER_PROTOCOL) 306 | if err != nil { 307 | return err 308 | } 309 | node, err := s.client.Nodes().Get(calicoapi.NodeMetadata{Name: os.Getenv(NODENAME)}) 310 | if err != nil { 311 | return err 312 | } 313 | 314 | for _, route := range list { 315 | if route.Dst == nil { 316 | continue 317 | } 318 | prefix := route.Dst.String() 319 | if pool.contain(prefix) { 320 | ipip := pool.IPIP != "" 321 | if pool.Mode == "cross-subnet" && !isCrossSubnet(route.Gw, node.Spec.BGP.IPv4Address.Network().IPNet) { 322 | ipip = false 323 | } 324 | if ipip { 325 | i, err := net.InterfaceByName(pool.IPIP) 326 | if err != nil { 327 | return err 328 | } 329 | route.LinkIndex = i.Index 330 | route.SetFlag(netlink.FLAG_ONLINK) 331 | } else { 332 | tbl, err := s.bgpServer.GetRib("", bgp.RF_IPv4_UC, []*bgptable.LookupPrefix{ 333 | &bgptable.LookupPrefix{ 334 | Prefix: prefix, 335 | }, 336 | }) 337 | if err != nil { 338 | return err 339 | } 340 | bests := tbl.Bests("") 341 | if len(bests) == 0 { 342 | log.Printf("no best for %s", prefix) 343 | continue 344 | } 345 | best := bests[0] 346 | if best.IsLocal() { 347 | log.Printf("%s's best is local path", prefix) 348 | continue 349 | } 350 | gw, err := recursiveNexthopLookup(best.GetNexthop()) 351 | if err != nil { 352 | return err 353 | } 354 | route.Gw = gw 355 | route.Flags = 0 356 | rs, err := netlink.RouteGet(gw) 357 | if err != nil { 358 | return err 359 | } 360 | if len(rs) == 0 { 361 | return fmt.Errorf("no route for path: %s", gw) 362 | } 363 | r := rs[0] 364 | route.LinkIndex = r.LinkIndex 365 | } 366 | return netlink.RouteReplace(&route) 367 | } 368 | } 369 | return nil 370 | } 371 | 372 | func (s *Server) getNodeASN() (numorstring.ASNumber, error) { 373 | return s.getPeerASN(os.Getenv(NODENAME)) 374 | } 375 | 376 | func (s *Server) getPeerASN(host string) (numorstring.ASNumber, error) { 377 | node, err := s.client.Nodes().Get(calicoapi.NodeMetadata{Name: host}) 378 | if err != nil { 379 | return 0, err 380 | } 381 | if node.Spec.BGP == nil { 382 | return 0, fmt.Errorf("host %s is running in policy-only mode") 383 | } 384 | asn := node.Spec.BGP.ASNumber 385 | if asn == nil { 386 | return s.client.Config().GetGlobalASNumber() 387 | } 388 | return *asn, nil 389 | 390 | } 391 | 392 | func (s *Server) getGlobalConfig() (*bgpconfig.Global, error) { 393 | asn, err := s.getNodeASN() 394 | if err != nil { 395 | return nil, err 396 | } 397 | return &bgpconfig.Global{ 398 | Config: bgpconfig.GlobalConfig{ 399 | As: uint32(asn), 400 | RouterId: s.ipv4.String(), 401 | }, 402 | }, nil 403 | } 404 | 405 | func (s *Server) isMeshMode() (bool, error) { 406 | return s.client.Config().GetNodeToNodeMesh() 407 | } 408 | 409 | // getMeshNeighborConfigs returns the list of mesh BGP neighbor configuration struct 410 | func (s *Server) getMeshNeighborConfigs() ([]*bgpconfig.Neighbor, error) { 411 | globalASN, err := s.getNodeASN() 412 | if err != nil { 413 | return nil, err 414 | } 415 | nodes, err := s.client.Nodes().List(calicoapi.NodeMetadata{}) 416 | if err != nil { 417 | return nil, err 418 | } 419 | ns := make([]*bgpconfig.Neighbor, 0, len(nodes.Items)) 420 | for _, node := range nodes.Items { 421 | if node.Metadata.Name == os.Getenv(NODENAME) { 422 | continue 423 | } 424 | peerASN := globalASN 425 | spec := node.Spec.BGP 426 | if spec == nil { 427 | continue 428 | } 429 | 430 | asn := spec.ASNumber 431 | if asn != nil { 432 | peerASN = *asn 433 | } 434 | if v4 := spec.IPv4Address; v4 != nil { 435 | ip := v4.IP.String() 436 | id := strings.Replace(ip, ".", "_", -1) 437 | ns = append(ns, &bgpconfig.Neighbor{ 438 | Config: bgpconfig.NeighborConfig{ 439 | NeighborAddress: ip, 440 | PeerAs: uint32(peerASN), 441 | Description: fmt.Sprintf("Mesh_%s", id), 442 | }, 443 | }) 444 | } 445 | if v6 := spec.IPv6Address; v6 != nil { 446 | ip := v6.IP.String() 447 | id := strings.Replace(ip, ":", "_", -1) 448 | ns = append(ns, &bgpconfig.Neighbor{ 449 | Config: bgpconfig.NeighborConfig{ 450 | NeighborAddress: ip, 451 | PeerAs: uint32(peerASN), 452 | Description: fmt.Sprintf("Mesh_%s", id), 453 | }, 454 | }) 455 | } 456 | } 457 | return ns, nil 458 | 459 | } 460 | 461 | // getNeighborConfigFromPeer returns a BGP neighbor configuration struct from *etcd.Node 462 | func getNeighborConfigFromPeer(peer string, neighborType string) (*bgpconfig.Neighbor, error) { 463 | m := &struct { 464 | IP string `json:"ip"` 465 | ASN string `json:"as_num"` 466 | }{} 467 | if err := json.Unmarshal([]byte(peer), m); err != nil { 468 | return nil, err 469 | } 470 | asn, err := numorstring.ASNumberFromString(m.ASN) 471 | if err != nil { 472 | return nil, err 473 | } 474 | return &bgpconfig.Neighbor{ 475 | Config: bgpconfig.NeighborConfig{ 476 | NeighborAddress: m.IP, 477 | PeerAs: uint32(asn), 478 | Description: fmt.Sprintf("%s_%s", strings.Title(neighborType), underscore(m.IP)), 479 | }, 480 | }, nil 481 | } 482 | 483 | // getNonMeshNeighborConfigs returns the list of non-mesh BGP neighbor configuration struct 484 | // valid neighborType is either "global" or "node" 485 | func (s *Server) getNonMeshNeighborConfigs(neighborType string) ([]*bgpconfig.Neighbor, error) { 486 | var metadata calicoapi.BGPPeerMetadata 487 | switch neighborType { 488 | case "global": 489 | metadata.Scope = calicoscope.Global 490 | case "node": 491 | metadata.Scope = calicoscope.Node 492 | metadata.Node = os.Getenv(NODENAME) 493 | default: 494 | return nil, fmt.Errorf("invalid neighbor type: %s", neighborType) 495 | } 496 | list, err := s.client.BGPPeers().List(metadata) 497 | if err != nil { 498 | return nil, err 499 | } 500 | ns := make([]*bgpconfig.Neighbor, 0, len(list.Items)) 501 | for _, node := range list.Items { 502 | addr := node.Metadata.PeerIP.String() 503 | ns = append(ns, &bgpconfig.Neighbor{ 504 | Config: bgpconfig.NeighborConfig{ 505 | NeighborAddress: addr, 506 | PeerAs: uint32(node.Spec.ASNumber), 507 | Description: fmt.Sprintf("%s_%s", strings.Title(neighborType), underscore(addr)), 508 | }, 509 | }) 510 | } 511 | return ns, nil 512 | } 513 | 514 | // getGlobalNeighborConfigs returns the list of global BGP neighbor configuration struct 515 | func (s *Server) getGlobalNeighborConfigs() ([]*bgpconfig.Neighbor, error) { 516 | return s.getNonMeshNeighborConfigs("global") 517 | } 518 | 519 | // getNodeNeighborConfigs returns the list of node specific BGP neighbor configuration struct 520 | func (s *Server) getNodeSpecificNeighborConfigs() ([]*bgpconfig.Neighbor, error) { 521 | return s.getNonMeshNeighborConfigs("node") 522 | } 523 | 524 | // getNeighborConfigs returns the complete list of BGP neighbor configuration 525 | // which the node should peer. 526 | func (s *Server) getNeighborConfigs() ([]*bgpconfig.Neighbor, error) { 527 | var neighbors []*bgpconfig.Neighbor 528 | // --- Node-to-node mesh --- 529 | if mesh, err := s.isMeshMode(); err == nil && mesh { 530 | ns, err := s.getMeshNeighborConfigs() 531 | if err != nil { 532 | return nil, err 533 | } 534 | neighbors = append(neighbors, ns...) 535 | } else if err != nil { 536 | return nil, err 537 | } 538 | // --- Global peers --- 539 | if ns, err := s.getGlobalNeighborConfigs(); err != nil { 540 | return nil, err 541 | } else { 542 | neighbors = append(neighbors, ns...) 543 | } 544 | // --- Node-specific peers --- 545 | if ns, err := s.getNodeSpecificNeighborConfigs(); err != nil { 546 | return nil, err 547 | } else { 548 | neighbors = append(neighbors, ns...) 549 | } 550 | return neighbors, nil 551 | } 552 | 553 | func etcdKeyToPrefix(key string) string { 554 | path := strings.Split(key, "/") 555 | return strings.Replace(path[len(path)-1], "-", "/", 1) 556 | } 557 | 558 | func (s *Server) makePath(prefix string, isWithdrawal bool) (*bgptable.Path, error) { 559 | _, ipNet, err := net.ParseCIDR(prefix) 560 | if err != nil { 561 | return nil, err 562 | } 563 | 564 | p := ipNet.IP 565 | masklen, _ := ipNet.Mask.Size() 566 | v4 := true 567 | if p.To4() == nil { 568 | v4 = false 569 | } 570 | 571 | var nlri bgp.AddrPrefixInterface 572 | attrs := []bgp.PathAttributeInterface{ 573 | bgp.NewPathAttributeOrigin(0), 574 | } 575 | 576 | if v4 { 577 | nlri = bgp.NewIPAddrPrefix(uint8(masklen), p.String()) 578 | attrs = append(attrs, bgp.NewPathAttributeNextHop(s.ipv4.String())) 579 | } else { 580 | nlri = bgp.NewIPv6AddrPrefix(uint8(masklen), p.String()) 581 | attrs = append(attrs, bgp.NewPathAttributeMpReachNLRI(s.ipv6.String(), []bgp.AddrPrefixInterface{nlri})) 582 | } 583 | 584 | return bgptable.NewPath(nil, nlri, isWithdrawal, attrs, time.Now(), false), nil 585 | } 586 | 587 | // getAssignedPrefixes retrives prefixes assigned to the node and returns them as a 588 | // list of BGP path. 589 | // using etcd directly since libcalico-go doesn't seem to have a method to return 590 | // assigned prefixes yet. 591 | func (s *Server) getAssignedPrefixes(api etcd.KeysAPI) ([]*bgptable.Path, uint64, error) { 592 | var ps []*bgptable.Path 593 | var index uint64 594 | f := func(version string) error { 595 | res, err := api.Get(context.Background(), fmt.Sprintf("%s/%s/%s/block", CALICO_AGGR, os.Getenv(NODENAME), version), &etcd.GetOptions{Recursive: true}) 596 | if err != nil { 597 | return err 598 | } 599 | if index == 0 { 600 | index = res.Index 601 | } 602 | for _, v := range res.Node.Nodes { 603 | path, err := s.makePath(etcdKeyToPrefix(v.Key), false) 604 | if err != nil { 605 | return err 606 | } 607 | ps = append(ps, path) 608 | } 609 | return nil 610 | } 611 | if s.ipv4 != nil { 612 | if err := f("ipv4"); err != nil { 613 | return nil, 0, err 614 | } 615 | } 616 | if s.ipv6 != nil { 617 | if err := f("ipv6"); err != nil { 618 | return nil, 0, err 619 | } 620 | } 621 | return ps, index, nil 622 | } 623 | 624 | // watchPrefix watches etcd /calico/ipam/v2/host/$NODENAME and add/delete 625 | // aggregated routes which are assigned to the node. 626 | // This function also updates policy appropriately. 627 | func (s *Server) watchPrefix() error { 628 | 629 | paths, index, err := s.getAssignedPrefixes(s.etcd) 630 | if err != nil { 631 | return err 632 | } 633 | 634 | if err = s.updatePrefixSet(paths); err != nil { 635 | return err 636 | } 637 | 638 | if _, err := s.bgpServer.AddPath("", paths); err != nil { 639 | return err 640 | } 641 | s.prefixReady <- 1 642 | 643 | watcher := s.etcd.Watcher(fmt.Sprintf("%s/%s", CALICO_AGGR, os.Getenv(NODENAME)), &etcd.WatcherOptions{Recursive: true, AfterIndex: index}) 644 | for { 645 | var err error 646 | res, err := watcher.Next(context.Background()) 647 | if err != nil { 648 | return err 649 | } 650 | var path *bgptable.Path 651 | key := etcdKeyToPrefix(res.Node.Key) 652 | if res.Action == "delete" { 653 | path, err = s.makePath(key, true) 654 | } else { 655 | path, err = s.makePath(key, false) 656 | } 657 | if err != nil { 658 | return err 659 | } 660 | paths := []*bgptable.Path{path} 661 | if err = s.updatePrefixSet(paths); err != nil { 662 | return err 663 | } 664 | if _, err := s.bgpServer.AddPath("", paths); err != nil { 665 | return err 666 | } 667 | log.Printf("add path: %s", path) 668 | } 669 | } 670 | 671 | func (s *Server) AddNeighbor(n *bgpconfig.Neighbor) error { 672 | n.GracefulRestart.Config.Enabled = true 673 | n.GracefulRestart.Config.RestartTime = 120 674 | n.GracefulRestart.Config.LongLivedEnabled = true 675 | n.GracefulRestart.Config.NotificationEnabled = true 676 | ipAddr, err := net.ResolveIPAddr("ip", n.Config.NeighborAddress) 677 | var typ bgpconfig.AfiSafiType 678 | if err == nil { 679 | if ipAddr.IP.To4() == nil { 680 | typ = bgpconfig.AFI_SAFI_TYPE_IPV6_UNICAST 681 | } else { 682 | typ = bgpconfig.AFI_SAFI_TYPE_IPV4_UNICAST 683 | } 684 | } 685 | 686 | n.AfiSafis = []bgpconfig.AfiSafi{ 687 | bgpconfig.AfiSafi{ 688 | Config: bgpconfig.AfiSafiConfig{ 689 | AfiSafiName: typ, 690 | Enabled: true, 691 | }, 692 | MpGracefulRestart: bgpconfig.MpGracefulRestart{ 693 | Config: bgpconfig.MpGracefulRestartConfig{ 694 | Enabled: true, 695 | }, 696 | }, 697 | State: bgpconfig.AfiSafiState{ 698 | AfiSafiName: typ, 699 | }, 700 | }, 701 | } 702 | log.Printf("AddNeighbor neighbor=%#v", n) 703 | log.Printf("AddNeighbor neighbor=%s", n) 704 | if err := s.bgpServer.AddNeighbor(n); err != nil { 705 | return err 706 | } 707 | return nil 708 | } 709 | 710 | // watchBGPConfig watches etcd path /calico/bgp/v1 and handle various changes 711 | // in etcd. Though this method tries to minimize effects to the existing BGP peers, 712 | // when /calico/bgp/v1/host/$NODENAME or /calico/global/as_num is changed, 713 | // give up handling the change and return error (this leads calico-bgp-daemon to be restarted) 714 | func (s *Server) watchBGPConfig() error { 715 | var index uint64 716 | res, err := s.etcd.Get(context.Background(), CALICO_BGP, nil) 717 | if err != nil { 718 | return err 719 | } 720 | index = res.Index 721 | 722 | neighborConfigs, err := s.getNeighborConfigs() 723 | if err != nil { 724 | return err 725 | } 726 | 727 | for _, n := range neighborConfigs { 728 | if err = s.AddNeighbor(n); err != nil { 729 | return err 730 | } 731 | } 732 | 733 | watcher := s.etcd.Watcher(CALICO_BGP, &etcd.WatcherOptions{Recursive: true, AfterIndex: index}) 734 | for { 735 | res, err := watcher.Next(context.Background()) 736 | if err != nil { 737 | return err 738 | } 739 | prev := "" 740 | if res.PrevNode != nil { 741 | prev = res.PrevNode.Value 742 | } 743 | log.Printf("watch: action: %s, key: %s node: %s, prev-node: %s", res.Action, res.Node.Key, res.Node.Value, prev) 744 | if res.Action == "set" && res.Node.Value == prev { 745 | log.Printf("same value. ignore") 746 | continue 747 | } 748 | 749 | handleNonMeshNeighbor := func(neighborType string) error { 750 | switch res.Action { 751 | case "delete": 752 | n, err := getNeighborConfigFromPeer(res.PrevNode.Value, neighborType) 753 | if err != nil { 754 | return err 755 | } 756 | return s.bgpServer.DeleteNeighbor(n) 757 | case "set", "create", "update", "compareAndSwap": 758 | n, err := getNeighborConfigFromPeer(res.Node.Value, neighborType) 759 | if err != nil { 760 | return err 761 | } 762 | return s.AddNeighbor(n) 763 | } 764 | log.Printf("unhandled action: %s", res.Action) 765 | return nil 766 | } 767 | 768 | key := res.Node.Key 769 | switch { 770 | case strings.HasPrefix(key, fmt.Sprintf("%s/global/peer_", CALICO_BGP)): 771 | err = handleNonMeshNeighbor("global") 772 | case strings.HasPrefix(key, fmt.Sprintf("%s/host/%s/peer_", CALICO_BGP, os.Getenv(NODENAME))): 773 | err = handleNonMeshNeighbor("node") 774 | case strings.HasPrefix(key, fmt.Sprintf("%s/host/%s", CALICO_BGP, os.Getenv(NODENAME))): 775 | log.Println("Local host config update. Restart") 776 | os.Exit(1) 777 | case strings.HasPrefix(key, fmt.Sprintf("%s/host", CALICO_BGP)): 778 | elems := strings.Split(key, "/") 779 | if len(elems) < 4 { 780 | log.Printf("unhandled key: %s", key) 781 | continue 782 | } 783 | deleteNeighbor := func(node *etcd.Node) error { 784 | if node.Value == "" { 785 | return nil 786 | } 787 | n := &bgpconfig.Neighbor{ 788 | Config: bgpconfig.NeighborConfig{ 789 | NeighborAddress: node.Value, 790 | }, 791 | } 792 | return s.bgpServer.DeleteNeighbor(n) 793 | } 794 | host := elems[len(elems)-2] 795 | switch elems[len(elems)-1] { 796 | case "ip_addr_v4", "ip_addr_v6": 797 | switch res.Action { 798 | case "delete": 799 | if err = deleteNeighbor(res.PrevNode); err != nil { 800 | return err 801 | } 802 | case "set": 803 | if res.PrevNode != nil { 804 | if err = deleteNeighbor(res.PrevNode); err != nil { 805 | return err 806 | } 807 | } 808 | if res.Node.Value == "" { 809 | continue 810 | } 811 | asn, err := s.getPeerASN(host) 812 | if err != nil { 813 | return err 814 | } 815 | n := &bgpconfig.Neighbor{ 816 | Config: bgpconfig.NeighborConfig{ 817 | NeighborAddress: res.Node.Value, 818 | PeerAs: uint32(asn), 819 | Description: fmt.Sprintf("Mesh_%s", underscore(res.Node.Value)), 820 | }, 821 | } 822 | if err = s.AddNeighbor(n); err != nil { 823 | return err 824 | } 825 | } 826 | case "as_num": 827 | var asn numorstring.ASNumber 828 | if res.Action == "set" { 829 | asn, err = numorstring.ASNumberFromString(res.Node.Value) 830 | if err != nil { 831 | return err 832 | } 833 | } else { 834 | asn, err = s.getNodeASN() 835 | if err != nil { 836 | return err 837 | } 838 | } 839 | for _, version := range []string{"v4", "v6"} { 840 | res, err := s.etcd.Get(context.Background(), fmt.Sprintf("%s/host/%s/ip_addr_%s", CALICO_BGP, host, version), nil) 841 | if errorButKeyNotFound(err) != nil { 842 | return err 843 | } 844 | if res == nil { 845 | continue 846 | } 847 | if err = deleteNeighbor(res.Node); err != nil { 848 | return err 849 | } 850 | ip := res.Node.Value 851 | n := &bgpconfig.Neighbor{ 852 | Config: bgpconfig.NeighborConfig{ 853 | NeighborAddress: ip, 854 | PeerAs: uint32(asn), 855 | Description: fmt.Sprintf("Mesh_%s", underscore(ip)), 856 | }, 857 | } 858 | if err = s.AddNeighbor(n); err != nil { 859 | return err 860 | } 861 | } 862 | default: 863 | log.Printf("unhandled key: %s", key) 864 | } 865 | case strings.HasPrefix(key, fmt.Sprintf("%s/global/as_num", CALICO_BGP)): 866 | log.Println("Global AS number update. Restart") 867 | os.Exit(1) 868 | case strings.HasPrefix(key, fmt.Sprintf("%s/global/node_mesh", CALICO_BGP)): 869 | mesh, err := s.isMeshMode() 870 | if err != nil { 871 | return err 872 | } 873 | ns, err := s.getMeshNeighborConfigs() 874 | if err != nil { 875 | return err 876 | } 877 | for _, n := range ns { 878 | if mesh { 879 | err = s.AddNeighbor(n) 880 | } else { 881 | err = s.bgpServer.DeleteNeighbor(n) 882 | } 883 | if err != nil { 884 | return err 885 | } 886 | } 887 | } 888 | if err != nil { 889 | return err 890 | } 891 | } 892 | } 893 | 894 | // watchKernelRoute receives netlink route update notification and announces 895 | // kernel/boot routes using BGP. 896 | func (s *Server) watchKernelRoute() error { 897 | err := s.loadKernelRoute() 898 | if err != nil { 899 | return err 900 | } 901 | 902 | ch := make(chan netlink.RouteUpdate) 903 | err = netlink.RouteSubscribe(ch, nil) 904 | if err != nil { 905 | return err 906 | } 907 | for update := range ch { 908 | log.Printf("kernel update: %s", update) 909 | if update.Table == syscall.RT_TABLE_MAIN && (update.Protocol == syscall.RTPROT_KERNEL || update.Protocol == syscall.RTPROT_BOOT) { 910 | // TODO: handle ipPool deletion. RTM_DELROUTE message 911 | // can belong to previously valid ipPool. 912 | if s.ipam.match(update.Dst.String()) == nil { 913 | continue 914 | } 915 | isWithdrawal := false 916 | switch update.Type { 917 | case syscall.RTM_DELROUTE: 918 | isWithdrawal = true 919 | case syscall.RTM_NEWROUTE: 920 | default: 921 | log.Printf("unhandled rtm type: %d", update.Type) 922 | continue 923 | } 924 | path, err := s.makePath(update.Dst.String(), isWithdrawal) 925 | if err != nil { 926 | return err 927 | } 928 | log.Printf("made path from kernel update: %s", path) 929 | if _, err = s.bgpServer.AddPath("", []*bgptable.Path{path}); err != nil { 930 | return err 931 | } 932 | } else if update.Table == syscall.RT_TABLE_LOCAL { 933 | // This means the interface address is updated 934 | // Some routes we injected may be deleted by the kernel 935 | // Reload routes from BGP RIB and inject again 936 | ip, _, _ := net.ParseCIDR(update.Dst.String()) 937 | family := bgp.RF_IPv4_UC 938 | if ip.To4() == nil { 939 | family = bgp.RF_IPv6_UC 940 | } 941 | tbl, err := s.bgpServer.GetRib("", family, nil) 942 | if err != nil { 943 | return err 944 | } 945 | s.reloadCh <- tbl.Bests("") 946 | } 947 | } 948 | return fmt.Errorf("netlink route subscription ended") 949 | } 950 | 951 | func (s *Server) loadKernelRoute() error { 952 | <-s.prefixReady 953 | filter := &netlink.Route{ 954 | Table: syscall.RT_TABLE_MAIN, 955 | } 956 | list, err := netlink.RouteListFiltered(netlink.FAMILY_V4, filter, netlink.RT_FILTER_TABLE) 957 | if err != nil { 958 | return err 959 | } 960 | for _, route := range list { 961 | if route.Dst == nil { 962 | continue 963 | } 964 | if s.ipam.match(route.Dst.String()) == nil { 965 | continue 966 | } 967 | if route.Protocol == syscall.RTPROT_KERNEL || route.Protocol == syscall.RTPROT_BOOT { 968 | path, err := s.makePath(route.Dst.String(), false) 969 | if err != nil { 970 | return err 971 | } 972 | log.Printf("made path from kernel route: %s", path) 973 | if _, err = s.bgpServer.AddPath("", []*bgptable.Path{path}); err != nil { 974 | return err 975 | } 976 | } 977 | } 978 | return nil 979 | } 980 | 981 | // injectRoute is a helper function to inject BGP routes to linux kernel 982 | // TODO: multipath support 983 | func (s *Server) injectRoute(path *bgptable.Path) error { 984 | nexthop := path.GetNexthop() 985 | nlri := path.GetNlri() 986 | dst, _ := netlink.ParseIPNet(nlri.String()) 987 | route := &netlink.Route{ 988 | Dst: dst, 989 | Gw: nexthop, 990 | Protocol: RTPROT_GOBGP, 991 | } 992 | 993 | ipip := false 994 | if dst.IP.To4() != nil { 995 | if p := s.ipam.match(nlri.String()); p != nil { 996 | ipip = p.IPIP != "" 997 | 998 | node, err := s.client.Nodes().Get(calicoapi.NodeMetadata{Name: os.Getenv(NODENAME)}) 999 | if err != nil { 1000 | return err 1001 | } 1002 | 1003 | if p.Mode == "cross-subnet" && !isCrossSubnet(route.Gw, node.Spec.BGP.IPv4Address.Network().IPNet) { 1004 | ipip = false 1005 | } 1006 | if ipip { 1007 | i, err := net.InterfaceByName(p.IPIP) 1008 | if err != nil { 1009 | return err 1010 | } 1011 | route.LinkIndex = i.Index 1012 | route.SetFlag(netlink.FLAG_ONLINK) 1013 | } 1014 | } 1015 | // TODO: if !IsWithdraw, we'd ignore that 1016 | } 1017 | 1018 | if path.IsWithdraw { 1019 | log.Printf("removed route %s from kernel", nlri) 1020 | return netlink.RouteDel(route) 1021 | } 1022 | if !ipip { 1023 | gw, err := recursiveNexthopLookup(path.GetNexthop()) 1024 | if err != nil { 1025 | return err 1026 | } 1027 | route.Gw = gw 1028 | } 1029 | log.Printf("added route %s to kernel %s", nlri, route) 1030 | return netlink.RouteReplace(route) 1031 | } 1032 | 1033 | // watchBGPPath watches BGP routes from other peers and inject them into 1034 | // linux kernel 1035 | // TODO: multipath support 1036 | func (s *Server) watchBGPPath() error { 1037 | watcher := s.bgpServer.Watch(bgpserver.WatchBestPath(false)) 1038 | for { 1039 | var paths []*bgptable.Path 1040 | select { 1041 | case ev := <-watcher.Event(): 1042 | msg, ok := ev.(*bgpserver.WatchEventBestPath) 1043 | if !ok { 1044 | continue 1045 | } 1046 | paths = msg.PathList 1047 | case paths = <-s.reloadCh: 1048 | } 1049 | for _, path := range paths { 1050 | if path.IsLocal() { 1051 | continue 1052 | } 1053 | if err := s.injectRoute(path); err != nil { 1054 | return err 1055 | } 1056 | } 1057 | } 1058 | } 1059 | 1060 | // initialPolicySetting initialize BGP export policy. 1061 | // this creates two prefix-sets named 'aggregated' and 'host'. 1062 | // A route is allowed to be exported when it matches with 'aggregated' set, 1063 | // and not allowed when it matches with 'host' set. 1064 | func (s *Server) initialPolicySetting() error { 1065 | createEmptyPrefixSet := func(name string) error { 1066 | ps, err := bgptable.NewPrefixSet(bgpconfig.PrefixSet{PrefixSetName: name}) 1067 | if err != nil { 1068 | return err 1069 | } 1070 | return s.bgpServer.AddDefinedSet(ps) 1071 | } 1072 | for _, name := range []string{aggregatedPrefixSetName, hostPrefixSetName} { 1073 | if err := createEmptyPrefixSet(name); err != nil { 1074 | return err 1075 | } 1076 | } 1077 | // intended to work as same as 'calico_pools' export filter of BIRD configuration 1078 | definition := bgpconfig.PolicyDefinition{ 1079 | Name: "calico_aggr", 1080 | Statements: []bgpconfig.Statement{ 1081 | bgpconfig.Statement{ 1082 | Conditions: bgpconfig.Conditions{ 1083 | MatchPrefixSet: bgpconfig.MatchPrefixSet{ 1084 | PrefixSet: aggregatedPrefixSetName, 1085 | }, 1086 | }, 1087 | Actions: bgpconfig.Actions{ 1088 | RouteDisposition: bgpconfig.ROUTE_DISPOSITION_ACCEPT_ROUTE, 1089 | }, 1090 | }, 1091 | bgpconfig.Statement{ 1092 | Conditions: bgpconfig.Conditions{ 1093 | MatchPrefixSet: bgpconfig.MatchPrefixSet{ 1094 | PrefixSet: hostPrefixSetName, 1095 | }, 1096 | }, 1097 | Actions: bgpconfig.Actions{ 1098 | RouteDisposition: bgpconfig.ROUTE_DISPOSITION_REJECT_ROUTE, 1099 | }, 1100 | }, 1101 | }, 1102 | } 1103 | policy, err := bgptable.NewPolicy(definition) 1104 | if err != nil { 1105 | return err 1106 | } 1107 | if err = s.bgpServer.AddPolicy(policy, false); err != nil { 1108 | return err 1109 | } 1110 | return s.bgpServer.AddPolicyAssignment("", bgptable.POLICY_DIRECTION_EXPORT, 1111 | []*bgpconfig.PolicyDefinition{&definition}, 1112 | bgptable.ROUTE_TYPE_ACCEPT) 1113 | } 1114 | 1115 | func (s *Server) updatePrefixSet(paths []*bgptable.Path) error { 1116 | for _, path := range paths { 1117 | err := s._updatePrefixSet(path.GetNlri().String(), path.IsWithdraw) 1118 | if err != nil { 1119 | return err 1120 | } 1121 | } 1122 | return nil 1123 | } 1124 | 1125 | // _updatePrefixSet updates 'aggregated' and 'host' prefix-sets 1126 | // we add the exact prefix to 'aggregated' set, and add corresponding longer 1127 | // prefixes to 'host' set. 1128 | // 1129 | // e.g. prefix: "192.168.1.0/26" del: false 1130 | // add "192.168.1.0/26" to 'aggregated' set 1131 | // add "192.168.1.0/26..32" to 'host' set 1132 | // 1133 | func (s *Server) _updatePrefixSet(prefix string, del bool) error { 1134 | _, ipNet, err := net.ParseCIDR(prefix) 1135 | if err != nil { 1136 | return err 1137 | } 1138 | ps, err := bgptable.NewPrefixSet(bgpconfig.PrefixSet{ 1139 | PrefixSetName: aggregatedPrefixSetName, 1140 | PrefixList: []bgpconfig.Prefix{ 1141 | bgpconfig.Prefix{ 1142 | IpPrefix: prefix, 1143 | }, 1144 | }, 1145 | }) 1146 | if err != nil { 1147 | return err 1148 | } 1149 | if del { 1150 | err = s.bgpServer.DeleteDefinedSet(ps, false) 1151 | } else { 1152 | err = s.bgpServer.AddDefinedSet(ps) 1153 | } 1154 | if err != nil { 1155 | return err 1156 | } 1157 | min, _ := ipNet.Mask.Size() 1158 | max := 32 1159 | if ipNet.IP.To4() == nil { 1160 | max = 128 1161 | } 1162 | ps, err = bgptable.NewPrefixSet(bgpconfig.PrefixSet{ 1163 | PrefixSetName: hostPrefixSetName, 1164 | PrefixList: []bgpconfig.Prefix{ 1165 | bgpconfig.Prefix{ 1166 | IpPrefix: prefix, 1167 | MasklengthRange: fmt.Sprintf("%d..%d", min, max), 1168 | }, 1169 | }, 1170 | }) 1171 | if err != nil { 1172 | return err 1173 | } 1174 | if del { 1175 | return s.bgpServer.DeleteDefinedSet(ps, false) 1176 | } 1177 | return s.bgpServer.AddDefinedSet(ps) 1178 | } 1179 | 1180 | func main() { 1181 | 1182 | // Display the version on "-v", otherwise just delegate to the skel code. 1183 | // Use a new flag set so as not to conflict with existing libraries which use "flag" 1184 | flagSet := flag.NewFlagSet("Calico", flag.ExitOnError) 1185 | 1186 | version := flagSet.Bool("v", false, "Display version") 1187 | err := flagSet.Parse(os.Args[1:]) 1188 | if err != nil { 1189 | fmt.Println(err) 1190 | os.Exit(1) 1191 | } 1192 | if *version { 1193 | fmt.Println(VERSION) 1194 | os.Exit(0) 1195 | } 1196 | 1197 | rawloglevel := os.Getenv("CALICO_BGP_LOGSEVERITYSCREEN") 1198 | loglevel := log.InfoLevel 1199 | if rawloglevel != "" { 1200 | loglevel, err = log.ParseLevel(rawloglevel) 1201 | if err != nil { 1202 | log.WithError(err).Error("Failed to parse loglevel, defaulting to info.") 1203 | loglevel = log.InfoLevel 1204 | } 1205 | } 1206 | log.SetLevel(loglevel) 1207 | 1208 | server, err := NewServer() 1209 | if err != nil { 1210 | log.Printf("failed to create new server") 1211 | log.Fatal(err) 1212 | } 1213 | 1214 | server.Serve() 1215 | } 1216 | --------------------------------------------------------------------------------