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
|
package main
import (
"context"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
dbName string = "test"
colName string = "pids"
)
func deal() {
defer wg.Done()
var cooked Event
var ok bool
var err error
var mongo *mongo.Client
var res []bson.M
mongo, err = connect()
if err != nil {
fmt.Printf("Err connecting the mongodb: %v\n", err)
}
pidCol := mongo.Database(dbName).Collection(colName)
err = pidCol.Drop(context.Background())
if err != nil {
fmt.Printf("Err drop: %v\n", err)
}
_, err = pidCol.InsertOne(context.Background(), bson.M{
"ppid": 1,
"pid": containerdPid,
"cwd": "/",
})
if err != nil {
fmt.Printf("Err containerd: %v", err)
return
}
fmt.Printf("Containerd: %d\n", containerdPid)
for {
cooked, ok = <-cookedChan
if !ok {
break
}
switch syscallTable[cooked.syscall] {
case "fork", "vfork", "clone":
// 有无父进程在观察中
res, err = findDocuments(mongo, "test", "pids", bson.M{"pid": cooked.ppid})
if err != nil || len(res) != 1 {
break
}
// 自身是否已经记录
res, err = findDocuments(mongo, "test", "pids", bson.M{"pid": cooked.pid})
if err != nil {
fmt.Printf("Err finding: %v\n", err)
break
} else if len(res) != 0 {
fmt.Printf("Err inserting pid %v: already in db: %v\n", cooked.pid, res)
break
}
doc := []bson.A{}
for _, str := range cooked.argv {
doc = append(doc, bson.A{str})
}
_, err := pidCol.InsertOne(context.Background(), bson.M{
"timestamp": cooked.timestamp,
"ppid": cooked.ppid,
"pid": cooked.pid,
"cwd": cooked.cwd,
"args": doc,
"children": []bson.M{},
})
if err != nil {
fmt.Printf("Err insert: %v\n", err)
}
_, err = pidCol.UpdateOne(context.Background(), bson.M{"pid": cooked.pid}, bson.M{
"$push": bson.M{
"children": cooked.pid,
},
})
if err != nil {
fmt.Printf("Err insert: %v\n", err)
}
case "exit", "exit_group":
// TODO: 记得补全退出逻辑
// 上哪找exit code呢?
}
}
}
func connect() (*mongo.Client, error) {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
return nil, err
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
return nil, err
}
return client, nil
}
func findDocuments(client *mongo.Client, dbName, colName string, filter bson.M) ([]bson.M, error) {
collection := client.Database(dbName).Collection(colName)
cur, err := collection.Find(context.Background(), filter)
if err != nil {
return nil, err
}
var results []bson.M
err = cur.All(context.Background(), &results)
return results, err
}
|