-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer_scanner.go
109 lines (92 loc) · 2.63 KB
/
container_scanner.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
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"sync"
"syscall"
"github.com/containerd/containerd"
"github.com/containerd/containerd/cio"
"github.com/containerd/containerd/containers"
"github.com/containerd/containerd/events"
"github.com/containerd/containerd/namespaces"
)
func main() {
// Create a containerd client
client, err := containerd.New("/run/containerd/containerd.sock")
if err != nil {
log.Fatalf("Failed to connect to containerd: %v", err)
}
defer client.Close()
// Create a context with the "k8s.io" namespace
ctx := namespaces.WithNamespace(context.Background(), "k8s.io")
// Create a wait group to wait for goroutines to finish
var wg sync.WaitGroup
// Create a channel to handle termination signals
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
// Subscribe to container events
eventCh, err := client.Subscribe(ctx, events.WithFilter("topic==container"))
if err != nil {
log.Fatalf("Failed to subscribe to container events: %v", err)
}
// Handle container events in a separate goroutine
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case e := <-eventCh:
if e.Namespace != "k8s.io" {
// Skip events from other namespaces
continue
}
// Retrieve container information
container, err := client.LoadContainer(ctx, e.ID)
if err != nil {
log.Printf("Error loading container %s: %v", e.ID, err)
continue
}
// Skip non-running containers
task, err := container.Task(ctx, cio.Load)
if err != nil {
log.Printf("Error getting task for container %s: %v", e.ID, err)
continue
}
if task.Status(ctx).Status != containerd.Running {
continue
}
// Handle container creation event for running containers
wg.Add(1)
go func(containerID string) {
defer wg.Done()
// Retrieve container information
container, err := client.LoadContainer(ctx, containerID)
if err != nil {
log.Printf("Error loading container %s: %v", containerID, err)
return
}
name, _ := container.Labels(ctx)
// Print container information
fmt.Printf("Running container created: Name=%s, ID=%s, PID=%d\n", name, containerID, task.Pid())
}(e.ID)
}
}
}()
fmt.Println("Waiting for running container creation events...")
// Wait for termination signals
select {
case <-sigCh:
fmt.Println("Received termination signal. Cleaning up...")
cancel := make(chan struct{})
close(cancel)
client.Unsubscribe(eventCh)
close(eventCh)
client.EventService().Close()
wg.Wait()
fmt.Println("Cleanup completed. Exiting.")
}
}