├── .gitattributes ├── .github ├── dependabot.yml ├── release.yml └── workflows │ ├── build_pr.yml │ └── build_tag_and_main.yml ├── .gitignore ├── Dockerfile ├── LICENSE.txt ├── Makefile ├── README.md ├── configmap-reload.go ├── go.mod └── go.sum /.gitattributes: -------------------------------------------------------------------------------- 1 | Makefile linguist-documentation 2 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Copyright 2021 D2iQ, Inc. All rights reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | # To get started with Dependabot version updates, you'll need to specify which 5 | # package ecosystems to update and where the package manifests are located. 6 | # Please see the documentation for all configuration options: 7 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 8 | 9 | version: 2 10 | updates: 11 | - package-ecosystem: github-actions 12 | directory: / 13 | groups: 14 | github-actions: 15 | patterns: 16 | - "*" 17 | update-types: 18 | - minor 19 | - patch 20 | schedule: 21 | interval: weekly 22 | 23 | - package-ecosystem: gomod 24 | directory: / 25 | groups: 26 | gomod: 27 | patterns: 28 | - "*" 29 | update-types: 30 | - minor 31 | - patch 32 | schedule: 33 | interval: weekly 34 | 35 | - package-ecosystem: "docker" 36 | directories: 37 | - "/" 38 | schedule: 39 | interval: "daily" 40 | -------------------------------------------------------------------------------- /.github/release.yml: -------------------------------------------------------------------------------- 1 | changelog: 2 | categories: 3 | - title: Changes 4 | labels: 5 | - "*" 6 | exclude: 7 | labels: 8 | - dependencies 9 | - title: Dependencies 10 | labels: 11 | - dependencies 12 | -------------------------------------------------------------------------------- /.github/workflows/build_pr.yml: -------------------------------------------------------------------------------- 1 | name: build-pr 2 | on: 3 | pull_request: 4 | branches: 5 | - main 6 | 7 | permissions: read-all 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-24.04 12 | steps: 13 | - name: Checkout code 14 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 15 | 16 | - name: Set up QEMU 17 | uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3.6.0 18 | 19 | - name: Set up Docker Buildx 20 | uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0 21 | 22 | - name: Build image 23 | run: | 24 | docker buildx build \ 25 | --platform linux/arm64/v8,linux/amd64,linux/arm,linux/ppc64le,linux/s390x \ 26 | -t ghcr.io/jimmidyson/configmap-reload:${{ github.event.pull_request.head.sha }} \ 27 | . 28 | -------------------------------------------------------------------------------- /.github/workflows/build_tag_and_main.yml: -------------------------------------------------------------------------------- 1 | name: build-and-push-tag-and-main 2 | on: 3 | push: 4 | branches: 5 | - main 6 | tags: 7 | - v* 8 | 9 | permissions: read-all 10 | 11 | jobs: 12 | build-and-push: 13 | runs-on: ubuntu-24.04 14 | permissions: 15 | contents: write 16 | packages: write 17 | steps: 18 | - name: Checkout code 19 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 20 | 21 | - name: Set up QEMU 22 | uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3.6.0 23 | 24 | - name: Set up Docker Buildx 25 | uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0 26 | 27 | - name: Login to GitHub Container Registry 28 | uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0 29 | with: 30 | registry: ghcr.io 31 | username: ${{ github.actor }} 32 | password: ${{ github.token }} 33 | 34 | - name: Build and push image 35 | run: | 36 | docker buildx build \ 37 | --platform linux/arm64/v8,linux/amd64,linux/arm,linux/ppc64le,linux/s390x \ 38 | -t ghcr.io/jimmidyson/configmap-reload:${{ github.ref_name == 'main' && 'dev' || github.ref_name }} \ 39 | --push \ 40 | . 41 | 42 | - name: Create release 43 | uses: softprops/action-gh-release@da05d552573ad5aba039eaac05058a918a7bf631 # v2.2.2 44 | if: startsWith(github.ref, 'refs/tags/') 45 | with: 46 | token: ${{ github.token }} 47 | make_latest: true 48 | generate_release_notes: true 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | out/ 2 | _gopath/ 3 | vendor/ 4 | .vendor 5 | manifest-tool 6 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax=docker/dockerfile:1 2 | 3 | ARG BASEIMAGE=gcr.io/distroless/static-debian11:nonroot 4 | 5 | FROM --platform=${BUILDPLATFORM} golang:1.24.3@sha256:86b4cff66e04d41821a17cea30c1031ed53e2635e2be99ae0b4a7d69336b5063 AS builder 6 | 7 | COPY . /src 8 | WORKDIR /src 9 | ARG TARGETARCH 10 | RUN CGO_ENABLED=0 GOARCH=${TARGETARCH} go build --installsuffix cgo -ldflags="-s -w -extldflags '-static'" -a -o /configmap-reload configmap-reload.go 11 | 12 | FROM ${BASEIMAGE} 13 | 14 | LABEL org.opencontainers.image.source="https://github.com/jimmidyson/configmap-reload" 15 | 16 | USER 65534 17 | 18 | COPY --from=builder /configmap-reload /configmap-reload 19 | 20 | ENTRYPOINT ["/configmap-reload"] 21 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Red Hat, Inc. 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 implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | SHELL := /bin/bash -euo pipefail 16 | 17 | # Use the native vendor/ dependency system 18 | export GO111MODULE := on 19 | export CGO_ENABLED := 0 20 | 21 | GOOS ?= $(shell go env GOOS) 22 | GOARCH ?= $(shell go env GOARCH) 23 | ORG := github.com/jimmidyson 24 | REPOPATH ?= $(ORG)/configmap-reload 25 | DOCKER_IMAGE_NAME ?= ghcr.io/jimmidyson/configmap-reload 26 | DOCKER_IMAGE_TAG ?= latest 27 | 28 | LDFLAGS := -s -w -extldflags '-static' 29 | 30 | SRCFILES := $(shell find . ! -path './out/*' ! -path './.git/*' -type f) 31 | 32 | ALL_ARCH=amd64 arm arm64 ppc64le s390x 33 | ML_PLATFORMS=$(addprefix linux/,$(ALL_ARCH)) 34 | ALL_BINARIES ?= $(addprefix out/configmap-reload-, \ 35 | $(addprefix linux-,$(ALL_ARCH)) \ 36 | darwin-amd64 \ 37 | windows-amd64.exe) 38 | 39 | BINARY=configmap-reload-linux-$(GOARCH) 40 | 41 | out/configmap-reload: out/configmap-reload-$(GOOS)-$(GOARCH) 42 | cp out/configmap-reload-$(GOOS)-$(GOARCH) out/configmap-reload 43 | 44 | out/configmap-reload-%: $(SRCFILES) 45 | GOARCH=$(word 2,$(subst -, ,$(*:.exe=))) GOOS=$(word 1,$(subst -, ,$(*:.exe=))) \ 46 | go build --installsuffix cgo -ldflags="$(LDFLAGS)" -a \ 47 | -o $@ configmap-reload.go 48 | 49 | .PHONY: cross 50 | cross: $(ALL_BINARIES) 51 | 52 | .PHONY: checksum 53 | checksum: 54 | for f in $(ALL_BINARIES) ; do \ 55 | if [ -f "$${f}" ]; then \ 56 | openssl sha256 "$${f}" | awk '{print $$2}' > "$${f}.sha256" ; \ 57 | fi ; \ 58 | done 59 | 60 | .PHONY: clean 61 | clean: 62 | rm -rf out 63 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kubernetes ConfigMap Reload 2 | 3 | [![license](https://img.shields.io/github/license/jimmidyson/configmap-reload.svg?maxAge=2592000)](https://github.com/jimmidyson/configmap-reload) 4 | [![Docker Stars](https://img.shields.io/docker/stars/jimmidyson/configmap-reload.svg?maxAge=2592000)](https://hub.docker.com/r/jimmidyson/configmap-reload/) 5 | [![Docker Pulls](https://img.shields.io/docker/pulls/jimmidyson/configmap-reload.svg?maxAge=2592000)](https://hub.docker.com/r/jimmidyson/configmap-reload/) 6 | 7 | **configmap-reload** is a simple binary to trigger a reload when Kubernetes ConfigMaps or Secrets, mounted into pods, 8 | are updated. 9 | It watches mounted volume dirs and notifies the target process that the config map has been changed. 10 | It currently only supports sending an HTTP request, but in future it is expected to support sending OS 11 | (e.g. SIGHUP) once Kubernetes supports pod PID namespaces. 12 | 13 | Since version v0.10, the Docker image is available from ghcr.io at . 14 | Previous versons are available from Docker Hub at 15 | 16 | ### Usage 17 | 18 | ``` 19 | Usage of ./out/configmap-reload: 20 | -volume-dir value 21 | the config map volume directory to watch for updates; may be used multiple times 22 | -web.listen-address string 23 | address to listen on for web interface and telemetry. (default ":9533") 24 | -web.telemetry-path string 25 | path under which to expose metrics. (default "/metrics") 26 | -webhook-method string 27 | the HTTP method url to use to send the webhook (default "POST") 28 | -webhook-status-code int 29 | the HTTP status code indicating successful triggering of reload (default 200) 30 | -webhook-url string 31 | the url to send a request to when the specified config map volume directory has been updated 32 | -webhook-retries integer 33 | the amount of times to retry the webhook reload request 34 | ``` 35 | 36 | ### License 37 | 38 | This project is [Apache Licensed](LICENSE.txt) 39 | 40 | -------------------------------------------------------------------------------- /configmap-reload.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | "net/url" 9 | "os" 10 | "path/filepath" 11 | "strconv" 12 | "time" 13 | 14 | fsnotify "github.com/fsnotify/fsnotify" 15 | "github.com/prometheus/client_golang/prometheus" 16 | "github.com/prometheus/client_golang/prometheus/promhttp" 17 | ) 18 | 19 | const namespace = "configmap_reload" 20 | 21 | var ( 22 | volumeDirs volumeDirsFlag 23 | webhook webhookFlag 24 | webhookMethod = flag.String("webhook-method", "POST", "the HTTP method url to use to send the webhook") 25 | webhookStatusCode = flag.Int("webhook-status-code", 200, "the HTTP status code indicating successful triggering of reload") 26 | webhookRetries = flag.Int("webhook-retries", 1, "the amount of times to retry the webhook reload request") 27 | listenAddress = flag.String("web.listen-address", ":9533", "Address to listen on for web interface and telemetry.") 28 | metricPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.") 29 | 30 | lastReloadError = prometheus.NewGaugeVec(prometheus.GaugeOpts{ 31 | Namespace: namespace, 32 | Name: "last_reload_error", 33 | Help: "Whether the last reload resulted in an error (1 for error, 0 for success)", 34 | }, []string{"webhook"}) 35 | requestDuration = prometheus.NewGaugeVec(prometheus.GaugeOpts{ 36 | Namespace: namespace, 37 | Name: "last_request_duration_seconds", 38 | Help: "Duration of last webhook request", 39 | }, []string{"webhook"}) 40 | successReloads = prometheus.NewCounterVec(prometheus.CounterOpts{ 41 | Namespace: namespace, 42 | Name: "success_reloads_total", 43 | Help: "Total success reload calls", 44 | }, []string{"webhook"}) 45 | requestErrorsByReason = prometheus.NewCounterVec(prometheus.CounterOpts{ 46 | Namespace: namespace, 47 | Name: "request_errors_total", 48 | Help: "Total request errors by reason", 49 | }, []string{"webhook", "reason"}) 50 | watcherErrors = prometheus.NewCounter(prometheus.CounterOpts{ 51 | Namespace: namespace, 52 | Name: "watcher_errors_total", 53 | Help: "Total filesystem watcher errors", 54 | }) 55 | requestsByStatusCode = prometheus.NewCounterVec(prometheus.CounterOpts{ 56 | Namespace: namespace, 57 | Name: "requests_total", 58 | Help: "Total requests by response status code", 59 | }, []string{"webhook", "status_code"}) 60 | ) 61 | 62 | func init() { 63 | prometheus.MustRegister(lastReloadError) 64 | prometheus.MustRegister(requestDuration) 65 | prometheus.MustRegister(successReloads) 66 | prometheus.MustRegister(requestErrorsByReason) 67 | prometheus.MustRegister(watcherErrors) 68 | prometheus.MustRegister(requestsByStatusCode) 69 | } 70 | 71 | func main() { 72 | flag.Var(&volumeDirs, "volume-dir", "the config map volume directory to watch for updates; may be used multiple times") 73 | flag.Var(&webhook, "webhook-url", "the url to send a request to when the specified config map volume directory has been updated") 74 | flag.Parse() 75 | 76 | if len(volumeDirs) < 1 { 77 | log.Println("Missing volume-dir") 78 | log.Println() 79 | flag.Usage() 80 | os.Exit(1) 81 | } 82 | 83 | if len(webhook) < 1 { 84 | log.Println("Missing webhook-url") 85 | log.Println() 86 | flag.Usage() 87 | os.Exit(1) 88 | } 89 | 90 | watcher, err := fsnotify.NewWatcher() 91 | if err != nil { 92 | log.Fatal(err) 93 | } 94 | defer watcher.Close() 95 | 96 | go func() { 97 | for { 98 | select { 99 | case event := <-watcher.Events: 100 | if !isValidEvent(event) { 101 | continue 102 | } 103 | log.Println("config map updated") 104 | for _, h := range webhook { 105 | begun := time.Now() 106 | req, err := http.NewRequest(*webhookMethod, h.String(), nil) 107 | if err != nil { 108 | setFailureMetrics(h.String(), "client_request_create") 109 | log.Println("error:", err) 110 | continue 111 | } 112 | userInfo := h.User 113 | if userInfo != nil { 114 | if password, passwordSet := userInfo.Password(); passwordSet { 115 | req.SetBasicAuth(userInfo.Username(), password) 116 | } 117 | } 118 | 119 | successfulReloadWebhook := false 120 | 121 | for retries := *webhookRetries; retries != 0; retries-- { 122 | log.Printf("performing webhook request (%d/%d)", retries, *webhookRetries) 123 | resp, err := http.DefaultClient.Do(req) 124 | if err != nil { 125 | setFailureMetrics(h.String(), "client_request_do") 126 | log.Println("error:", err) 127 | time.Sleep(time.Second * 10) 128 | continue 129 | } 130 | resp.Body.Close() 131 | requestsByStatusCode.WithLabelValues(h.String(), strconv.Itoa(resp.StatusCode)).Inc() 132 | if resp.StatusCode != *webhookStatusCode { 133 | setFailureMetrics(h.String(), "client_response") 134 | log.Println("error:", "Received response code", resp.StatusCode, ", expected", *webhookStatusCode) 135 | time.Sleep(time.Second * 10) 136 | continue 137 | } 138 | 139 | setSuccessMetrics(h.String(), begun) 140 | log.Println("successfully triggered reload") 141 | successfulReloadWebhook = true 142 | break 143 | } 144 | 145 | if !successfulReloadWebhook { 146 | setFailureMetrics(h.String(), "retries_exhausted") 147 | log.Println("error:", "Webhook reload retries exhausted") 148 | } 149 | } 150 | case err := <-watcher.Errors: 151 | watcherErrors.Inc() 152 | log.Println("error:", err) 153 | } 154 | } 155 | }() 156 | 157 | for _, d := range volumeDirs { 158 | log.Printf("Watching directory: %q", d) 159 | err = watcher.Add(d) 160 | if err != nil { 161 | log.Fatal(err) 162 | } 163 | } 164 | 165 | log.Fatal(serverMetrics(*listenAddress, *metricPath)) 166 | } 167 | 168 | func setFailureMetrics(h, reason string) { 169 | requestErrorsByReason.WithLabelValues(h, reason).Inc() 170 | lastReloadError.WithLabelValues(h).Set(1.0) 171 | } 172 | 173 | func setSuccessMetrics(h string, begun time.Time) { 174 | requestDuration.WithLabelValues(h).Set(time.Since(begun).Seconds()) 175 | successReloads.WithLabelValues(h).Inc() 176 | lastReloadError.WithLabelValues(h).Set(0.0) 177 | } 178 | 179 | func isValidEvent(event fsnotify.Event) bool { 180 | if event.Op&fsnotify.Create != fsnotify.Create { 181 | return false 182 | } 183 | if filepath.Base(event.Name) != "..data" { 184 | return false 185 | } 186 | return true 187 | } 188 | 189 | func serverMetrics(listenAddress, metricsPath string) error { 190 | http.Handle(metricsPath, promhttp.Handler()) 191 | http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 192 | w.Write([]byte(` 193 | 194 | ConfigMap Reload Metrics 195 | 196 |

ConfigMap Reload

197 |

Metrics

198 | 199 | 200 | `)) 201 | }) 202 | return http.ListenAndServe(listenAddress, nil) 203 | } 204 | 205 | type volumeDirsFlag []string 206 | 207 | type webhookFlag []*url.URL 208 | 209 | func (v *volumeDirsFlag) Set(value string) error { 210 | *v = append(*v, value) 211 | return nil 212 | } 213 | 214 | func (v *volumeDirsFlag) String() string { 215 | return fmt.Sprint(*v) 216 | } 217 | 218 | func (v *webhookFlag) Set(value string) error { 219 | u, err := url.Parse(value) 220 | if err != nil { 221 | return fmt.Errorf("invalid URL: %v", err) 222 | } 223 | *v = append(*v, u) 224 | return nil 225 | } 226 | 227 | func (v *webhookFlag) String() string { 228 | return fmt.Sprint(*v) 229 | } 230 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jimmidyson/configmap-reload 2 | 3 | go 1.22 4 | 5 | toolchain go1.24.2 6 | 7 | require ( 8 | github.com/fsnotify/fsnotify v1.9.0 9 | github.com/prometheus/client_golang v1.22.0 10 | ) 11 | 12 | require ( 13 | github.com/beorn7/perks v1.0.1 // indirect 14 | github.com/cespare/xxhash/v2 v2.3.0 // indirect 15 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect 16 | github.com/prometheus/client_model v0.6.1 // indirect 17 | github.com/prometheus/common v0.62.0 // indirect 18 | github.com/prometheus/procfs v0.15.1 // indirect 19 | golang.org/x/sys v0.30.0 // indirect 20 | google.golang.org/protobuf v1.36.5 // indirect 21 | ) 22 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= 2 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= 3 | github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= 4 | github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= 5 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 6 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 7 | github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= 8 | github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= 9 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= 10 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 11 | github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= 12 | github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= 13 | github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= 14 | github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= 15 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= 16 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= 17 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 18 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 19 | github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= 20 | github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= 21 | github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= 22 | github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= 23 | github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= 24 | github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= 25 | github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= 26 | github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= 27 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 28 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 29 | golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= 30 | golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 31 | google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= 32 | google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= 33 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 34 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 35 | --------------------------------------------------------------------------------