Skip to content

Commit e1272f0

Browse files
committedMay 25, 2020
initial commit
0 parents  commit e1272f0

11 files changed

+1243
-0
lines changed
 

‎Dockerfile

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
FROM golang:1.13 as builder
2+
3+
ARG KUBECONFIG
4+
ARG NODE_NAME
5+
6+
ENV GO111MODULE=on
7+
8+
WORKDIR /app
9+
10+
COPY go.mod .
11+
COPY go.sum .
12+
13+
RUN go mod download
14+
15+
COPY . .
16+
17+
RUN CGO_ENABLED=0 GOOS=linux go build
18+
19+
FROM scratch
20+
COPY --from=builder /app/k8s-node-label-monitor /app/
21+
22+
ENTRYPOINT [ "/app/k8s-node-label-monitor" ]

‎LICENSE

+202
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
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.

‎README.md

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# Kubernetes Node Label Monitor
2+
3+
This tool provides a custom Kubernetes controller for monitoring and notifying changes in the label states of Kubernetes
4+
nodes (labels added, deleted, or updated), and can be run either node-local or cluster-wide. Notifications can be
5+
dispatched to a number of different targets, and can be easily extended or customized through a simple notification
6+
interface.
7+
8+
## Installation
9+
10+
If planning to use the CLI App directly, e.g. for node-local testing, this can be compiled and installed as other Go
11+
projects:
12+
13+
```
14+
$ go get github.com/adaptant-labs/k8s-node-label-monitor
15+
```
16+
17+
For Docker containers and Kubernetes deployment instructions, see below.
18+
19+
## Usage
20+
21+
General usage is as follows:
22+
23+
```
24+
$ k8s-node-label-monitor --help
25+
Node Label Monitor for Kubernetes
26+
Usage: k8s-node-label-monitor [flags]
27+
28+
-kubeconfig string
29+
Paths to a kubeconfig. Only required if out-of-cluster.
30+
-l Only track changes to the local node
31+
-n string
32+
Notification endpoint to POST updates to
33+
```
34+
35+
### Running Node-Local via Docker
36+
37+
Multi-arch Docker images are available on Docker Hub at [adaptant/k8s-node-label-monitor]. These may be run as-is
38+
in-cluster, or out of cluster with an appropriate `KUBECONFIG` passed through.
39+
40+
### Running as a Kubernetes Deployment (Cluster-wide Monitoring)
41+
42+
An example Deployment configuration for cluster-wide monitoring and notification is provided in
43+
`k8s-node-label-monitor-cluster-deployment.yaml`, which can be, as the name implies, directly applied to the running
44+
cluster:
45+
46+
```
47+
$ kubectl apply -f https://raw.githubusercontent.com/adaptant-labs/k8s-node-label-monitor/k8s-node-label-monitor-cluster-deployment.yaml
48+
```
49+
50+
This will create a single Deployment constrained to running on the Kubernetes master. It will further create a special
51+
`node-label-monitor` service account, cluster role, and binding with the permission to list and watch nodes.
52+
53+
### Running as a Kubernetes DaemonSet (Node-Local Monitoring)
54+
55+
An example DaemonSet configuration for node-local monitoring and notification is provided in
56+
`k8s-node-label-monitor-cluster-deployment.yaml`, which can be applied directly:
57+
58+
```
59+
$ kubectl apply -f https://raw.githubusercontent.com/adaptant-labs/k8s-node-label-monitor/k8s-node-label-monitor-node-local-daemonset.yaml
60+
```
61+
62+
This will create a DaemonSet that will run on each node, with each node monitoring and notifying changes to its own
63+
label state directly. It will further create a special `node-label-monitor` service account, cluster role, and binding
64+
with the permission to list and watch nodes.
65+
66+
## Notification Plugins
67+
68+
Notification targets are provided through easily-extensible plugins. At present, the following notification mechanisms
69+
are supported:
70+
71+
| Notifier | Description |
72+
|----------|-------------|
73+
| Logger | Log-based notification, piggybacking on the default logger instance |
74+
| REST API Endpoint | POSTs the JSON-encoded payload to a defined REST API endpoint |
75+
76+
## Features and bugs
77+
78+
Please file feature requests and bugs in the [issue tracker][tracker].
79+
80+
## Acknowledgements
81+
82+
This project has received funding from the European Union’s Horizon 2020 research and innovation programme under grant
83+
agreement No 825480 ([SODALITE]).
84+
85+
## License
86+
87+
`k8s-node-label-monitor` is licensed under the terms of the Apache 2.0 license, the full version of which can be found
88+
in the LICENSE file included in the distribution.
89+
90+
[SODALITE]: https://www.sodalite.eu
91+
[tracker]: https://github.com/adaptant-labs/k8s-node-label-monitor/issues
92+
[adaptant/k8s-node-label-monitor]: https://hub.docker.com/repository/docker/adaptant/k8s-node-label-monitor

‎go.mod

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
module github.com/adaptant-labs/k8s-node-label-monitor
2+
3+
go 1.13
4+
5+
require (
6+
github.com/go-logr/logr v0.1.0
7+
k8s.io/api v0.18.3
8+
k8s.io/apimachinery v0.18.3
9+
k8s.io/client-go v0.18.2
10+
sigs.k8s.io/controller-runtime v0.6.0
11+
)

‎go.sum

+434
Large diffs are not rendered by default.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
kind: ServiceAccount
2+
apiVersion: v1
3+
metadata:
4+
name: node-label-monitor
5+
namespace: kube-system
6+
---
7+
kind: ClusterRole
8+
apiVersion: rbac.authorization.k8s.io/v1
9+
metadata:
10+
name: system:node-label-monitor
11+
rules:
12+
- apiGroups: [""]
13+
resources: ["nodes"]
14+
verbs: ["list", "watch"]
15+
---
16+
kind: ClusterRoleBinding
17+
apiVersion: rbac.authorization.k8s.io/v1
18+
metadata:
19+
name: system:node-label-monitor
20+
subjects:
21+
- kind: ServiceAccount
22+
name: node-label-monitor
23+
namespace: kube-system
24+
roleRef:
25+
kind: ClusterRole
26+
name: system:node-label-monitor
27+
apiGroup: rbac.authorization.k8s.io
28+
---
29+
apiVersion: apps/v1
30+
kind: Deployment
31+
metadata:
32+
labels:
33+
app: node-label-monitor
34+
name: node-label-monitor
35+
namespace: kube-system
36+
spec:
37+
replicas: 1
38+
selector:
39+
matchLabels:
40+
app: node-label-monitor
41+
template:
42+
metadata:
43+
labels:
44+
app: node-label-monitor
45+
spec:
46+
serviceAccount: node-label-monitor
47+
affinity:
48+
nodeAffinity:
49+
preferredDuringSchedulingIgnoredDuringExecution:
50+
- weight: 1
51+
preference:
52+
matchExpressions:
53+
- key: "node-role.kubernetes.io/master"
54+
operator: In
55+
values: [""]
56+
tolerations:
57+
- key: "node-role.kubernetes.io/master"
58+
operator: "Equal"
59+
value: ""
60+
effect: "NoSchedule"
61+
containers:
62+
- env:
63+
- name: NODE_NAME
64+
valueFrom:
65+
fieldRef:
66+
fieldPath: spec.nodeName
67+
image: adaptant/k8s-node-label-monitor:latest
68+
name: node-label-monitor
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
kind: ServiceAccount
2+
apiVersion: v1
3+
metadata:
4+
name: node-label-monitor
5+
namespace: kube-system
6+
---
7+
kind: ClusterRole
8+
apiVersion: rbac.authorization.k8s.io/v1
9+
metadata:
10+
name: system:node-label-monitor
11+
rules:
12+
- apiGroups: [""]
13+
resources: ["nodes"]
14+
verbs: ["list", "watch"]
15+
---
16+
kind: ClusterRoleBinding
17+
apiVersion: rbac.authorization.k8s.io/v1
18+
metadata:
19+
name: system:node-label-monitor
20+
subjects:
21+
- kind: ServiceAccount
22+
name: node-label-monitor
23+
namespace: kube-system
24+
roleRef:
25+
kind: ClusterRole
26+
name: system:node-label-monitor
27+
apiGroup: rbac.authorization.k8s.io
28+
---
29+
apiVersion: apps/v1
30+
kind: DaemonSet
31+
metadata:
32+
labels:
33+
app: node-label-monitor
34+
name: node-label-monitor
35+
namespace: kube-system
36+
spec:
37+
selector:
38+
matchLabels:
39+
app: node-label-monitor
40+
template:
41+
metadata:
42+
labels:
43+
app: node-label-monitor
44+
spec:
45+
serviceAccount: node-label-monitor
46+
containers:
47+
- env:
48+
- name: NODE_NAME
49+
valueFrom:
50+
fieldRef:
51+
fieldPath: spec.nodeName
52+
image: adaptant/k8s-node-label-monitor:latest
53+
name: node-label-monitor
54+
args:
55+
# Run in node-local mode
56+
- "-l"

‎main.go

+278
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
package main
2+
3+
import (
4+
"flag"
5+
"fmt"
6+
"github.com/adaptant-labs/k8s-node-label-monitor/notifiers"
7+
v1 "k8s.io/api/core/v1"
8+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
9+
"k8s.io/apimachinery/pkg/fields"
10+
"k8s.io/apimachinery/pkg/util/wait"
11+
"k8s.io/client-go/kubernetes"
12+
"k8s.io/client-go/tools/cache"
13+
"k8s.io/client-go/util/workqueue"
14+
"os"
15+
"sigs.k8s.io/controller-runtime/pkg/client/config"
16+
logf "sigs.k8s.io/controller-runtime/pkg/log"
17+
"sigs.k8s.io/controller-runtime/pkg/log/zap"
18+
"time"
19+
)
20+
21+
var (
22+
monitorName = "k8s-node-label-monitor"
23+
nodeLocal = false
24+
log = logf.Log.WithName(monitorName)
25+
nodeLabels = map[string]map[string]string{}
26+
)
27+
28+
type Controller struct {
29+
indexer cache.Indexer
30+
queue workqueue.RateLimitingInterface
31+
informer cache.Controller
32+
notifier notifiers.LabelNotifier
33+
}
34+
35+
// Compare two label maps and determine which key/value pairs have been added, deleted, or updated.
36+
func compareLabelMaps(oldMap map[string]string, newMap map[string]string) (added map[string]string, deleted []string, updated map[string]string) {
37+
added = map[string]string{}
38+
deleted = []string{}
39+
updated = map[string]string{}
40+
41+
// Compare the old map to the new
42+
for oldKey, oldValue := range oldMap {
43+
if val, ok := newMap[oldKey]; ok {
44+
// The same key exists, but the values differ - record it as updated
45+
if val != oldValue {
46+
updated[oldKey] = val
47+
}
48+
} else {
49+
// Key has been removed
50+
deleted = append(deleted, oldKey)
51+
}
52+
}
53+
54+
// Compare the new map to the old
55+
for newKey, newValue := range newMap {
56+
if _, ok := oldMap[newKey]; !ok {
57+
// If the key does not exist in the old map, record it as added
58+
added[newKey] = newValue
59+
}
60+
}
61+
62+
return added, deleted, updated
63+
}
64+
65+
func NewController(queue workqueue.RateLimitingInterface, indexer cache.Indexer, informer cache.Controller) *Controller {
66+
return &Controller{
67+
indexer: indexer,
68+
informer: informer,
69+
queue: queue,
70+
}
71+
}
72+
73+
// Calculate label changes across each node update
74+
func (c *Controller) labelUpdateHandler(key string) error {
75+
obj, exists, err := c.indexer.GetByKey(key)
76+
if err != nil {
77+
log.Error(err, "Failed to get key")
78+
return err
79+
}
80+
81+
if exists {
82+
node := obj.(*v1.Node)
83+
nodeName := node.GetName()
84+
85+
// Compare the cached label state to the incoming one
86+
added, deleted, updated := compareLabelMaps(nodeLabels[nodeName], node.Labels)
87+
88+
// Log any label updates
89+
if len(added) > 0 || len(deleted) > 0 || len(updated) > 0 {
90+
notification := notifiers.LabelUpdateNotification{
91+
Node: node.GetName(),
92+
Added: added,
93+
Updated: updated,
94+
Deleted: deleted,
95+
}
96+
97+
err := c.notifier.Notify(log, notification)
98+
if err != nil {
99+
log.Error(err, "Failed to dispatch notification")
100+
return err
101+
}
102+
}
103+
104+
// Remove any previously cached labels
105+
if nodeLabels[nodeName] != nil {
106+
for k := range nodeLabels[nodeName] {
107+
delete(nodeLabels[nodeName], k)
108+
}
109+
} else {
110+
// Ensure the label cache is allocated for this node
111+
nodeLabels[nodeName] = make(map[string]string)
112+
}
113+
114+
// Cache the updated label state
115+
for k, v := range node.Labels {
116+
nodeLabels[nodeName][k] = v
117+
}
118+
}
119+
120+
return nil
121+
}
122+
123+
func (c *Controller) processNextWorkItem() bool {
124+
key, quit := c.queue.Get()
125+
if quit {
126+
return false
127+
}
128+
129+
defer c.queue.Done(key)
130+
131+
err := c.labelUpdateHandler(key.(string))
132+
if err == nil {
133+
c.queue.Forget(key)
134+
return true
135+
}
136+
137+
// If we have failed, requeue the work for later
138+
c.queue.AddRateLimited(key)
139+
return true
140+
}
141+
142+
func (c *Controller) runWorker() {
143+
for c.processNextWorkItem() {
144+
}
145+
}
146+
147+
func (c *Controller) Run(threadiness int, stopCh chan struct{}) {
148+
// Let workers stop when we are done
149+
defer c.queue.ShutDown()
150+
151+
log.Info("Starting node controller")
152+
go c.informer.Run(stopCh)
153+
154+
if !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {
155+
log.Info("Timed out waiting for cache sync")
156+
return
157+
}
158+
159+
for i := 0; i < threadiness; i++ {
160+
go wait.Until(c.runWorker, time.Second, stopCh)
161+
}
162+
163+
<-stopCh
164+
log.Info("Stopping node controller")
165+
}
166+
167+
func getNodeName() (string, error) {
168+
// Within the Kubernetes Pod, the hostname provides the Pod name, rather than the node name, so we pass in the
169+
// node name via the NODE_NAME environment variable instead.
170+
nodeName := os.Getenv("NODE_NAME")
171+
if len(nodeName) > 0 {
172+
return nodeName, nil
173+
}
174+
175+
// If the NODE_NAME environment variable is unset, fall back on hostname matching (e.g. when running outside of
176+
// a Kubernetes deployment).
177+
return os.Hostname()
178+
}
179+
180+
func enqueueNodeUpdate(nodeName string, queue workqueue.RateLimitingInterface) {
181+
if nodeLocal {
182+
hostname, err := getNodeName()
183+
if err != nil {
184+
log.Error(err, "unable to determine local hostname for node-local monitoring")
185+
return
186+
}
187+
188+
if hostname != nodeName {
189+
return
190+
}
191+
}
192+
193+
queue.Add(nodeName)
194+
}
195+
196+
func main() {
197+
var endpoint string
198+
199+
flag.BoolVar(&nodeLocal, "l", false, "Only track changes to the local node")
200+
flag.StringVar(&endpoint, "n", "", "Notification endpoint to POST updates to")
201+
202+
flag.Usage = func() {
203+
fmt.Fprintf(os.Stderr, "Node Label Monitor for Kubernetes\n")
204+
fmt.Fprintf(os.Stderr, "Usage: %s [flags]\n\n", monitorName)
205+
flag.PrintDefaults()
206+
}
207+
208+
flag.Parse()
209+
210+
cfg := config.GetConfigOrDie()
211+
clientset := kubernetes.NewForConfigOrDie(cfg)
212+
213+
logf.SetLogger(zap.New(zap.UseDevMode(false)))
214+
215+
if nodeLocal {
216+
hostname, err := getNodeName()
217+
if err != nil {
218+
log.Error(err, "unable to determine local hostname for node-local monitoring")
219+
return
220+
}
221+
msg := fmt.Sprintf("configured for node-local monitoring on %s", hostname)
222+
log.Info(msg)
223+
} else {
224+
log.Info("configured for cluster-wide monitoring")
225+
}
226+
227+
// Create the node watcher
228+
nodeListWatcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), "nodes", metav1.NamespaceAll, fields.Everything())
229+
230+
// Create the workqueue
231+
queue := workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), monitorName)
232+
233+
// Monitor when nodes are added to, updated, or deleted from the Cluster
234+
indexer, informer := cache.NewIndexerInformer(nodeListWatcher, &v1.Node{}, 0, cache.ResourceEventHandlerFuncs{
235+
AddFunc: func(obj interface{}) {
236+
key, err := cache.MetaNamespaceKeyFunc(obj)
237+
if err == nil {
238+
// Add node
239+
enqueueNodeUpdate(key, queue)
240+
}
241+
},
242+
UpdateFunc: func(oldObj, newObj interface{}) {
243+
key, err := cache.MetaNamespaceKeyFunc(newObj)
244+
if err == nil {
245+
// Update node
246+
enqueueNodeUpdate(key, queue)
247+
}
248+
},
249+
DeleteFunc: func(obj interface{}) {
250+
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
251+
if err == nil {
252+
// Remove node
253+
delete(nodeLabels, key)
254+
enqueueNodeUpdate(key, queue)
255+
}
256+
},
257+
}, cache.Indexers{})
258+
259+
controller := NewController(queue, indexer, informer)
260+
261+
// Set up the notifier for this controller
262+
if len(endpoint) > 0 {
263+
var err error
264+
controller.notifier, err = notifiers.NewEndpointNotifier(log, endpoint)
265+
if err != nil {
266+
log.Error(err, "failed to instantiate endpoint notifier")
267+
return
268+
}
269+
} else {
270+
controller.notifier = notifiers.LogNotifier{}
271+
}
272+
273+
// Start the controller
274+
stop := make(chan struct{})
275+
defer close(stop)
276+
go controller.Run(1, stop)
277+
select {}
278+
}

‎notifiers/logger.go

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package notifiers
2+
3+
import (
4+
"encoding/json"
5+
"github.com/go-logr/logr"
6+
)
7+
8+
// Default log-based notifier
9+
type LogNotifier struct{}
10+
11+
func (l LogNotifier) Notify(log logr.Logger, notification LabelUpdateNotification) error {
12+
msg, err := json.Marshal(notification)
13+
if err != nil {
14+
log.Error(err, "failed to marshal JSON")
15+
return err
16+
}
17+
18+
log.Info(string(msg))
19+
return nil
20+
}

‎notifiers/notifier.go

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package notifiers
2+
3+
import "github.com/go-logr/logr"
4+
5+
type LabelUpdateNotification struct {
6+
Node string `json:"node"`
7+
Added map[string]string `json:"labelsAdded"`
8+
Deleted []string `json:"labelsDeleted"`
9+
Updated map[string]string `json:"labelsUpdated"`
10+
}
11+
12+
type LabelNotifier interface {
13+
Notify(log logr.Logger, notification LabelUpdateNotification) error
14+
}

‎notifiers/rest.go

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package notifiers
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"fmt"
7+
"github.com/go-logr/logr"
8+
"net/http"
9+
"net/url"
10+
)
11+
12+
// REST Endpoint Notifier
13+
type EndpointNotifier struct {
14+
endpoint string
15+
}
16+
17+
func NewEndpointNotifier(log logr.Logger, endpoint string) (*EndpointNotifier, error) {
18+
_, err := url.ParseRequestURI(endpoint)
19+
if err != nil {
20+
log.Error(err, "failed to validate endpoint URL")
21+
return nil, err
22+
}
23+
24+
return &EndpointNotifier{
25+
endpoint: endpoint,
26+
}, nil
27+
}
28+
29+
func (e EndpointNotifier) Notify(log logr.Logger, notification LabelUpdateNotification) error {
30+
payload, err := json.Marshal(notification)
31+
if err != nil {
32+
log.Error(err, "failed to marshal JSON payload")
33+
return err
34+
}
35+
36+
msg := fmt.Sprintf("notifying %s", e.endpoint)
37+
log.Info(msg)
38+
39+
_, err = http.Post(e.endpoint, "application/json", bytes.NewBuffer(payload))
40+
if err != nil {
41+
log.Error(err, "failed to POST to endpoint")
42+
return err
43+
}
44+
45+
return nil
46+
}

0 commit comments

Comments
 (0)
Please sign in to comment.