-
Notifications
You must be signed in to change notification settings - Fork 55
/
metrics.go
90 lines (78 loc) · 2.27 KB
/
metrics.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Copyright (C) 2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package metrics
import (
"crypto/sha256"
"encoding/base64"
"fmt"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"github.com/ava-labs/avalanche-cli/pkg/application"
"github.com/ava-labs/avalanche-cli/pkg/constants"
"github.com/ava-labs/avalanche-cli/pkg/utils"
"github.com/posthog/posthog-go"
"github.com/spf13/cobra"
)
// telemetryToken value is set at build and install scripts using ldflags
var (
telemetryToken = ""
telemetryInstance = "https://app.posthog.com"
)
func GetCLIVersion() string {
wdPath, err := os.Getwd()
if err != nil {
return ""
}
versionPath := filepath.Join(wdPath, "VERSION")
content, err := os.ReadFile(versionPath)
if err != nil {
return ""
}
return string(content)
}
func userIsOptedIn(app *application.Avalanche) bool {
if app.Conf.ConfigFileExists() && app.Conf.GetConfigBoolValue(constants.ConfigMetricsEnabledKey) {
return true
}
return false
}
func HandleTracking(cmd *cobra.Command, commandPath string, app *application.Avalanche, flags map[string]string) {
if !userIsOptedIn(app) {
return
}
if !cmd.HasSubCommands() && CheckCommandIsNotCompletion(cmd) {
TrackMetrics(commandPath, flags)
}
}
func CheckCommandIsNotCompletion(cmd *cobra.Command) bool {
result := strings.Fields(cmd.CommandPath())
if len(result) >= 2 && result[1] == "completion" {
return false
}
return true
}
func TrackMetrics(commandPath string, flags map[string]string) {
if telemetryToken == "" || utils.IsE2E() {
return
}
client, _ := posthog.NewWithConfig(telemetryToken, posthog.Config{Endpoint: telemetryInstance})
defer client.Close()
usr, _ := user.Current() // use empty string if err
hash := sha256.Sum256([]byte(fmt.Sprintf("%s%s", usr.Username, usr.Uid)))
userID := base64.StdEncoding.EncodeToString(hash[:])
telemetryProperties := make(map[string]interface{})
telemetryProperties["command"] = commandPath
telemetryProperties["version"] = GetCLIVersion()
telemetryProperties["os"] = runtime.GOOS
for propertyKey, propertyValue := range flags {
telemetryProperties[propertyKey] = propertyValue
}
_ = client.Enqueue(posthog.Capture{
DistinctId: userID,
Event: "cli-command",
Properties: telemetryProperties,
})
}