This repository has been archived by the owner on Apr 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
takeoff.go
228 lines (192 loc) · 5.83 KB
/
takeoff.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
package orbiter
import (
"errors"
"net/http"
"time"
orbcfg "github.com/caos/orbos/pkg/orb"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"gopkg.in/yaml.v3"
"github.com/caos/orbos/internal/operator/common"
"github.com/caos/orbos/mntr"
"github.com/caos/orbos/pkg/git"
"github.com/caos/orbos/pkg/secret"
"github.com/caos/orbos/pkg/tree"
)
func ToEnsureResult(done bool, err error) *EnsureResult {
return &EnsureResult{
Err: err,
Done: done,
}
}
type EnsureResult struct {
Err error
Done bool
}
type ConfigureFunc func(orb orbcfg.Orb) error
func NoopConfigure(orb orbcfg.Orb) error {
return nil
}
type QueryFunc func(nodeAgentsCurrent *common.CurrentNodeAgents, nodeAgentsDesired *common.DesiredNodeAgents, queried map[string]interface{}) (EnsureFunc, error)
type EnsureFunc func(pdf func(monitor mntr.Monitor) error) *EnsureResult
func NoopEnsure(_ func(monitor mntr.Monitor) error) *EnsureResult {
return &EnsureResult{Done: true}
}
type event struct {
commit string
files []git.File
}
func Instrument(monitor mntr.Monitor, healthyChan chan bool) {
defer func() { monitor.RecoverPanic(recover()) }()
healthy := true
prometheus.MustRegister(prometheus.NewBuildInfoCollector())
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/health", func(writer http.ResponseWriter, request *http.Request) {
msg := "OK"
status := 200
if !healthy {
msg = "ORBITER is not healthy. See the logs."
status = 404
}
writer.WriteHeader(status)
writer.Write([]byte(msg))
})
go func() {
timeout := 10 * time.Minute
ticker := time.NewTimer(timeout)
for {
select {
case newHealthiness := <-healthyChan:
ticker.Reset(timeout)
if newHealthiness == healthy {
continue
}
healthy = newHealthiness
if !newHealthiness {
monitor.Error(errors.New("ORBITER is unhealthy now"))
continue
}
monitor.Info("ORBITER is healthy now")
case <-ticker.C:
monitor.Error(errors.New("ORBITER is unhealthy now as it did not report healthiness for 10 minutes"))
healthy = false
}
}
}()
if err := http.ListenAndServe(":9000", nil); err != nil {
panic(err)
}
}
func Adapt(gitClient *git.Client, monitor mntr.Monitor, finished chan struct{}, adapt AdaptFunc) (QueryFunc, DestroyFunc, ConfigureFunc, bool, *tree.Tree, *tree.Tree, map[string]*secret.Secret, error) {
treeDesired, err := gitClient.ReadTree(git.OrbiterFile)
if err != nil {
return nil, nil, nil, false, nil, nil, nil, err
}
treeCurrent := &tree.Tree{}
query, destroy, configure, migrate, secrets, err := adapt(monitor, finished, treeDesired, treeCurrent)
return query, destroy, configure, migrate, treeDesired, treeCurrent, secrets, err
}
func Takeoff(monitor mntr.Monitor, conf *Config, healthyChan chan bool) func() {
return func() {
var err error
defer func() {
go func() {
if err != nil {
healthyChan <- false
return
}
healthyChan <- true
}()
}()
query, _, _, migrate, treeDesired, treeCurrent, _, err := Adapt(conf.GitClient, monitor, conf.FinishedChan, conf.Adapt)
if err != nil {
monitor.Error(err)
return
}
desiredNodeAgents := common.NodeAgentsDesiredKind{
Kind: "nodeagent.caos.ch/NodeAgents",
Version: "v0",
Spec: common.NodeAgentsSpec{
Commit: conf.OrbiterCommit,
},
}
marshalCurrentFiles := func() []git.File {
return []git.File{{
Path: "caos-internal/orbiter/current.yml",
Content: common.MarshalYAML(treeCurrent),
}, {
Path: "caos-internal/orbiter/node-agents-desired.yml",
Content: common.MarshalYAML(desiredNodeAgents),
}}
}
if migrate {
if err = conf.GitClient.PushGitDesiredStates(monitor, "Desired state migrated", []git.GitDesiredState{{
Desired: treeDesired,
Path: git.OrbiterFile,
}}); err != nil {
monitor.Error(err)
return
}
}
currentNodeAgents := common.NodeAgentsCurrentKind{}
if err := yaml.Unmarshal(conf.GitClient.Read("caos-internal/orbiter/node-agents-current.yml"), ¤tNodeAgents); err != nil {
monitor.Error(err)
return
}
handleAdapterError := func(err error) {
monitor.Error(err)
if commitErr := conf.GitClient.Commit(mntr.CommitRecord([]*mntr.Field{{Pos: 0, Key: "err", Value: err.Error()}})); commitErr != nil {
monitor.Error(err)
return
}
monitor.Error(conf.GitClient.Push())
}
ensure, err := query(¤tNodeAgents.Current, &desiredNodeAgents.Spec.NodeAgents, nil)
if err != nil {
handleAdapterError(err)
return
}
if err := conf.GitClient.Clone(); err != nil {
monitor.Error(err)
return
}
reconciledCurrentStateMsg := "Current state reconciled"
if err := conf.GitClient.UpdateRemote(reconciledCurrentStateMsg, func() []git.File {
return []git.File{marshalCurrentFiles()[0]}
}); err != nil {
monitor.Error(err)
return
}
result := ensure(conf.GitClient.PushDesiredFunc(git.OrbiterFile, treeDesired))
if result.Err != nil {
handleAdapterError(result.Err)
return
}
if result.Done {
monitor.Info("Desired state is ensured")
} else {
monitor.Info("Desired state is not yet ensured")
}
conf.GitClient.UpdateRemote("Current state changed", func() []git.File {
pushFiles := marshalCurrentFiles()
if result.Done {
var deletedACurrentNodeAgent bool
for currentNA := range currentNodeAgents.Current.NA {
if _, ok := desiredNodeAgents.Spec.NodeAgents.NA[currentNA]; !ok {
currentNodeAgents.Current.NA[currentNA] = nil
delete(currentNodeAgents.Current.NA, currentNA)
deletedACurrentNodeAgent = true
}
}
if deletedACurrentNodeAgent {
monitor.Info("Clearing node agents current states")
pushFiles = append(pushFiles, git.File{
Path: "caos-internal/orbiter/node-agents-current.yml",
Content: common.MarshalYAML(currentNodeAgents),
})
}
}
return pushFiles
})
}
}