discovery.go 7.77 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
// discovery provides container information resolution via containerd.
// This prefers containerd RPCs for configuration over /proc inspection,
// following the principle that configuration should come from the container runtime
// while runtime state (like namespace inodes) requires /proc.
package k8s

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/containerd/containerd"
	"github.com/containerd/containerd/namespaces"
	specs "github.com/opencontainers/runtime-spec/specs-go"
)

const (
	// K8sNamespace is the containerd namespace used by Kubernetes
	K8sNamespace = "k8s.io"
	// DefaultSocket is the default containerd socket path
	DefaultSocket = "/run/containerd/containerd.sock"
)

// ContainerInfo holds resolved container information from containerd.
// Configuration data comes from containerd RPCs, runtime state from /proc.
type ContainerInfo struct {
	ContainerID string
	PID         uint32
	RootFS      string // Actual rootfs path (bundle path + spec.Root.Path)
	BundlePath  string // Path to container bundle directory
	Image       string
	Spec        *specs.Spec // OCI spec from containerd (mounts, namespaces config)
	Labels      map[string]string
}

// MountInfo represents a mount from the OCI spec.
type MountInfo struct {
	Destination string   // Mount point inside container
	Source      string   // Source path on host
	Type        string   // Filesystem type (bind, tmpfs, etc.)
	Options     []string // Mount options
}

// NamespaceConfig represents namespace configuration from OCI spec.
type NamespaceConfig struct {
	Type string // Namespace type (network, pid, mount, etc.)
	Path string // Path to namespace (empty for new namespace)
}

// DiscoveryClient wraps the containerd client for container discovery.
type DiscoveryClient struct {
	client *containerd.Client
	socket string
}

// NewDiscoveryClient creates a new discovery client.
func NewDiscoveryClient(socket string) (*DiscoveryClient, error) {
	if socket == "" {
		socket = DefaultSocket
	}

	client, err := containerd.New(socket)
	if err != nil {
		return nil, fmt.Errorf("failed to connect to containerd at %s: %w", socket, err)
	}

	return &DiscoveryClient{
		client: client,
		socket: socket,
	}, nil
}

// Close closes the containerd client connection.
func (c *DiscoveryClient) Close() error {
	if c.client != nil {
		return c.client.Close()
	}
	return nil
}

// ResolveContainer resolves a container ID to its process information.
// This retrieves configuration from containerd RPCs (OCI spec, labels, image)
// and runtime paths from /proc (rootfs access path).
func (c *DiscoveryClient) ResolveContainer(ctx context.Context, containerID string) (*ContainerInfo, error) {
	// Use the Kubernetes namespace for containerd
	ctx = namespaces.WithNamespace(ctx, K8sNamespace)

	// Load the container
	container, err := c.client.LoadContainer(ctx, containerID)
	if err != nil {
		return nil, fmt.Errorf("failed to load container %s: %w", containerID, err)
	}

	// Get the task (running process)
	task, err := container.Task(ctx, nil)
	if err != nil {
		return nil, fmt.Errorf("failed to get task for container %s: %w", containerID, err)
	}

	// Get the PID
	pid := task.Pid()

	// Get container image
	image, err := container.Image(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to get image for container %s: %w", containerID, err)
	}

	// Get OCI spec from containerd - this contains mount config, namespace config, etc.
	// This is preferred over parsing /proc for configuration data.
	spec, err := container.Spec(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to get spec for container %s: %w", containerID, err)
	}

	// Get container labels (includes K8s pod info)
	labels, err := container.Labels(ctx)
	if err != nil {
		// Labels are optional, don't fail
		labels = make(map[string]string)
	}

	// Construct the bundle path where containerd stores the container runtime files
	// Standard containerd layout: /run/containerd/io.containerd.runtime.v2.task/<namespace>/<container_id>/
	containerdRunRoot := os.Getenv("CONTAINERD_RUN_ROOT")
	if containerdRunRoot == "" {
		containerdRunRoot = "/run/containerd"
	}
	bundlePath := filepath.Join(containerdRunRoot, "io.containerd.runtime.v2.task", K8sNamespace, containerID)

	// Get the rootfs path from the OCI spec (usually "rootfs" relative to bundle)
	rootfsRelPath := "rootfs"
	if spec.Root != nil && spec.Root.Path != "" {
		rootfsRelPath = spec.Root.Path
	}

	// Construct full rootfs path
	var rootFS string
	if filepath.IsAbs(rootfsRelPath) {
		rootFS = rootfsRelPath
	} else {
		rootFS = filepath.Join(bundlePath, rootfsRelPath)
	}

	return &ContainerInfo{
		ContainerID: containerID,
		PID:         pid,
		RootFS:      rootFS,
		BundlePath:  bundlePath,
		Image:       image.Name(),
		Spec:        spec,
		Labels:      labels,
	}, nil
}

// GetMounts returns the mount configuration from the OCI spec.
// This is preferred over parsing /proc/mountinfo for configuration,
// though /proc is still needed for runtime mount state.
func (info *ContainerInfo) GetMounts() []MountInfo {
	if info.Spec == nil || info.Spec.Mounts == nil {
		return nil
	}

	mounts := make([]MountInfo, len(info.Spec.Mounts))
	for i, m := range info.Spec.Mounts {
		mounts[i] = MountInfo{
			Destination: m.Destination,
			Source:      m.Source,
			Type:        m.Type,
			Options:     m.Options,
		}
	}
	return mounts
}

// GetNamespaces returns the namespace configuration from the OCI spec.
func (info *ContainerInfo) GetNamespaces() []NamespaceConfig {
	if info.Spec == nil || info.Spec.Linux == nil {
		return nil
	}

	namespaces := make([]NamespaceConfig, len(info.Spec.Linux.Namespaces))
	for i, ns := range info.Spec.Linux.Namespaces {
		namespaces[i] = NamespaceConfig{
			Type: string(ns.Type),
			Path: ns.Path,
		}
	}
	return namespaces
}

// GetMaskedPaths returns the masked paths from the OCI spec.
func (info *ContainerInfo) GetMaskedPaths() []string {
	if info.Spec == nil || info.Spec.Linux == nil {
		return nil
	}
	return info.Spec.Linux.MaskedPaths
}

// GetReadonlyPaths returns the readonly paths from the OCI spec.
func (info *ContainerInfo) GetReadonlyPaths() []string {
	if info.Spec == nil || info.Spec.Linux == nil {
		return nil
	}
	return info.Spec.Linux.ReadonlyPaths
}

// GetRootfsPath returns the rootfs path from the OCI spec.
// Note: For CRIU, use info.RootFS which is the /proc/<pid>/root path.
func (info *ContainerInfo) GetRootfsPath() string {
	if info.Spec == nil || info.Spec.Root == nil {
		return ""
	}
	return info.Spec.Root.Path
}

// IsRootReadonly returns whether the root filesystem is readonly.
func (info *ContainerInfo) IsRootReadonly() bool {
	if info.Spec == nil || info.Spec.Root == nil {
		return false
	}
	return info.Spec.Root.Readonly
}

// GetHostname returns the container's hostname from the OCI spec.
func (info *ContainerInfo) GetHostname() string {
	if info.Spec == nil {
		return ""
	}
	return info.Spec.Hostname
}

// ListContainers lists all containers in the K8s namespace.
func (c *DiscoveryClient) ListContainers(ctx context.Context) ([]string, error) {
	ctx = namespaces.WithNamespace(ctx, K8sNamespace)

	containers, err := c.client.Containers(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to list containers: %w", err)
	}

	ids := make([]string, len(containers))
	for i, container := range containers {
		ids[i] = container.ID()
	}

	return ids, nil
}

// GetContainerLabels returns the labels for a container.
func (c *DiscoveryClient) GetContainerLabels(ctx context.Context, containerID string) (map[string]string, error) {
	ctx = namespaces.WithNamespace(ctx, K8sNamespace)

	container, err := c.client.LoadContainer(ctx, containerID)
	if err != nil {
		return nil, fmt.Errorf("failed to load container %s: %w", containerID, err)
	}

	labels, err := container.Labels(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed to get labels for container %s: %w", containerID, err)
	}

	return labels, nil
}