-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathdependency.go
More file actions
356 lines (313 loc) · 10.9 KB
/
dependency.go
File metadata and controls
356 lines (313 loc) · 10.9 KB
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package dependency
import (
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
"github.com/utmstack/UTMStack/agent/utils"
"github.com/utmstack/UTMStack/shared/fs"
"github.com/utmstack/UTMStack/shared/http"
)
const (
updaterBaseName = "utmstack_updater_service"
// Dependency versions - single source of truth
UpdaterVersion = "11.2.3"
BeatsVersion = "11.2.3"
MacosCollectorVersion = "11.2.3"
)
// getUpdaterVersion reads the desired updater version from version.json
// (the updater_version field). Falls back to UpdaterVersion if the
// file is missing, unreadable, or the field is empty.
//
// The source of truth for this value is version.json shipped by the server,
// which the updater promotes on each successful agent update.
func getUpdaterVersion() string {
var v struct {
UpdaterVersion string `json:"updater_version"`
}
versionPath := filepath.Join(fs.GetExecutablePath(), "version.json")
if !fs.Exists(versionPath) {
return UpdaterVersion
}
if err := fs.ReadJSON(versionPath, &v); err != nil {
return UpdaterVersion
}
if v.UpdaterVersion == "" {
return UpdaterVersion
}
return v.UpdaterVersion
}
// UpdaterFile returns the updater binary name with OS and architecture suffix.
// Format: utmstack_updater_service_<os>_<arch>[.exe]
// Examples:
// - utmstack_updater_service_linux_amd64
// - utmstack_updater_service_windows_amd64.exe
// - utmstack_updater_service_darwin_arm64
func UpdaterFile(suffix string) string {
name := fmt.Sprintf("%s_%s_%s%s", updaterBaseName, runtime.GOOS, runtime.GOARCH, suffix)
if runtime.GOOS == "windows" {
return name + ".exe"
}
return name
}
// Dependency represents a dependency that the agent needs.
type Dependency struct {
Name string // Unique identifier
Version string // Current version in this agent build
BinaryPath string // Path to check if already exists
DownloadURL func(server string) string // URL template to download from
DownloadName string // Filename to save as (if different from BinaryPath basename)
Critical bool // If true, failure blocks agent startup
PreDownload func() (cleanup func(), err error) // Called before download, returns cleanup for rollback
PostDownload func() error // Run after download (e.g., unzip). Can be nil.
Configure func() error // Run on first install (can be nil)
Update func() error // Run on version change (can be nil, uses Configure)
Uninstall func() error // Run when dependency is removed (can be nil)
}
// Exists checks if the dependency binary exists on disk.
func (d *Dependency) Exists() bool {
return fs.Exists(d.BinaryPath)
}
// InstalledDep represents a dependency that has been installed and tracked.
type InstalledDep struct {
Name string `json:"name"`
Version string `json:"version"`
}
// InstalledDeps is the list of installed dependencies (persisted to JSON).
type InstalledDeps struct {
Dependencies []InstalledDep `json:"dependencies"`
}
func (i *InstalledDeps) Get(name string) *InstalledDep {
for idx := range i.Dependencies {
if i.Dependencies[idx].Name == name {
return &i.Dependencies[idx]
}
}
return nil
}
func (i *InstalledDeps) Add(name, version string) {
i.Dependencies = append(i.Dependencies, InstalledDep{Name: name, Version: version})
}
func (i *InstalledDeps) Update(name, version string) {
for idx := range i.Dependencies {
if i.Dependencies[idx].Name == name {
i.Dependencies[idx].Version = version
return
}
}
}
func (i *InstalledDeps) Remove(name string) {
for idx := range i.Dependencies {
if i.Dependencies[idx].Name == name {
i.Dependencies = append(i.Dependencies[:idx], i.Dependencies[idx+1:]...)
return
}
}
}
func (i *InstalledDeps) Has(name string) bool {
return i.Get(name) != nil
}
var (
installedDepsFile = filepath.Join(fs.GetExecutablePath(), "dependencies.json")
reconcileMu sync.Mutex
)
// readInstalledDeps reads the installed dependencies from disk.
func readInstalledDeps() (*InstalledDeps, error) {
installed := &InstalledDeps{Dependencies: []InstalledDep{}}
if !fs.Exists(installedDepsFile) {
return installed, nil
}
if err := fs.ReadJSON(installedDepsFile, installed); err != nil {
return nil, fmt.Errorf("error reading dependencies file: %v", err)
}
return installed, nil
}
// writeInstalledDeps writes the installed dependencies to disk.
func writeInstalledDeps(installed *InstalledDeps) error {
return fs.WriteJSON(installedDepsFile, installed)
}
// Reconcile ensures all dependencies are installed and up-to-date.
// This should be called at agent startup, before starting collectors.
func Reconcile(server string, skipCertValidation bool) error {
reconcileMu.Lock()
defer reconcileMu.Unlock()
utils.Logger.Info("Starting dependency reconciliation...")
installed, err := readInstalledDeps()
if err != nil {
return fmt.Errorf("failed to read installed dependencies: %v", err)
}
desired := GetDependencies()
var criticalErrors []error
// Process each desired dependency
for _, dep := range desired {
inst := installed.Get(dep.Name)
if inst == nil {
// Not tracked yet
if dep.Exists() {
// MIGRATION: Already installed by previous version, configure and track it
utils.Logger.Info("Migrating existing dependency: %s (version %s)", dep.Name, dep.Version)
if dep.Configure != nil {
if err := dep.Configure(); err != nil {
errMsg := fmt.Errorf("failed to configure migrated dependency %s: %v", dep.Name, err)
utils.Logger.ErrorF("%v", errMsg)
if dep.Critical {
criticalErrors = append(criticalErrors, errMsg)
}
continue
}
}
installed.Add(dep.Name, dep.Version)
} else {
// FRESH INSTALL: Download (if needed) and configure
utils.Logger.Info("Installing new dependency: %s (version %s)", dep.Name, dep.Version)
if dep.DownloadURL != nil {
if err := downloadDependency(dep, server, skipCertValidation); err != nil {
errMsg := fmt.Errorf("failed to download dependency %s: %v", dep.Name, err)
utils.Logger.ErrorF("%v", errMsg)
if dep.Critical {
criticalErrors = append(criticalErrors, errMsg)
}
continue
}
}
if dep.Configure != nil {
if err := dep.Configure(); err != nil {
errMsg := fmt.Errorf("failed to configure dependency %s: %v", dep.Name, err)
utils.Logger.ErrorF("%v", errMsg)
if dep.Critical {
criticalErrors = append(criticalErrors, errMsg)
}
continue
}
}
installed.Add(dep.Name, dep.Version)
utils.Logger.Info("Dependency %s installed successfully", dep.Name)
}
} else if inst.Version != dep.Version {
// VERSION CHANGED: Download (if needed) and update
utils.Logger.Info("Updating dependency: %s (%s -> %s)", dep.Name, inst.Version, dep.Version)
// Call PreDownload hook if defined
var cleanup func()
if dep.PreDownload != nil {
var err error
cleanup, err = dep.PreDownload()
if err != nil {
errMsg := fmt.Errorf("failed to run PreDownload for %s: %v", dep.Name, err)
utils.Logger.ErrorF("%v", errMsg)
if dep.Critical {
criticalErrors = append(criticalErrors, errMsg)
}
continue
}
}
if dep.DownloadURL != nil {
if err := downloadDependency(dep, server, skipCertValidation); err != nil {
errMsg := fmt.Errorf("failed to download dependency update %s: %v", dep.Name, err)
utils.Logger.ErrorF("%v", errMsg)
if dep.Critical {
criticalErrors = append(criticalErrors, errMsg)
}
// Rollback: call cleanup if PreDownload succeeded
if cleanup != nil {
utils.Logger.Info("Rolling back PreDownload changes for %s", dep.Name)
cleanup()
}
continue
}
}
updateFn := dep.Update
if updateFn == nil {
updateFn = dep.Configure
}
if updateFn != nil {
if err := updateFn(); err != nil {
errMsg := fmt.Errorf("failed to update dependency %s: %v", dep.Name, err)
utils.Logger.ErrorF("%v", errMsg)
if dep.Critical {
criticalErrors = append(criticalErrors, errMsg)
}
// Rollback: call cleanup if PreDownload succeeded
if cleanup != nil {
utils.Logger.Info("Rolling back PreDownload changes for %s", dep.Name)
cleanup()
}
continue
}
}
installed.Update(dep.Name, dep.Version)
utils.Logger.Info("Dependency %s updated successfully", dep.Name)
} else {
// Same version, nothing to do
utils.Logger.Info("Dependency %s is up to date (version %s)", dep.Name, dep.Version)
}
}
// CLEANUP: Remove dependencies that are no longer needed
for _, inst := range installed.Dependencies {
found := false
for _, dep := range desired {
if dep.Name == inst.Name {
found = true
break
}
}
if !found {
utils.Logger.Info("Removing obsolete dependency: %s", inst.Name)
// Find the uninstall function if we have it from old code
// For now, just remove from tracking
installed.Remove(inst.Name)
}
}
// Save the updated installed dependencies
if err := writeInstalledDeps(installed); err != nil {
return fmt.Errorf("failed to write installed dependencies: %v", err)
}
if len(criticalErrors) > 0 {
return fmt.Errorf("critical dependency errors: %v", criticalErrors)
}
utils.Logger.Info("Dependency reconciliation completed")
return nil
}
// UninstallAll calls the Uninstall hook for all dependencies that have one.
// This should be called during agent uninstall to clean up dependency artifacts.
func UninstallAll() error {
utils.Logger.Info("Starting dependency uninstall...")
for _, dep := range GetDependencies() {
if dep.Uninstall != nil {
utils.Logger.Info("Uninstalling dependency: %s", dep.Name)
if err := dep.Uninstall(); err != nil {
utils.Logger.ErrorF("failed to uninstall %s: %v", dep.Name, err)
// Continue with other dependencies even if one fails
}
}
}
utils.Logger.Info("Dependency uninstall completed")
return nil
}
// downloadDependency downloads the dependency binary.
func downloadDependency(dep Dependency, server string, skipCertValidation bool) error {
if dep.DownloadURL == nil {
return fmt.Errorf("dependency %s has no download URL", dep.Name)
}
url := dep.DownloadURL(server)
// Use DownloadName if specified, otherwise use basename of BinaryPath
filename := dep.DownloadName
if filename == "" {
filename = filepath.Base(dep.BinaryPath)
}
destDir := filepath.Dir(dep.BinaryPath)
// Ensure destination directory exists
if err := os.MkdirAll(destDir, 0755); err != nil {
return fmt.Errorf("failed to create directory %s: %v", destDir, err)
}
if err := http.DownloadFile(url, map[string]string{}, filename, destDir, skipCertValidation); err != nil {
return err
}
// Run post-download hook if defined (e.g., unzip)
if dep.PostDownload != nil {
if err := dep.PostDownload(); err != nil {
return fmt.Errorf("post-download failed: %v", err)
}
}
return nil
}