main.go 7.68 KB
Newer Older
Adam Harrison's avatar
Adam Harrison committed
1
2
3
4
package main

import (
	"math/rand"
5
	"net/http"
Adam Harrison's avatar
Adam Harrison committed
6
7
8
9
10
11
12
13
14
15
16
	"os"
	"os/exec"
	"regexp"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/spf13/cobra"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/pkg/api/v1"
	"k8s.io/client-go/rest"

17
18
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
Adam Harrison's avatar
Adam Harrison committed
19
20
21
	"github.com/weaveworks/kured/pkg/alerts"
	"github.com/weaveworks/kured/pkg/daemonsetlock"
	"github.com/weaveworks/kured/pkg/delaytick"
22
	"github.com/weaveworks/kured/pkg/notifications/slack"
Adam Harrison's avatar
Adam Harrison committed
23
24
25
)

var (
26
27
28
	version = "unreleased"

	// Command line flags
29
	period         time.Duration
Adam Harrison's avatar
Adam Harrison committed
30
31
32
33
34
35
	dsNamespace    string
	dsName         string
	lockAnnotation string
	prometheusURL  string
	alertFilter    *regexp.Regexp
	rebootSentinel string
36
37
	slackHookURL   string
	slackUsername  string
38
39
40
41
42
43
44

	// Metrics
	rebootRequiredGauge = prometheus.NewGaugeVec(prometheus.GaugeOpts{
		Subsystem: "kured",
		Name:      "reboot_required",
		Help:      "OS requires reboot due to software updates.",
	}, []string{"node"})
Adam Harrison's avatar
Adam Harrison committed
45
46
)

47
48
49
50
func init() {
	prometheus.MustRegister(rebootRequiredGauge)
}

Adam Harrison's avatar
Adam Harrison committed
51
52
53
54
55
56
func main() {
	rootCmd := &cobra.Command{
		Use:   "kured",
		Short: "Kubernetes Reboot Daemon",
		Run:   root}

57
58
	rootCmd.PersistentFlags().DurationVar(&period, "period", time.Minute*60,
		"reboot check period")
Adam Harrison's avatar
Adam Harrison committed
59
60
61
62
63
64
65
66
67
68
69
70
71
	rootCmd.PersistentFlags().StringVar(&dsNamespace, "ds-name", "kube-system",
		"namespace containing daemonset on which to place lock")
	rootCmd.PersistentFlags().StringVar(&dsName, "ds-namespace", "kured",
		"name of daemonset on which to place lock")
	rootCmd.PersistentFlags().StringVar(&lockAnnotation, "lock-annotation", "weave.works/kured-node-lock",
		"annotation in which to record locking node")
	rootCmd.PersistentFlags().StringVar(&prometheusURL, "prometheus-url", "",
		"Prometheus instance to probe for active alerts")
	rootCmd.PersistentFlags().Var(&regexpValue{&alertFilter}, "alert-filter-regexp",
		"alert names to ignore when checking for active alerts")
	rootCmd.PersistentFlags().StringVar(&rebootSentinel, "reboot-sentinel", "/var/run/reboot-required",
		"path to file whose existence signals need to reboot")

72
73
74
75
76
	rootCmd.PersistentFlags().StringVar(&slackHookURL, "slack-hook-url", "",
		"slack hook URL for reboot notfications")
	rootCmd.PersistentFlags().StringVar(&slackUsername, "slack-username", "kured",
		"slack username for reboot notfications")

Adam Harrison's avatar
Adam Harrison committed
77
78
79
80
81
	if err := rootCmd.Execute(); err != nil {
		log.Fatal(err)
	}
}

82
func sentinelExists() bool {
Adam Harrison's avatar
Adam Harrison committed
83
84
85
86
87
88
89
	_, err := os.Stat(rebootSentinel)
	switch {
	case err == nil:
		return true
	case os.IsNotExist(err):
		return false
	default:
90
		log.Fatalf("Unable to determine existence of sentinel: %v", err)
Adam Harrison's avatar
Adam Harrison committed
91
92
93
94
		return false // unreachable; prevents compilation error
	}
}

95
96
97
98
99
100
101
102
103
104
func rebootRequired() bool {
	if sentinelExists() {
		log.Infof("Reboot required")
		return true
	} else {
		log.Infof("Reboot not required")
		return false
	}
}

Adam Harrison's avatar
Adam Harrison committed
105
106
func rebootBlocked() bool {
	if prometheusURL != "" {
107
		alertNames, err := alerts.PrometheusActiveAlerts(prometheusURL, alertFilter)
Adam Harrison's avatar
Adam Harrison committed
108
109
110
111
		if err != nil {
			log.Warnf("Reboot blocked: prometheus query error: %v", err)
			return true
		}
112
113
114
115
		count := len(alertNames)
		if count > 10 {
			alertNames = append(alertNames[:10], "...")
		}
Adam Harrison's avatar
Adam Harrison committed
116
		if count > 0 {
117
			log.Warnf("Reboot blocked: %d active alerts: %v", count, alertNames)
Adam Harrison's avatar
Adam Harrison committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
			return true
		}
	}
	return false
}

func holding(lock *daemonsetlock.DaemonSetLock, metadata interface{}) bool {
	holding, err := lock.Test(metadata)
	if err != nil {
		log.Fatalf("Error testing lock: %v", err)
	}
	if holding {
		log.Infof("Holding lock")
	}
	return holding
}

func acquire(lock *daemonsetlock.DaemonSetLock, metadata interface{}) bool {
	holding, holder, err := lock.Acquire(metadata)
	switch {
	case err != nil:
		log.Fatalf("Error acquiring lock: %v", err)
		return false
	case !holding:
		log.Warnf("Lock already held: %v", holder)
		return false
	default:
		log.Infof("Acquired reboot lock")
		return true
	}
}

func release(lock *daemonsetlock.DaemonSetLock) {
	log.Infof("Releasing lock")
	if err := lock.Release(); err != nil {
		log.Fatalf("Error releasing lock: %v", err)
	}
}

func drain(nodeID string) {
	log.Infof("Draining node %s", nodeID)
	drainCmd := exec.Command("/usr/bin/kubectl", "drain",
		"--ignore-daemonsets", "--delete-local-data", "--force", nodeID)
	if err := drainCmd.Run(); err != nil {
		log.Fatalf("Error invoking drain command: %v", err)
	}
}

func uncordon(nodeID string) {
	log.Infof("Uncordoning node %s", nodeID)
	uncordonCmd := exec.Command("/usr/bin/kubectl", "uncordon", nodeID)
	if err := uncordonCmd.Run(); err != nil {
		log.Fatalf("Error invoking uncordon command: %v", err)
	}
}

func waitForDrain(client *kubernetes.Clientset, nodeID string) {
	for {
		var unterminated int

		namespaces, err := client.CoreV1().Namespaces().List(v1.ListOptions{})
		if err != nil {
			log.Fatalf("Error waiting for drain: %v", err)
		}

		for _, namespace := range namespaces.Items {
			drainCandidates := v1.ListOptions{LabelSelector: "ignore_on_drain!=true"}
			pods, err := client.CoreV1().Pods(namespace.ObjectMeta.Name).List(drainCandidates)
			if err != nil {
				log.Fatalf("Error waiting for drain: %v", err)
			}

			for _, pod := range pods.Items {
				if pod.Spec.NodeName == nodeID &&
					pod.Status.Phase != "Succeeded" &&
					pod.Status.Phase != "Failed" {
					unterminated++
				}
			}
		}

		if unterminated == 0 {
			return
		}

		log.Infof("Waiting for %d pods to terminate", unterminated)
		time.Sleep(time.Minute)
	}
}

208
func commandReboot(nodeID string) {
Adam Harrison's avatar
Adam Harrison committed
209
	log.Infof("Commanding reboot")
210
211
212
213
214
215
216

	if slackHookURL != "" {
		if err := slack.NotifyReboot(slackHookURL, slackUsername, nodeID); err != nil {
			log.Warnf("Error notifying slack: %v", err)
		}
	}

Adam Harrison's avatar
Adam Harrison committed
217
218
219
220
221
222
223
	// Relies on /var/run/dbus/system_bus_socket bind mount to talk to systemd
	rebootCmd := exec.Command("/bin/systemctl", "reboot")
	if err := rebootCmd.Run(); err != nil {
		log.Fatalf("Error invoking reboot command: %v", err)
	}
}

224
func maintainRebootRequiredMetric(nodeID string) {
Adam Harrison's avatar
Adam Harrison committed
225
	for {
226
227
228
229
230
		if sentinelExists() {
			rebootRequiredGauge.WithLabelValues(nodeID).Set(1)
		} else {
			rebootRequiredGauge.WithLabelValues(nodeID).Set(0)
		}
Adam Harrison's avatar
Adam Harrison committed
231
232
233
234
235
236
237
238
239
		time.Sleep(time.Minute)
	}
}

// nodeMeta is used to remember information across reboots
type nodeMeta struct {
	Unschedulable bool `json:"unschedulable"`
}

240
func rebootAsRequired(nodeID string) {
Adam Harrison's avatar
Adam Harrison committed
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
	config, err := rest.InClusterConfig()
	if err != nil {
		log.Fatal(err)
	}

	client, err := kubernetes.NewForConfig(config)
	if err != nil {
		log.Fatal(err)
	}

	lock := daemonsetlock.New(client, nodeID, dsNamespace, dsName, lockAnnotation)

	nodeMeta := nodeMeta{}
	if holding(lock, &nodeMeta) {
		if !nodeMeta.Unschedulable {
			uncordon(nodeID)
		}
		release(lock)
	}

	source := rand.NewSource(time.Now().UnixNano())
262
	tick := delaytick.New(source, period)
Adam Harrison's avatar
Adam Harrison committed
263
	for _ = range tick {
264
265
266
267
268
269
270
271
272
273
274
275
		if rebootRequired() && !rebootBlocked() {
			node, err := client.CoreV1().Nodes().Get(nodeID)
			if err != nil {
				log.Fatal(err)
			}
			nodeMeta.Unschedulable = node.Spec.Unschedulable

			if acquire(lock, &nodeMeta) {
				if !nodeMeta.Unschedulable {
					drain(nodeID)
					waitForDrain(client, nodeID)
				}
276
277
278
279
280
				commandReboot(nodeID)
				for {
					log.Infof("Waiting for reboot")
					time.Sleep(time.Minute)
				}
Adam Harrison's avatar
Adam Harrison committed
281
282
283
			}
		}
	}
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
}

func root(cmd *cobra.Command, args []string) {
	log.Infof("Kubernetes Reboot Daemon: %s", version)

	nodeID := os.Getenv("KURED_NODE_ID")
	if nodeID == "" {
		log.Fatal("KURED_NODE_ID environment variable required")
	}

	log.Infof("Node ID: %s", nodeID)
	log.Infof("Lock Annotation: %s/%s:%s", dsNamespace, dsName, lockAnnotation)
	log.Infof("Reboot Sentinel: %s every %v", rebootSentinel, period)

	go rebootAsRequired(nodeID)
	go maintainRebootRequiredMetric(nodeID)
Adam Harrison's avatar
Adam Harrison committed
300

301
302
	http.Handle("/metrics", promhttp.Handler())
	log.Fatal(http.ListenAndServe(":8080", nil))
Adam Harrison's avatar
Adam Harrison committed
303
}