forked from HDT3213/rdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.go
73 lines (69 loc) · 1.82 KB
/
memory.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
package helper
import (
"encoding/csv"
"errors"
"fmt"
"github.com/vkill-w/go-rdb-tool/bytefmt"
"github.com/vkill-w/go-rdb-tool/core"
"github.com/vkill-w/go-rdb-tool/model"
"os"
"strconv"
"time"
)
// MemoryProfile read rdb file and analysis memory usage then write result to csv file
func MemoryProfile(rdbFilename string, csvFilename string, options ...interface{}) error {
if rdbFilename == "" {
return errors.New("src file path is required")
}
if csvFilename == "" {
return errors.New("output file path is required")
}
rdbFile, err := os.Open(rdbFilename)
if err != nil {
return fmt.Errorf("open rdb %s failed, %v", rdbFilename, err)
}
defer func() {
_ = rdbFile.Close()
}()
csvFile, err := os.Create(csvFilename)
if err != nil {
return fmt.Errorf("create json %s failed, %v", csvFilename, err)
}
defer func() {
_ = csvFile.Close()
}()
var dec decoder = core.NewDecoder(rdbFile)
if dec, err = wrapDecoder(dec, options...); err != nil {
return err
}
_, err = csvFile.WriteString("database,key,type,size,size_readable,element_count,encoding,expiration\n")
if err != nil {
return fmt.Errorf("write csv failed: %v", err)
}
csvWriter := csv.NewWriter(csvFile)
defer csvWriter.Flush()
formatExpiration := func(o model.RedisObject) string {
expiration := o.GetExpiration()
if expiration == nil {
return ""
}
return expiration.Format(time.RFC3339)
}
return dec.Parse(func(object model.RedisObject) bool {
err = csvWriter.Write([]string{
strconv.Itoa(object.GetDBIndex()),
object.GetKey(),
object.GetType(),
strconv.Itoa(object.GetSize()),
bytefmt.FormatSize(uint64(object.GetSize())),
strconv.Itoa(object.GetElemCount()),
object.GetEncoding(),
formatExpiration(object),
})
if err != nil {
fmt.Printf("csv write failed: %v", err)
return false
}
return true
})
}