File: telemetry.go

package info (click to toggle)
golang-github-crc-org-crc 2.34.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,548 kB
  • sloc: sh: 398; makefile: 326; javascript: 40
file content (100 lines) | stat: -rw-r--r-- 2,258 bytes parent folder | download
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
package telemetry

import (
	"context"
	"os/user"
	"strings"
	"sync"

	"github.com/crc-org/crc/v2/pkg/crc/constants"
)

type contextKey struct{}

var key = contextKey{}

type Properties struct {
	lock    sync.Mutex
	storage map[string]interface{}
}

func (p *Properties) set(name string, value interface{}) {
	p.lock.Lock()
	defer p.lock.Unlock()
	p.storage[name] = value
}

func (p *Properties) values() map[string]interface{} {
	p.lock.Lock()
	defer p.lock.Unlock()
	ret := make(map[string]interface{})
	for k, v := range p.storage {
		ret[k] = v
	}
	return ret
}

func propertiesFromContext(ctx context.Context) *Properties {
	value := ctx.Value(key)
	if cast, ok := value.(*Properties); ok {
		return cast
	}
	return nil
}

func NewContext(ctx context.Context) context.Context {
	return context.WithValue(ctx, key, &Properties{storage: make(map[string]interface{})})
}

func GetContextProperties(ctx context.Context) map[string]interface{} {
	properties := propertiesFromContext(ctx)
	if properties == nil {
		return make(map[string]interface{})
	}
	return properties.values()
}

func setContextProperty(ctx context.Context, key string, value interface{}) {
	properties := propertiesFromContext(ctx)
	if properties != nil {
		properties.set(key, value)
	}
}

func SetCPUs(ctx context.Context, value int) {
	setContextProperty(ctx, "cpus", value)
}

func SetMemory(ctx context.Context, value uint64) {
	setContextProperty(ctx, "memory", value)
}

func SetDiskSize(ctx context.Context, value uint64) {
	setContextProperty(ctx, "disk-size", value)
}

func SetConfigurationKey(ctx context.Context, value string) {
	setContextProperty(ctx, "key", value)
}

func SetStartType(ctx context.Context, value StartType) {
	setContextProperty(ctx, "start-type", value)
}

type StartType string

const (
	AlreadyRunningStartType StartType = "already-running"
	CreationStartType       StartType = "creation"
	StartStartType          StartType = "start"
)

func SetError(err error) string {
	// Mask username if present in the error string
	user, err1 := user.Current()
	if err1 != nil {
		return err1.Error()
	}
	withoutHomeDir := strings.ReplaceAll(err.Error(), constants.GetHomeDir(), "$HOME")
	return strings.ReplaceAll(withoutHomeDir, user.Username, "$USERNAME")
}