forked from XTLS/libXray
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stats.go
75 lines (67 loc) · 1.72 KB
/
stats.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
package libXray
import (
"context"
"fmt"
"path"
"reflect"
"github.com/xtls/libxray/nodep"
statsService "github.com/xtls/xray-core/app/stats/command"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
func isNil(i interface{}) bool {
vi := reflect.ValueOf(i)
if vi.Kind() == reflect.Ptr {
return vi.IsNil()
}
return i == nil
}
func writeResult(m proto.Message, path string) error {
if isNil(m) {
return fmt.Errorf("m is nil")
}
ops := protojson.MarshalOptions{}
b, err := ops.Marshal(m)
if err != nil {
return err
}
err = nodep.WriteBytes(b, path)
return err
}
// query system stats and outbound stats.
// server means The API server address, like "127.0.0.1:8080".
// dir means the dir which result json will be wrote to.
func QueryStats(server string, dir string) string {
conn, err := grpc.Dial(server, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
if err != nil {
return err.Error()
}
defer conn.Close()
client := statsService.NewStatsServiceClient(conn)
sysStatsReq := &statsService.SysStatsRequest{}
sysStatsRes, err := client.GetSysStats(context.Background(), sysStatsReq)
if err != nil {
return err.Error()
}
sysStatsPath := path.Join(dir, "sysStats.json")
err = writeResult(sysStatsRes, sysStatsPath)
if err != nil {
return err.Error()
}
statsReq := &statsService.QueryStatsRequest{
Pattern: "",
Reset_: false,
}
statsRes, err := client.QueryStats(context.Background(), statsReq)
if err != nil {
return err.Error()
}
statsPath := path.Join(dir, "stats.json")
err = writeResult(statsRes, statsPath)
if err != nil {
return err.Error()
}
return ""
}