-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcommands.go
More file actions
352 lines (295 loc) · 11.1 KB
/
commands.go
File metadata and controls
352 lines (295 loc) · 11.1 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
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"go.goms.io/aks/AKSFlexNode/pkg/bootstrapper"
"go.goms.io/aks/AKSFlexNode/pkg/config"
"go.goms.io/aks/AKSFlexNode/pkg/logger"
"go.goms.io/aks/AKSFlexNode/pkg/spec"
"go.goms.io/aks/AKSFlexNode/pkg/status"
)
// Version information variables (set at build time)
var (
Version = "dev"
GitCommit = "unknown"
BuildTime = "unknown"
)
func NewApplyCommand() *cobra.Command {
var flagMode string
cmd := &cobra.Command{
Use: "apply",
Short: "Apply configuration to the node",
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
logger := logger.GetLoggerFromContext(ctx)
cfg, err := config.LoadConfig(configPath)
if err != nil {
return fmt.Errorf("failed to load config from %s: %w", configPath, err)
}
var b interface {
Bootstrap(context.Context) (*bootstrapper.ExecutionResult, error)
}
if strings.EqualFold(flagMode, "minimal") {
logger.Info("Using minimal bootstrapper mode")
b = bootstrapper.NewMinimal(cfg, logger)
} else {
logger.Info("Using full bootstrapper mode")
b = bootstrapper.New(cfg, logger)
}
result, err := b.Bootstrap(ctx)
if err != nil {
return err
}
fmt.Printf(
"Bootstrap completed with success: %t, duration: %v, steps: %d\n",
result.Success, result.Duration, result.StepCount,
)
if !result.Success {
fmt.Printf("Bootstrap failed with error: %s\n", result.Error)
return fmt.Errorf("bootstrap failed: %s", result.Error)
}
return nil
},
}
cmd.Flags().StringVar(&flagMode, "mode", "minimal", "minimal or full")
return cmd
}
// NewAgentCommand creates a new agent command
func NewAgentCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "agent",
Short: "Start AKS node agent with Arc connection",
Long: "Initialize and run the AKS node agent daemon with automatic status tracking and self-recovery",
RunE: func(cmd *cobra.Command, args []string) error {
return runAgent(cmd.Context())
},
}
return cmd
}
// NewUnbootstrapCommand creates a new unbootstrap command
func NewUnbootstrapCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "unbootstrap",
Short: "Remove AKS node configuration and Arc connection",
Long: "Clean up and remove all AKS node components and Arc registration from this machine",
RunE: func(cmd *cobra.Command, args []string) error {
return runUnbootstrap(cmd.Context())
},
}
return cmd
}
// NewVersionCommand creates a new version command
func NewVersionCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "version",
Short: "Show version information",
Long: "Display version, build commit, and build time information",
Run: func(cmd *cobra.Command, args []string) {
runVersion()
},
}
return cmd
}
// runAgent executes the bootstrap process and then runs as daemon
func runAgent(ctx context.Context) error {
logger := logger.GetLoggerFromContext(ctx)
cfg, err := config.LoadConfig(configPath)
if err != nil {
return fmt.Errorf("failed to load config from %s: %w", configPath, err)
}
bootstrapExecutor := bootstrapper.New(cfg, logger)
result, err := bootstrapExecutor.Bootstrap(ctx)
if err != nil {
return err
}
// Handle and log the bootstrap result
if err := handleExecutionResult(result, "bootstrap", logger); err != nil {
return err
}
// After successful bootstrap, transition to daemon mode
logger.Info("Bootstrap completed successfully, transitioning to daemon mode...")
return runDaemonLoop(ctx, cfg)
}
// runUnbootstrap executes the unbootstrap process
func runUnbootstrap(ctx context.Context) error {
logger := logger.GetLoggerFromContext(ctx)
cfg, err := config.LoadConfig(configPath)
if err != nil {
return fmt.Errorf("failed to load config from %s: %w", configPath, err)
}
bootstrapExecutor := bootstrapper.New(cfg, logger)
result, err := bootstrapExecutor.Unbootstrap(ctx)
if err != nil {
return err
}
// Handle and log the result (unbootstrap is more lenient with failures)
return handleExecutionResult(result, "unbootstrap", logger)
}
// runVersion displays version information
func runVersion() {
fmt.Printf("AKS Flex Node Agent\n")
fmt.Printf("Version: %s\n", Version)
fmt.Printf("Git Commit: %s\n", GitCommit)
fmt.Printf("Build Time: %s\n", BuildTime)
}
// runDaemonLoop runs the periodic status collection and bootstrap monitoring daemon
func runDaemonLoop(ctx context.Context, cfg *config.Config) error {
logger := logger.GetLoggerFromContext(ctx)
// Create status file directory - using runtime directory for service or temp for development
statusFilePath := status.GetStatusFilePath()
statusDir := filepath.Dir(statusFilePath)
if err := os.MkdirAll(statusDir, 0o750); err != nil {
return fmt.Errorf("failed to create status directory %s: %w", statusDir, err)
}
// Clean up any stale status file on daemon startup
if _, err := os.Stat(statusFilePath); err == nil {
logger.Info("Removing stale status file from previous daemon session...")
if err := os.Remove(statusFilePath); err != nil {
logger.Warnf("Failed to remove stale status file: %v", err)
} else {
logger.Info("Stale status file removed successfully")
}
}
logger.Info("Starting periodic status collection daemon (status: 1 minutes, bootstrap check: 2 minute)")
// Create tickers for different intervals
statusTicker := time.NewTicker(1 * time.Minute)
bootstrapTicker := time.NewTicker(2 * time.Minute)
specTicker := time.NewTicker(30 * time.Minute)
defer statusTicker.Stop()
defer bootstrapTicker.Stop()
defer specTicker.Stop()
// Collect status immediately on start
if err := collectAndWriteStatus(ctx, cfg, statusFilePath); err != nil {
logger.Errorf("Failed to collect initial status: %v", err)
}
// Collect managed cluster spec once on daemon startup.
if err := collectAndWriteManagedClusterSpec(ctx, cfg); err != nil {
logger.Warnf("Failed to collect initial managed cluster spec: %v", err)
}
// Run the periodic collection and monitoring loop
for {
select {
case <-ctx.Done():
logger.Info("Daemon shutting down due to context cancellation")
return ctx.Err()
case <-statusTicker.C:
logger.Infof("Starting periodic status collection at %s...", time.Now().Format("2006-01-02 15:04:05"))
if err := collectAndWriteStatus(ctx, cfg, statusFilePath); err != nil {
logger.Errorf("Failed to collect status at %s: %v", time.Now().Format("2006-01-02 15:04:05"), err)
// Continue running even if status collection fails
} else {
logger.Infof("Status collection completed successfully at %s", time.Now().Format("2006-01-02 15:04:05"))
}
case <-bootstrapTicker.C:
logger.Infof("Starting bootstrap health check at %s...", time.Now().Format("2006-01-02 15:04:05"))
if err := checkAndBootstrap(ctx, cfg); err != nil {
logger.Errorf("Auto-bootstrap check failed at %s: %v", time.Now().Format("2006-01-02 15:04:05"), err)
// Continue running even if bootstrap check fails
} else {
logger.Infof("Bootstrap health check completed at %s", time.Now().Format("2006-01-02 15:04:05"))
}
case <-specTicker.C:
logger.Infof("Starting periodic managed cluster spec collection at %s...", time.Now().Format("2006-01-02 15:04:05"))
if err := collectAndWriteManagedClusterSpec(ctx, cfg); err != nil {
logger.Warnf("Failed to collect managed cluster spec at %s: %v", time.Now().Format("2006-01-02 15:04:05"), err)
} else {
logger.Infof("Managed cluster spec collection completed at %s", time.Now().Format("2006-01-02 15:04:05"))
}
}
}
}
func collectAndWriteManagedClusterSpec(ctx context.Context, cfg *config.Config) error {
logger := logger.GetLoggerFromContext(ctx)
collector := spec.NewManagedClusterSpecCollector(cfg, logger)
_, err := collector.Collect(ctx)
return err
}
// checkAndBootstrap checks if the node needs re-bootstrapping and performs it if necessary
func checkAndBootstrap(ctx context.Context, cfg *config.Config) error {
logger := logger.GetLoggerFromContext(ctx)
// Create status collector to check bootstrap requirements
collector := status.NewCollector(cfg, logger, Version)
// Check if bootstrap is needed
needsBootstrap := collector.NeedsBootstrap(ctx)
if !needsBootstrap {
return nil // All good, no action needed
}
logger.Info("Node requires re-bootstrapping, initiating auto-bootstrap...")
// Perform bootstrap
bootstrapExecutor := bootstrapper.New(cfg, logger)
result, err := bootstrapExecutor.Bootstrap(ctx)
if err != nil {
// Bootstrap failed - remove status file so next check will detect the problem
removeStatusFile(ctx)
return fmt.Errorf("auto-bootstrap failed: %s", err)
}
// Handle and log the bootstrap result
if err := handleExecutionResult(result, "auto-bootstrap", logger); err != nil {
// Bootstrap execution failed - remove status file so next check will detect the problem
removeStatusFile(ctx)
return fmt.Errorf("auto-bootstrap execution failed: %s", err)
}
logger.Info("Auto-bootstrap completed successfully")
return nil
}
func removeStatusFile(ctx context.Context) {
logger := logger.GetLoggerFromContext(ctx)
statusFilePath := status.GetStatusFilePath()
if removeErr := os.Remove(statusFilePath); removeErr != nil {
logger.Debugf("Failed to remove status file: %s", removeErr)
} else {
logger.Debug("Removed status file successfully")
}
}
// collectAndWriteStatus collects current node status and writes it to the status file
func collectAndWriteStatus(ctx context.Context, cfg *config.Config, statusFilePath string) error {
logger := logger.GetLoggerFromContext(ctx)
// Create status collector
collector := status.NewCollector(cfg, logger, Version)
// Collect comprehensive status
nodeStatus, err := collector.CollectStatus(ctx)
if err != nil {
return fmt.Errorf("failed to collect node status: %w", err)
}
// Write status to JSON file
statusData, err := json.MarshalIndent(nodeStatus, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal status to JSON: %w", err)
}
// Write to temporary file first, then rename (atomic operation)
tempFile := statusFilePath + ".tmp"
if err := os.WriteFile(tempFile, statusData, 0o600); err != nil {
return fmt.Errorf("failed to write status to temp file: %w", err)
}
if err := os.Rename(tempFile, statusFilePath); err != nil {
return fmt.Errorf("failed to rename temp status file: %w", err)
}
logger.Debugf("Status written to %s", statusFilePath)
return nil
}
// handleExecutionResult processes and logs execution results
func handleExecutionResult(result *bootstrapper.ExecutionResult, operation string, logger *logrus.Logger) error {
if result == nil {
return fmt.Errorf("%s result is nil", operation)
}
if result.Success {
logger.Infof("%s completed successfully (duration: %v, steps: %d)",
operation, result.Duration, result.StepCount)
return nil
}
if operation == "unbootstrap" {
// For unbootstrap, log warnings but don't fail completely
logger.Warnf("%s completed with some failures: %s (duration: %v)",
operation, result.Error, result.Duration)
return nil
}
// For bootstrap, return error on failure
return fmt.Errorf("%s failed: %s", operation, result.Error)
}