-
Notifications
You must be signed in to change notification settings - Fork 312
/
meta.go
101 lines (83 loc) · 2.17 KB
/
meta.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
91
92
93
94
95
96
97
98
99
100
101
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package telemetry
import (
"io/ioutil"
"os"
"path/filepath"
"github.com/google/uuid"
"github.com/pingcap/errors"
"github.com/pingcap/tiup/pkg/environment"
"github.com/pingcap/tiup/pkg/localdata"
"gopkg.in/yaml.v2"
)
const telemetryFname = "meta.yaml"
// Status of telemetry.
type Status string
// Status of telemetry
const (
EnableStatus Status = "enable"
DisableStatus Status = "disable"
)
const defaultStatus = EnableStatus
// Meta data of telemetry.
type Meta struct {
UUID string `yaml:"uuid,omitempty"`
Status Status `yaml:"status,omitempty"`
}
// NewUUID return a new uuid.
func NewUUID() string {
return uuid.New().String()
}
// NewMeta create a new default Meta.
func NewMeta() *Meta {
return &Meta{
UUID: NewUUID(),
Status: EnableStatus,
}
}
// LoadFrom load meta from the specify file,
// return a default Meta and save it if the file not exist.
func LoadFrom(fname string) (meta *Meta, err error) {
var data []byte
data, err = ioutil.ReadFile(fname)
if err != nil {
if os.IsNotExist(err) {
meta = NewMeta()
return meta, meta.SaveTo(fname)
}
return
}
meta = new(Meta)
err = yaml.Unmarshal(data, meta)
return
}
// SaveTo save to the specified file.
func (m *Meta) SaveTo(fname string) error {
data, err := yaml.Marshal(m)
if err != nil {
return errors.AddStack(err)
}
return ioutil.WriteFile(fname, data, 0644)
}
// GetMeta read the telemeta from disk
func GetMeta(env *environment.Environment) (meta *Meta, fname string, err error) {
dir := env.Profile().Path(localdata.TelemetryDir)
err = os.MkdirAll(dir, 0755)
if err != nil {
return
}
fname = filepath.Join(dir, telemetryFname)
meta, err = LoadFrom(fname)
return
}