aboutsummaryrefslogtreecommitdiffstats
path: root/filter/filter.go
blob: b2341ec0df31fc67fb2420c5d919eee697087b24 (plain) (blame)
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
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"sort"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const (
	oldDBName      = "test"
	oldPidColName  = "pids"
	oldFdColName   = "fds"
	oldFileColName = "files"

	newDBName      = "cooked"
	newPidColName  = "tgids"
	newFileColName = "files"
)

// 进程树信息
var findTgid map[int]int
var helloTree map[int]*tgidNode

// 文件信息
var files []*File

func main() {
	// 连接到MongoDB
	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(context.TODO())

	oldDB := client.Database(oldDBName)

	/*
	 * Step 1: 进程数据处理
	 */
	oldPidCol := oldDB.Collection(oldPidColName)

	// 数据提取
	var rawPidData []Process
	cursor, err := oldPidCol.Find(context.Background(), bson.M{})
	if err != nil {
		fmt.Fprintf(os.Stderr, "Err: %v\n", err)
		return
	}
	err = cursor.All(context.Background(), &rawPidData)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Err All: %v\n", err)
		return
	}
	cursor.Close(context.Background())

	filtPids(&rawPidData)

	/*
	 * Step 2: 文件数据处理
	 * - 将已经关闭的和未关闭的同等看待
	 * - 未关闭的将关闭时间修改为对应进程退出时间
	 * - 值得注意的是,同一进程各线程共享文件描述符……需要处理吗?
	 */
	// 提取files和fds里的数据
	// TODO:是否可以只筛选被写过的记录?
	var rawFileData []File
	oldFileCol := oldDB.Collection(oldFileColName)
	cursor, err = oldFileCol.Find(context.Background(), bson.M{})
	if err != nil {
		fmt.Fprintf(os.Stderr, "Err: %v\n", err)
		return
	}
	err = cursor.All(context.Background(), &rawFileData)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Err All: %v\n", err)
		return
	}
	cursor.Close(context.Background())

	var rawFdData []File
	oldFdCol := oldDB.Collection(oldFdColName)
	cursor, err = oldFdCol.Find(context.Background(), bson.M{})
	if err != nil {
		fmt.Fprintf(os.Stderr, "Err: %v\n", err)
		return
	}
	err = cursor.All(context.Background(), &rawFdData)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Err All: %v\n", err)
		return
	}
	cursor.Close(context.Background())

	// 合并,处理
	rawFileData = append(rawFileData, rawFdData...)
	filtFiles(&rawFileData)

	// 扔回数据库
	newDB := client.Database(newDBName)
	newDB.Drop(context.Background())
	newPidCol := newDB.Collection(newPidColName)
	for _, pTgidNode := range helloTree {
		newPidCol.InsertOne(context.Background(), *pTgidNode)
	}

	newFileCol := newDB.Collection(newFileColName)
	for _, pFile := range files {
		newFileCol.InsertOne(context.Background(), *pFile)
	}
}

func ProMerge(a, b Process) (res Process) {
	// 合并过程中会遇到什么问题?
	res.Star = false

	if a.StartTimestamp.IsZero() {
		res.StartTimestamp = b.StartTimestamp
	} else if b.StartTimestamp.IsZero() {
		res.StartTimestamp = a.StartTimestamp
	} else if a.StartTimestamp.Before(b.StartTimestamp) {
		res.StartTimestamp = a.StartTimestamp
	} else {
		res.StartTimestamp = b.StartTimestamp
	}

	res.Ppid = a.Ppid
	if a.ParentTgid == 0 {
		res.ParentTgid = b.ParentTgid
	} else {
		res.ParentTgid = a.ParentTgid
	}

	res.Pid = a.Pid
	if a.Tgid == 0 {
		res.Tgid = b.Tgid
	} else {
		res.Tgid = a.Tgid
	}

	if len(a.Args) == 0 {
		res.Args = b.Args
	} else {
		res.Args = a.Args
	}

	if a.Comm == "" {
		res.Comm = b.Comm
	} else {
		res.Comm = a.Comm
	}

	if a.RootFS == "" {
		res.RootFS = b.RootFS
	} else {
		res.RootFS = a.RootFS
	}

	if a.Cwd == "" {
		res.Cwd = b.Cwd
	} else {
		res.Cwd = a.Cwd
	}

	res.Execve = append(a.Execve, b.Execve...)
	res.Children = append(a.Children, b.Children...)

	var flag bool // 真a假b
	if a.ExitTimestamp.IsZero() {
		flag = false
	} else if b.ExitTimestamp.IsZero() {
		flag = true
	} else if a.ExitTimestamp.Before(b.ExitTimestamp) {
		flag = true
	} else {
		flag = false
	}

	if flag {
		res.ExitCode = a.ExitCode
		res.ExitSignal = a.ExitSignal
		res.ExitTimestamp = a.ExitTimestamp
	} else {
		res.ExitCode = b.ExitCode
		res.ExitSignal = b.ExitSignal
		res.ExitTimestamp = b.ExitTimestamp
	}

	return res
}

func filtPids(pRawPidData *[]Process) {
	rawPidData := *pRawPidData
	// 合并由多线程导致的重复记录
	merged := make(map[int]Process) // pid --> Process
	for _, process := range rawPidData {
		tmp, exists := merged[process.Pid]
		if exists {
			// 证明重复了,要合并
			merged[process.Pid] = ProMerge(tmp, process)
		} else {
			// 没有,直接插入
			merged[process.Pid] = process
		}
	}

	// 合并出来的进程整理为tgidNode
	// var tgidMap map[int]*tgidNode // tgid --> tgidNode
	tgidMap := make(map[int]*tgidNode)
	findTgid = make(map[int]int) // pid --> tgid
	var stared int
	stared = -1
	for _, val := range merged {
		if val.Star {
			stared = val.Tgid
		}
		// 登记tgid
		findTgid[val.Pid] = val.Tgid
		// nodeval, ok := tgidMap.Load(val.Tgid)
		nodeval, exists := tgidMap[val.Tgid]
		if exists {
			// 直接记录
			// node := nodeval.(tgidNode)
			nodeval.Threads = append(nodeval.Threads, val)
			nodeval.FindPid[val.Pid] = len(nodeval.Threads) - 1
			// tgidMap.Store(val.Tgid, node)
		} else {
			node := tgidNode{
				Tgid:      val.Tgid,
				FindPid:   make(map[int]int),
				Threads:   make([]Process, 0),
				ChildTgid: make([]int, 0),
			}
			node.Threads = append(node.Threads, val)
			node.FindPid[val.Pid] = 0
			// tgidMap.Store(val.Tgid, node)
			tgidMap[val.Tgid] = &node
		}
	}

	// 从tgid==stared开始,构建树
	helloTree = make(map[int]*tgidNode) // 在树上的tgid节点,tgid --> *tgidNode
	var q Queue                         // 记录每一个整理好的结构体,bfs
	visited := make(map[int]bool)       // 哪些tgid已经访问过

	// tmp, ok := tgidMap.Load(stared)
	// if !ok {
	// 	return
	// }
	tmp, exists := tgidMap[stared]
	if !exists {
		return
	}

	// helloTree负责在遍历到该节点时记录
	// 队列仅负责搞明白哪些节点在树上
	// 因而所有添加子代tgid的行为只针对helloTree
	// q不添加,直接把新的tgid对应的tgidNode入队就是了
	q.Enqueue(tmp)
	visited[stared] = true
	for !q.IsEmpty() {
		tmp, ok := q.Dequeue()
		if !ok {
			continue
		}
		node := tmp.(*tgidNode) // 队列里的一个节点,这里必须重新申请node
		helloTree[node.Tgid] = node
		for i := 0; i < len(node.Threads); i++ {
			for j := 0; j < len(node.Threads[i].Children); j++ {
				tgid := findTgid[node.Threads[i].Children[j]]
				_, exists := visited[tgid]
				if !exists {
					// 子代里有没见过的tgid
					// tgidNode, ok := tgidMap.Load(tgid)
					tgidNode, exists := tgidMap[tgid]
					if !exists {
						continue
					}
					helloTree[node.Tgid].ChildTgid = append(helloTree[node.Tgid].ChildTgid, tgid)
					q.Enqueue(tgidNode)
					visited[tgid] = true
				}
			}
		}
	}

	// TODO:
	// 1.√修改数据结构,使之自身即存储树结构,插入数据库后前端拿出来就能用
	// 2.还有其余优化要做,比如线程退出时间与进程推出时间,关系到后续的文件修理
	// 3.根文件系统,问题很重大

	count := 0
	for _, val := range helloTree {
		count++
		fmt.Printf("==============================\ntgid: %6d, size: %6d, children: ", val.Tgid, len(val.Threads))
		for _, child := range val.ChildTgid {
			fmt.Printf("%7d", child)
		}
		fmt.Printf("\n")
		for _, process := range val.Threads {
			fmt.Printf("%v\n", process)
		}
		fmt.Printf("\n\n\n")
	}
	fmt.Printf("Star: %d, res: %d\n", stared, count)
}

func filtFiles(pRawFileData *[]File) {
	rawFileData := *pRawFileData
	files = make([]*File, 0)

	// 所有文件按照特定顺序排
	sort.Slice(rawFileData, func(i, j int) bool {
		pi := &rawFileData[i]
		pj := &rawFileData[j]

		if pi.FileName < pj.FileName {
			return true
		} else if pi.FileName > pj.FileName {
			return false
		}
		if pi.Pid < pj.Pid {
			return true
		} else if pi.Pid > pj.Pid {
			return false
		}
		if pi.Fd < pj.Fd {
			return true
		} else if pi.Fd > pj.Fd {
			return false
		}
		if pi.OpenTimestamp.Before(pj.OpenTimestamp) {
			return true
		} else {
			return false
		}
	})

	for _, file := range rawFileData {
		tgid := findTgid[file.Pid]
		pTgidNode, exists := helloTree[tgid]
		if !exists {
			continue
		}
		if file.CloseTimestamp.IsZero() {
			index, exists := pTgidNode.FindPid[file.Pid]
			if !exists || index < 0 || index >= len(pTgidNode.Threads) {
				continue
			}
			file.CloseTimestamp = pTgidNode.Threads[index].ExitTimestamp
		}
		files = append(files, &file)
	}
}