-
Notifications
You must be signed in to change notification settings - Fork 464
/
kubelet_service.go
271 lines (227 loc) · 7.41 KB
/
kubelet_service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package k8s
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"text/template"
"github.com/cosi-project/runtime/pkg/controller"
"github.com/cosi-project/runtime/pkg/resource"
"github.com/cosi-project/runtime/pkg/state"
"github.com/siderolabs/go-pointer"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
kubeletconfig "k8s.io/kubelet/config/v1beta1"
runtimetalos "github.com/talos-systems/talos/internal/app/machined/pkg/runtime"
"github.com/talos-systems/talos/internal/app/machined/pkg/system"
"github.com/talos-systems/talos/internal/app/machined/pkg/system/services"
"github.com/talos-systems/talos/pkg/machinery/constants"
"github.com/talos-systems/talos/pkg/machinery/resources/files"
"github.com/talos-systems/talos/pkg/machinery/resources/k8s"
runtimeres "github.com/talos-systems/talos/pkg/machinery/resources/runtime"
"github.com/talos-systems/talos/pkg/machinery/resources/secrets"
)
// ServiceManager is the interface to the v1alpha1 services subsystems.
type ServiceManager interface {
IsRunning(id string) (system.Service, bool, error)
Load(services ...system.Service) []string
Stop(ctx context.Context, serviceIDs ...string) (err error)
Start(serviceIDs ...string) error
}
// KubeletServiceController renders kubelet configuration files and controls kubelet service lifecycle.
type KubeletServiceController struct {
V1Alpha1Services ServiceManager
V1Alpha1Mode runtimetalos.Mode
}
// Name implements controller.Controller interface.
func (ctrl *KubeletServiceController) Name() string {
return "k8s.KubeletServiceController"
}
// Inputs implements controller.Controller interface.
func (ctrl *KubeletServiceController) Inputs() []controller.Input {
return nil
}
// Outputs implements controller.Controller interface.
func (ctrl *KubeletServiceController) Outputs() []controller.Output {
return nil
}
// Run implements controller.Controller interface.
//
//nolint:gocyclo,cyclop
func (ctrl *KubeletServiceController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error {
// initially, wait for the machine-id to be generated and /var to be mounted
if err := r.UpdateInputs([]controller.Input{
{
Namespace: files.NamespaceName,
Type: files.EtcFileStatusType,
ID: pointer.To("machine-id"),
Kind: controller.InputWeak,
},
{
Namespace: runtimeres.NamespaceName,
Type: runtimeres.MountStatusType,
ID: pointer.To(constants.EphemeralPartitionLabel),
Kind: controller.InputWeak,
},
}); err != nil {
return err
}
for {
select {
case <-ctx.Done():
return nil
case <-r.EventCh():
}
_, err := r.Get(ctx, resource.NewMetadata(files.NamespaceName, files.EtcFileStatusType, "machine-id", resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
continue
}
return fmt.Errorf("error getting etc file status: %w", err)
}
_, err = r.Get(ctx, resource.NewMetadata(runtimeres.NamespaceName, runtimeres.MountStatusType, constants.EphemeralPartitionLabel, resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
// in container mode EPHEMERAL is always mounted
if ctrl.V1Alpha1Mode != runtimetalos.ModeContainer {
// wait for the EPHEMERAL to be mounted
continue
}
} else {
return fmt.Errorf("error getting ephemeral mount status: %w", err)
}
}
break
}
// normal reconcile loop
if err := r.UpdateInputs([]controller.Input{
{
Namespace: k8s.NamespaceName,
Type: k8s.KubeletSpecType,
ID: pointer.To(k8s.KubeletID),
Kind: controller.InputWeak,
},
{
Namespace: secrets.NamespaceName,
Type: secrets.KubeletType,
ID: pointer.To(secrets.KubeletID),
Kind: controller.InputWeak,
},
}); err != nil {
return err
}
r.QueueReconcile()
for {
select {
case <-ctx.Done():
return nil
case <-r.EventCh():
}
cfg, err := r.Get(ctx, resource.NewMetadata(k8s.NamespaceName, k8s.KubeletSpecType, k8s.KubeletID, resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
continue
}
return fmt.Errorf("error getting config: %w", err)
}
cfgSpec := cfg.(*k8s.KubeletSpec).TypedSpec()
secret, err := r.Get(ctx, resource.NewMetadata(secrets.NamespaceName, secrets.KubeletType, secrets.KubeletID, resource.VersionUndefined))
if err != nil {
if state.IsNotFoundError(err) {
continue
}
return fmt.Errorf("error getting secrets: %w", err)
}
secretSpec := secret.(*secrets.Kubelet).TypedSpec()
if err = ctrl.writePKI(secretSpec); err != nil {
return fmt.Errorf("error writing kubelet PKI: %w", err)
}
if err = ctrl.writeConfig(cfgSpec); err != nil {
return fmt.Errorf("error writing kubelet configuration: %w", err)
}
_, running, err := ctrl.V1Alpha1Services.IsRunning("kubelet")
if err != nil {
ctrl.V1Alpha1Services.Load(&services.Kubelet{})
}
if running {
if err = ctrl.V1Alpha1Services.Stop(ctx, "kubelet"); err != nil {
return fmt.Errorf("error stopping kubelet service: %w", err)
}
}
if err = ctrl.V1Alpha1Services.Start("kubelet"); err != nil {
return fmt.Errorf("error starting kubelet service: %w", err)
}
}
}
func (ctrl *KubeletServiceController) writePKI(secretSpec *secrets.KubeletSpec) error {
cfg := struct {
Server string
CACert string
BootstrapTokenID string
BootstrapTokenSecret string
}{
Server: secretSpec.Endpoint.String(),
CACert: base64.StdEncoding.EncodeToString(secretSpec.CA.Crt),
BootstrapTokenID: secretSpec.BootstrapTokenID,
BootstrapTokenSecret: secretSpec.BootstrapTokenSecret,
}
templ := template.Must(template.New("tmpl").Parse(string(kubeletKubeConfigTemplate)))
var buf bytes.Buffer
if err := templ.Execute(&buf, cfg); err != nil {
return err
}
if err := ioutil.WriteFile(constants.KubeletBootstrapKubeconfig, buf.Bytes(), 0o600); err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(constants.KubernetesCACert), 0o700); err != nil {
return err
}
if err := ioutil.WriteFile(constants.KubernetesCACert, secretSpec.CA.Crt, 0o400); err != nil {
return err
}
return nil
}
var kubeletKubeConfigTemplate = []byte(`apiVersion: v1
kind: Config
clusters:
- name: local
cluster:
server: {{ .Server }}
certificate-authority-data: {{ .CACert }}
users:
- name: kubelet
user:
token: {{ .BootstrapTokenID }}.{{ .BootstrapTokenSecret }}
contexts:
- context:
cluster: local
user: kubelet
`)
func (ctrl *KubeletServiceController) writeConfig(cfgSpec *k8s.KubeletSpecSpec) error {
var kubeletConfiguration kubeletconfig.KubeletConfiguration
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(cfgSpec.Config, &kubeletConfiguration); err != nil {
return fmt.Errorf("error converting kubelet configuration from unstructured: %w", err)
}
serializer := json.NewSerializerWithOptions(
json.DefaultMetaFactory,
nil,
nil,
json.SerializerOptions{
Yaml: true,
Pretty: true,
Strict: true,
},
)
var buf bytes.Buffer
if err := serializer.Encode(&kubeletConfiguration, &buf); err != nil {
return err
}
return ioutil.WriteFile("/etc/kubernetes/kubelet.yaml", buf.Bytes(), 0o600)
}