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 }