/
static_pod_server.go
210 lines (160 loc) · 5.44 KB
/
static_pod_server.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
// 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 (
"context"
"fmt"
"net"
"net/http"
"sync"
"github.com/cosi-project/runtime/pkg/controller"
"github.com/cosi-project/runtime/pkg/safe"
"go.uber.org/zap"
"gopkg.in/yaml.v3"
"github.com/siderolabs/talos/pkg/machinery/resources/k8s"
)
// StaticPodServerController renders all static pod definitions as a PodList and serves it as YAML via HTTP.
type StaticPodServerController struct {
podList []byte
podListMu sync.Mutex
staticPodVersions map[string]string
}
// Name implements controller.Controller interface.
func (ctrl *StaticPodServerController) Name() string {
return "k8s.StaticPodServerController"
}
// Inputs implements controller.Controller interface.
func (ctrl *StaticPodServerController) Inputs() []controller.Input {
return []controller.Input{
{
Namespace: k8s.NamespaceName,
Type: k8s.StaticPodType,
Kind: controller.InputWeak,
},
}
}
// Outputs implements controller.Controller interface.
func (ctrl *StaticPodServerController) Outputs() []controller.Output {
return []controller.Output{
{
Type: k8s.StaticPodServerStatusType,
Kind: controller.OutputExclusive,
},
}
}
type pod map[string]any
type podList struct {
Kind string `json:"kind,omitempty" protobuf:"bytes,1,opt,name=kind"`
Items []pod `json:"items" protobuf:"bytes,2,rep,name=items"`
APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,3,opt,name=apiVersion"`
}
// Run implements controller.Controller interface.
func (ctrl *StaticPodServerController) Run(ctx context.Context, r controller.Runtime, logger *zap.Logger) error {
ctrl.staticPodVersions = map[string]string{}
shutdownServer, serverError, err := ctrl.createServer(ctx, r, logger)
if err != nil {
return fmt.Errorf("failed to start http server to serve static pod list: %w", err)
}
defer shutdownServer()
for {
select {
case <-ctx.Done():
return nil
case err := <-serverError:
return fmt.Errorf("http server closed unexpectedly: %w", err)
case <-r.EventCh():
staticPodList, err := ctrl.buildPodList(ctx, r, logger)
if err != nil {
logger.Error("error building static pod list", zap.Error(err))
}
ctrl.podListMu.Lock()
ctrl.podList = staticPodList
ctrl.podListMu.Unlock()
}
r.ResetRestartBackoff()
}
}
func (ctrl *StaticPodServerController) buildPodList(ctx context.Context, r controller.Runtime, logger *zap.Logger) ([]byte, error) {
staticPods, err := safe.ReaderListAll[*k8s.StaticPod](ctx, r)
if err != nil {
return nil, fmt.Errorf("error listing static pods: %w", err)
}
pl := podList{
Kind: "PodList",
APIVersion: "v1",
}
touchedPodIDs := map[string]struct{}{}
for iter := staticPods.Iterator(); iter.Next(); {
id := iter.Value().Metadata().ID()
version := iter.Value().Metadata().Version().String()
if oldVersion, exists := ctrl.staticPodVersions[id]; !exists || oldVersion != version {
ctrl.staticPodVersions[id] = version
if !exists {
logger.Info("rendered new static pod", zap.String("id", id))
} else {
logger.Info("rendered updated static pod", zap.String("id", id), zap.String("old_version", oldVersion), zap.String("new_version", version))
}
}
staticPodSpec := iter.Value().TypedSpec()
pl.Items = append(pl.Items, staticPodSpec.Pod)
touchedPodIDs[id] = struct{}{}
}
for id := range ctrl.staticPodVersions {
if _, exists := touchedPodIDs[id]; exists {
continue
}
logger.Info("removed static pod", zap.String("id", id))
delete(ctrl.staticPodVersions, id)
}
manifestContent, err := yaml.Marshal(pl)
if err != nil {
return nil, fmt.Errorf("error rendering list of static pods as yaml: %w", err)
}
return manifestContent, nil
}
func (ctrl *StaticPodServerController) createServer(ctx context.Context, r controller.Runtime, logger *zap.Logger) (func(), <-chan error, error) {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
ctrl.podListMu.Lock()
staticPodList := ctrl.podList
ctrl.podListMu.Unlock()
logger.Debug("serving static pod manifests", zap.Int("size", len(staticPodList)))
if staticPodList == nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
_, err := w.Write(staticPodList)
if err != nil {
logger.Error("failed to serve static pod manifests", zap.Error(err))
}
})
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, nil, fmt.Errorf("failed to create listener for serving static pod manifests: %w", err)
}
httpServer := &http.Server{
Handler: mux,
}
shutdownServer := func() {
if err := httpServer.Shutdown(ctx); err != nil {
logger.Error("failed to shut down HTTP server, serving static pod manifests", zap.Error(err))
}
}
go func() {
<-ctx.Done()
shutdownServer()
}()
if err := safe.WriterModify(ctx, r, k8s.NewStaticPodServerStatus(k8s.NamespaceName, k8s.StaticPodServerStatusResourceID), func(r *k8s.StaticPodServerStatus) error {
url := fmt.Sprintf("http://%s", listener.Addr().String())
r.TypedSpec().URL = url
return nil
}); err != nil {
return nil, nil, fmt.Errorf("error modifying StaticPodListURL resource: %w", err)
}
serverError := make(chan error, 1)
go func() {
serverError <- httpServer.Serve(listener)
}()
return shutdownServer, serverError, nil
}