-
Notifications
You must be signed in to change notification settings - Fork 14
/
dumpstate.go
256 lines (216 loc) · 7.53 KB
/
dumpstate.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
package plugin
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"time"
"go.uber.org/zap"
"golang.org/x/exp/slices"
vmapi "github.com/neondatabase/autoscaling/neonvm/apis/neonvm/v1"
"github.com/neondatabase/autoscaling/pkg/api"
"github.com/neondatabase/autoscaling/pkg/util"
)
type dumpStateConfig struct {
Port uint16 `json:"port"`
TimeoutSeconds uint `json:"timeoutSeconds"`
}
func (c *dumpStateConfig) validate() (string, error) {
if c.Port == 0 {
return "port", errors.New("value must be > 0")
} else if c.TimeoutSeconds == 0 {
return "timeoutSeconds", errors.New("value must be > 0")
}
return "", nil
}
type stateDump struct {
Stopped bool `json:"stopped"`
BuildInfo util.BuildInfo `json:"buildInfo"`
State pluginStateDump `json:"state"`
}
func (p *AutoscaleEnforcer) startDumpStateServer(shutdownCtx context.Context, logger *zap.Logger) error {
// Manually start the TCP listener so we can minimize errors in the background thread.
addr := net.TCPAddr{IP: net.IPv4zero, Port: int(p.state.conf.DumpState.Port)}
listener, err := net.ListenTCP("tcp", &addr)
if err != nil {
return fmt.Errorf("Error binding to %v", addr)
}
go func() {
mux := http.NewServeMux()
util.AddHandler(logger, mux, "/", http.MethodGet, "<empty>", func(ctx context.Context, _ *zap.Logger, body *struct{}) (*stateDump, int, error) {
timeout := time.Duration(p.state.conf.DumpState.TimeoutSeconds) * time.Second
startTime := time.Now()
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
state, err := p.dumpState(ctx, shutdownCtx.Err() != nil)
if err != nil {
if ctx.Err() != nil && errors.Is(ctx.Err(), context.DeadlineExceeded) {
totalDuration := time.Since(startTime)
return nil, 500, fmt.Errorf("timed out after %s while getting state", totalDuration)
} else {
// some other type of cancel; 400 is a little weird, but there isn't a great
// option here.
return nil, 400, fmt.Errorf("error while getting state: %w", err)
}
}
return state, 200, nil
})
// note: we don't shut down this server. It should be possible to continue fetching the
// internal state after shutdown has started.
server := &http.Server{Handler: mux}
if err := server.Serve(listener); err != nil {
logger.Error("dump-state server exited", zap.Error(err))
}
}()
return nil
}
func (p *AutoscaleEnforcer) dumpState(ctx context.Context, stopped bool) (*stateDump, error) {
state, err := p.state.dump(ctx)
if err != nil {
return nil, err
}
return &stateDump{
Stopped: stopped,
BuildInfo: util.GetBuildInfo(),
State: *state,
}, nil
}
type keyed[K any, V any] struct {
Key K `json:"key"`
Value V `json:"value"`
}
type pluginStateDump struct {
OngoingMigrationDeletions []keyed[util.NamespacedName, int] `json:"ongoingMigrationDeletions"`
Nodes []keyed[string, nodeStateDump] `json:"nodes"`
Pods []podNameAndPointer `json:"pods"`
MaxTotalReservableCPU vmapi.MilliCPU `json:"maxTotalReservableCPU"`
MaxTotalReservableMem api.Bytes `json:"maxTotalReservableMem"`
Conf Config `json:"config"`
}
type podNameAndPointer struct {
Obj pointerString `json:"obj"`
PodName util.NamespacedName `json:"podName"`
}
type pointerString string
type nodeStateDump struct {
Obj pointerString `json:"obj"`
Name string `json:"name"`
NodeGroup string `json:"nodeGroup"`
AvailabilityZone string `json:"availabilityZone"`
CPU nodeResourceState[vmapi.MilliCPU] `json:"cpu"`
Mem nodeResourceState[api.Bytes] `json:"mem"`
Pods []keyed[util.NamespacedName, podStateDump] `json:"pods"`
Mq []*podNameAndPointer `json:"mq"`
}
type podStateDump struct {
Obj pointerString `json:"obj"`
Name util.NamespacedName `json:"name"`
Node pointerString `json:"node"`
CPU podResourceState[vmapi.MilliCPU] `json:"cpu"`
Mem podResourceState[api.Bytes] `json:"mem"`
VM *vmPodState `json:"vm"`
}
func makePointerString[T any](t *T) pointerString {
return pointerString(fmt.Sprintf("%p", t))
}
func sortSliceByPodName[T any](slice []T, name func(T) util.NamespacedName) {
slices.SortFunc(slice, func(a, b T) (less bool) {
aName := name(a)
bName := name(b)
return aName.Namespace < bName.Namespace && aName.Name < bName.Name
})
}
func (s *pluginState) dump(ctx context.Context) (*pluginStateDump, error) {
if err := s.lock.TryLock(ctx); err != nil {
return nil, err
}
defer s.lock.Unlock()
pods := make([]podNameAndPointer, 0, len(s.pods))
for _, p := range s.pods {
pods = append(pods, podNameAndPointer{Obj: makePointerString(p), PodName: p.name})
}
sortSliceByPodName(pods, func(p podNameAndPointer) util.NamespacedName { return p.PodName })
nodes := make([]keyed[string, nodeStateDump], 0, len(s.nodes))
for k, n := range s.nodes {
nodes = append(nodes, keyed[string, nodeStateDump]{Key: k, Value: n.dump()})
}
slices.SortFunc(nodes, func(kvx, kvy keyed[string, nodeStateDump]) (less bool) {
return kvx.Key < kvy.Key
})
ongoingMigrationDeletions := make([]keyed[util.NamespacedName, int], 0, len(s.ongoingMigrationDeletions))
for k, count := range s.ongoingMigrationDeletions {
ongoingMigrationDeletions = append(ongoingMigrationDeletions, keyed[util.NamespacedName, int]{Key: k, Value: count})
}
sortSliceByPodName(ongoingMigrationDeletions, func(kv keyed[util.NamespacedName, int]) util.NamespacedName { return kv.Key })
return &pluginStateDump{
OngoingMigrationDeletions: ongoingMigrationDeletions,
Nodes: nodes,
Pods: pods,
MaxTotalReservableCPU: s.maxTotalReservableCPU,
MaxTotalReservableMem: s.maxTotalReservableMem,
Conf: *s.conf,
}, nil
}
func (s *nodeState) dump() nodeStateDump {
pods := make([]keyed[util.NamespacedName, podStateDump], 0, len(s.pods))
for k, p := range s.pods {
pods = append(pods, keyed[util.NamespacedName, podStateDump]{Key: k, Value: p.dump()})
}
sortSliceByPodName(pods, func(kv keyed[util.NamespacedName, podStateDump]) util.NamespacedName { return kv.Key })
mq := make([]*podNameAndPointer, 0, len(s.mq))
for _, p := range s.mq {
if p == nil {
mq = append(mq, nil)
} else {
v := podNameAndPointer{Obj: makePointerString(p), PodName: p.Name}
mq = append(mq, &v)
}
}
return nodeStateDump{
Obj: makePointerString(s),
Name: s.name,
NodeGroup: s.nodeGroup,
AvailabilityZone: s.availabilityZone,
CPU: s.cpu,
Mem: s.mem,
Pods: pods,
Mq: mq,
}
}
func (s *podState) dump() podStateDump {
var vm *vmPodState
if s.vm != nil {
vm = &[]vmPodState{s.vm.dump()}[0]
}
return podStateDump{
Obj: makePointerString(s),
Name: s.name,
Node: makePointerString(s.node),
CPU: s.cpu,
Mem: s.mem,
VM: vm,
}
}
func (s *vmPodState) dump() vmPodState {
// Copy some of the "may be nil" pointer fields
var metrics *api.Metrics
if s.Metrics != nil {
m := *s.Metrics
metrics = &m
}
var migrationState *podMigrationState
if s.MigrationState != nil {
migrationState = &podMigrationState{
Name: s.MigrationState.Name,
}
}
return vmPodState{
Name: s.Name,
MemSlotSize: s.MemSlotSize,
Config: s.Config,
Metrics: metrics,
MqIndex: s.MqIndex,
MigrationState: migrationState,
}
}