watcher.go 14.1 KB
Newer Older
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// Package watcher provides Kubernetes pod watching for automatic checkpointing.
package watcher

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/sirupsen/logrus"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/cache"

	"github.com/ai-dynamo/dynamo/deploy/chrek/pkg/checkpoint"
	checkpointk8s "github.com/ai-dynamo/dynamo/deploy/chrek/pkg/checkpoint/k8s"
)

const (
	// LabelCheckpointSource is the label that triggers automatic checkpointing
	LabelCheckpointSource = "nvidia.com/checkpoint-source"

	// LabelCheckpointHash is the label specifying the checkpoint identity hash
	LabelCheckpointHash = "nvidia.com/checkpoint-hash"

	// EnvCheckpointSignalFile is the env var in the pod specifying the signal file path
	EnvCheckpointSignalFile = "DYN_CHECKPOINT_SIGNAL_FILE"
)

// SignalFile represents the content of a checkpoint completion signal file
type SignalFile struct {
	CheckpointID   string    `json:"checkpoint_id"`
	CheckpointPath string    `json:"checkpoint_path"`
	Timestamp      time.Time `json:"timestamp"`
	Success        bool      `json:"success"`
	Error          string    `json:"error,omitempty"`
}

// Config holds watcher configuration
type Config struct {
	NodeName            string
	CheckpointDir       string
	HostProc            string
	ListenAddr          string // HTTP server address for health checks (e.g., ":8080")
	RestrictedNamespace string // Optional: restrict watching to this namespace (empty = cluster-wide)

	// GPU/CUDA checkpoint options (passed to checkpoint.Options)
	CUDAPluginDir  string   // Path to CRIU CUDA plugin directory
	GhostLimit     uint32   // Ghost file size limit in bytes (default: 512MB for GPU)
	Timeout        uint32   // CRIU timeout in seconds
	ExternalMounts []string // Additional external mount mappings
}

// Watcher watches for pods with checkpoint labels and triggers checkpoints
type Watcher struct {
	config          Config
	clientset       kubernetes.Interface
	discoveryClient *checkpointk8s.DiscoveryClient
	checkpointer    *checkpoint.Checkpointer
	log             *logrus.Entry

	// Track pods checkpoint status: "in_progress", "completed", or "" (not started/failed)
	checkpointed   map[string]string
	checkpointedMu sync.RWMutex

	stopCh chan struct{}
}

// NewWatcher creates a new pod watcher
func NewWatcher(cfg Config, discoveryClient *checkpointk8s.DiscoveryClient, checkpointer *checkpoint.Checkpointer) (*Watcher, error) {
	// Create in-cluster Kubernetes client
	restConfig, err := rest.InClusterConfig()
	if err != nil {
		return nil, fmt.Errorf("failed to get in-cluster config: %w", err)
	}

	clientset, err := kubernetes.NewForConfig(restConfig)
	if err != nil {
		return nil, fmt.Errorf("failed to create kubernetes client: %w", err)
	}

	return &Watcher{
		config:          cfg,
		clientset:       clientset,
		discoveryClient: discoveryClient,
		checkpointer:    checkpointer,
		log:             logrus.WithField("component", "watcher"),
		checkpointed:    make(map[string]string),
		stopCh:          make(chan struct{}),
	}, nil
}

// Start begins watching for pods and starts the health check server
func (w *Watcher) Start(ctx context.Context) error {
	w.log.WithFields(logrus.Fields{
		"node":            w.config.NodeName,
		"label":           LabelCheckpointSource,
		"signal_file_env": EnvCheckpointSignalFile,
	}).Info("Starting pod watcher")

	// Start health check HTTP server if address is configured
	if w.config.ListenAddr != "" {
		httpServer := w.startHealthServer(ctx)
		defer func() {
			shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()
			httpServer.Shutdown(shutdownCtx)
		}()
	}

	// Create informer factory with label selector and optional namespace restriction
	labelSelector := labels.SelectorFromSet(labels.Set{
		LabelCheckpointSource: "true",
	}).String()

	factoryOptions := []informers.SharedInformerOption{
		informers.WithTweakListOptions(func(opts *metav1.ListOptions) {
			opts.LabelSelector = labelSelector
		}),
	}

	// If namespace is specified, restrict watching to that namespace
	if w.config.RestrictedNamespace != "" {
		w.log.WithField("namespace", w.config.RestrictedNamespace).Info("Restricting pod watching to namespace")
		factoryOptions = append(factoryOptions, informers.WithNamespace(w.config.RestrictedNamespace))
	} else {
		w.log.Info("Watching pods cluster-wide (all namespaces)")
	}

	factory := informers.NewSharedInformerFactoryWithOptions(
		w.clientset,
		30*time.Second,
		factoryOptions...,
	)

	podInformer := factory.Core().V1().Pods().Informer()

	// Add event handlers
	podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			pod := obj.(*corev1.Pod)
			w.handlePodEvent(ctx, pod)
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			pod := newObj.(*corev1.Pod)
			w.handlePodEvent(ctx, pod)
		},
	})

	// Start informer
	go factory.Start(w.stopCh)

	// Wait for cache sync
	if !cache.WaitForCacheSync(w.stopCh, podInformer.HasSynced) {
		return fmt.Errorf("failed to sync informer cache")
	}

	w.log.Info("Pod watcher started and cache synced")

	// Wait for context cancellation
	<-ctx.Done()
	close(w.stopCh)

	return nil
}

// HealthResponse is the response for health check endpoint
type HealthResponse struct {
	Status   string `json:"status"`
	NodeName string `json:"node_name"`
}

// startHealthServer starts an HTTP server for health checks
func (w *Watcher) startHealthServer(ctx context.Context) *http.Server {
	mux := http.NewServeMux()
	mux.HandleFunc("/health", func(rw http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			http.Error(rw, "Method not allowed", http.StatusMethodNotAllowed)
			return
		}
		rw.Header().Set("Content-Type", "application/json")
		json.NewEncoder(rw).Encode(HealthResponse{
			Status:   "healthy",
			NodeName: w.config.NodeName,
		})
	})

	server := &http.Server{
		Addr:         w.config.ListenAddr,
		Handler:      mux,
		ReadTimeout:  10 * time.Second,
		WriteTimeout: 10 * time.Second,
		IdleTimeout:  60 * time.Second,
	}

	go func() {
		w.log.WithField("addr", w.config.ListenAddr).Info("Starting health check server")
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			w.log.WithError(err).Error("Health check server error")
		}
	}()

	return server
}

// Stop stops the watcher
func (w *Watcher) Stop() {
	close(w.stopCh)
}

// handlePodEvent processes a pod event
func (w *Watcher) handlePodEvent(ctx context.Context, pod *corev1.Pod) {
	// Filter to pods on this node
	if pod.Spec.NodeName != w.config.NodeName {
		return
	}

	// Check if pod is Ready
	if !w.isPodReady(pod) {
		return
	}

	// Check if we've already checkpointed this pod
	podKey := fmt.Sprintf("%s/%s", pod.Namespace, pod.Name)

	// Get checkpoint ID from label (uses the checkpoint hash)
	checkpointID, ok := pod.Labels[LabelCheckpointHash]
	if !ok || checkpointID == "" {
		w.log.WithField("pod", podKey).Warn("Pod has checkpoint label but no checkpoint-hash label")
		return
	}

	// Check if checkpoint is already in progress or completed for this pod
	w.checkpointedMu.Lock()
	status := w.checkpointed[podKey]
	if status == "completed" || status == "in_progress" {
		w.checkpointedMu.Unlock()
		return
	}
	// Mark as in_progress to prevent concurrent attempts
	w.checkpointed[podKey] = "in_progress"
	w.checkpointedMu.Unlock()

	// Trigger checkpoint
	w.log.WithFields(logrus.Fields{
		"pod":           podKey,
		"checkpoint_id": checkpointID,
	}).Info("Pod ready, triggering checkpoint")

	go w.doCheckpoint(ctx, pod, checkpointID, podKey)
}

// isPodReady checks if all containers in the pod are ready
func (w *Watcher) isPodReady(pod *corev1.Pod) bool {
	if pod.Status.Phase != corev1.PodRunning {
		return false
	}

	for _, cond := range pod.Status.Conditions {
		if cond.Type == corev1.PodReady && cond.Status == corev1.ConditionTrue {
			return true
		}
	}

	return false
}

// doCheckpoint performs the checkpoint and writes the signal file
func (w *Watcher) doCheckpoint(ctx context.Context, pod *corev1.Pod, checkpointID, podKey string) {
	log := w.log.WithFields(logrus.Fields{
		"pod":           podKey,
		"checkpoint_id": checkpointID,
	})

	// Find the main container and get signal file path from env
	var containerID string
	var signalFilePath string
	for _, container := range pod.Spec.Containers {
		if container.Name == "main" || len(pod.Spec.Containers) == 1 {
			// Get signal file path from environment
			for _, env := range container.Env {
				if env.Name == EnvCheckpointSignalFile {
					signalFilePath = env.Value
					break
				}
			}
			break
		}
	}

	// Get container ID from status
	for _, cs := range pod.Status.ContainerStatuses {
		if cs.Name == "main" || len(pod.Status.ContainerStatuses) == 1 {
			// Remove containerd:// prefix
			containerID = cs.ContainerID
			if len(containerID) > 13 && containerID[:13] == "containerd://" {
				containerID = containerID[13:]
			}
			break
		}
	}

	if containerID == "" {
		log.Error("Could not find container ID")
		w.checkpointedMu.Lock()
		delete(w.checkpointed, podKey)
		w.checkpointedMu.Unlock()
		return
	}

	if signalFilePath == "" {
		log.Warn("No DYN_CHECKPOINT_SIGNAL_FILE env var found, signal file will not be written")
	}

	log.WithFields(logrus.Fields{
		"container_id":     containerID,
		"signal_file_path": signalFilePath,
	}).Info("Found container, starting checkpoint")

	// Resolve container to get PID for signal file writing
	containerInfo, err := w.discoveryClient.ResolveContainer(ctx, containerID)
	if err != nil {
		log.WithError(err).Error("Failed to resolve container")
		w.checkpointedMu.Lock()
		delete(w.checkpointed, podKey)
		w.checkpointedMu.Unlock()
		return
	}

	// Perform checkpoint
	opts := checkpoint.Options{
		ContainerID:    containerID,
		CheckpointID:   checkpointID,
		CheckpointDir:  w.config.CheckpointDir,
		NodeName:       w.config.NodeName,
		PodName:        pod.Name,
		PodNamespace:   pod.Namespace,
		CUDAPluginDir:  w.config.CUDAPluginDir,
		GhostLimit:     w.config.GhostLimit,
		Timeout:        w.config.Timeout,
		ExternalMounts: w.config.ExternalMounts,
	}

	result, err := w.checkpointer.Checkpoint(ctx, opts)
	if err != nil {
		log.WithError(err).Error("Checkpoint failed")
		// Write failure marker to PVC so restore pods know checkpoint failed
		checkpointDir := filepath.Join(w.config.CheckpointDir, checkpointID)
		w.writeCheckpointDoneMarker(checkpointDir, checkpointID, false, err.Error(), log)
		if signalFilePath != "" {
			w.writeSignalFileToPod(int(containerInfo.PID), signalFilePath, checkpointID, "", false, err.Error())
		}
		// Clear the in_progress status so checkpoint can be retried
		w.checkpointedMu.Lock()
		delete(w.checkpointed, podKey)
		w.checkpointedMu.Unlock()
		return
	}

	log.WithField("checkpoint_dir", result.CheckpointDir).Info("Checkpoint completed successfully")

	// Write checkpoint.done marker to PVC for cross-node restore detection
	// This is written AFTER rootfs-diff.tar is complete, so it's safe to use as a completion marker
	w.writeCheckpointDoneMarker(result.CheckpointDir, checkpointID, true, "", log)

	// Write signal file to pod's hostPath for checkpoint job pod to exit
	if signalFilePath != "" {
		w.writeSignalFileToPod(int(containerInfo.PID), signalFilePath, checkpointID, result.CheckpointDir, true, "")
	}

	// Mark as completed so we don't checkpoint again
	w.checkpointedMu.Lock()
	w.checkpointed[podKey] = "completed"
	w.checkpointedMu.Unlock()
}

// writeSignalFileToPod writes a signal file to the checkpointed pod's filesystem
// via /proc/<pid>/root to indicate checkpoint completion
func (w *Watcher) writeSignalFileToPod(pid int, signalFilePath, checkpointID, checkpointPath string, success bool, errMsg string) {
	signal := SignalFile{
		CheckpointID:   checkpointID,
		CheckpointPath: checkpointPath,
		Timestamp:      time.Now().UTC(),
		Success:        success,
		Error:          errMsg,
	}

	data, err := json.MarshalIndent(signal, "", "  ")
	if err != nil {
		w.log.WithError(err).Error("Failed to marshal signal file")
		return
	}

	// Write to the pod's filesystem via /proc/<pid>/root
	// signalFilePath is the path inside the pod (e.g., /var/lib/dynamo-checkpoint/signal.done)
	hostSignalPath := fmt.Sprintf("%s/%d/root%s", w.config.HostProc, pid, signalFilePath)

	// Ensure signal directory exists in pod's filesystem
	signalDir := filepath.Dir(hostSignalPath)
	if err := os.MkdirAll(signalDir, 0755); err != nil {
		w.log.WithError(err).WithField("path", signalDir).Error("Failed to create signal directory in pod")
		return
	}

	if err := os.WriteFile(hostSignalPath, data, 0644); err != nil {
		w.log.WithError(err).WithField("path", hostSignalPath).Error("Failed to write signal file to pod")
		return
	}

	w.log.WithFields(logrus.Fields{
		"host_path": hostSignalPath,
		"pod_path":  signalFilePath,
		"pid":       pid,
		"success":   success,
	}).Info("Signal file written to pod filesystem")
}

// writeCheckpointDoneMarker writes a checkpoint.done marker file to the checkpoint directory on shared PVC.
// This file is written AFTER all checkpoint steps complete (including rootfs-diff.tar).
// Restore pods on ANY node check for this file to know the checkpoint is complete and safe to restore.
// This is separate from writeSignalFileToPod which signals the checkpoint job pod to exit.
func (w *Watcher) writeCheckpointDoneMarker(checkpointDir, checkpointID string, success bool, errMsg string, log *logrus.Entry) {
	markerPath := filepath.Join(checkpointDir, "checkpoint.done")

	marker := SignalFile{
		CheckpointID:   checkpointID,
		CheckpointPath: checkpointDir,
		Timestamp:      time.Now().UTC(),
		Success:        success,
		Error:          errMsg,
	}

	data, err := json.MarshalIndent(marker, "", "  ")
	if err != nil {
		log.WithError(err).Error("Failed to marshal checkpoint.done marker")
		return
	}

	if err := os.WriteFile(markerPath, data, 0644); err != nil {
		log.WithError(err).WithField("path", markerPath).Error("Failed to write checkpoint.done marker")
		return
	}

	log.WithFields(logrus.Fields{
		"path":    markerPath,
		"success": success,
	}).Info("checkpoint.done marker written to PVC")
}