-
Notifications
You must be signed in to change notification settings - Fork 305
/
history.go
261 lines (225 loc) · 5.71 KB
/
history.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Copyright 2022 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 environment
import (
"bufio"
"encoding/json"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"github.com/pingcap/tiup/pkg/tui"
"github.com/pingcap/tiup/pkg/utils"
"github.com/pkg/errors"
)
const (
// HistoryDir history save path
HistoryDir = "history"
historyPrefix = "tiup-history-"
historySize int64 = 1024 * 64 // history file default size is 64k
)
// commandRow type of command history row
type historyRow struct {
Date time.Time `json:"time"`
Command string `json:"command"`
Code int `json:"exit_code"`
}
// historyItem record history row file item
type historyItem struct {
path string
info fs.FileInfo
index int
}
// HistoryRecord record tiup exec cmd
func HistoryRecord(env *Environment, command []string, date time.Time, code int) error {
if env == nil {
return nil
}
historyPath := env.LocalPath(HistoryDir)
if utils.IsNotExist(historyPath) {
err := utils.MkdirAll(historyPath, 0755)
if err != nil {
return err
}
}
h := &historyRow{
Command: strings.Join(HidePassword(command), " "),
Date: date,
Code: code,
}
return h.save(historyPath)
}
// save save commandRow to file
func (r *historyRow) save(dir string) error {
rBytes, err := json.Marshal(r)
if err != nil {
return err
}
historyFile := getLatestHistoryFile(dir)
f, err := os.OpenFile(historyFile.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write(append(rBytes, []byte("\n")...))
return err
}
// GetHistory get tiup history
func (env *Environment) GetHistory(count int, all bool) ([]*historyRow, error) {
fList, err := getHistoryFileList(env.LocalPath(HistoryDir))
if err != nil {
return nil, err
}
rows := []*historyRow{}
for _, f := range fList {
rs, err := f.getHistory()
if err != nil {
return rows, err
}
if (len(rows)+len(rs)) > count && !all {
i := len(rows) + len(rs) - count
rows = append(rs[i:], rows...)
break
}
rows = append(rs, rows...)
}
return rows, nil
}
// DeleteHistory delete history file
func (env *Environment) DeleteHistory(retainDays int, skipConfirm bool) error {
if retainDays < 0 {
return errors.Errorf("retainDays cannot be less than 0")
}
// history file before `DelBeforeTime` will be deleted
oneDayDuration, _ := time.ParseDuration("-24h")
delBeforeTime := time.Now().Add(oneDayDuration * time.Duration(retainDays))
if !skipConfirm {
fmt.Printf("History logs before %s will be %s!\n",
color.HiYellowString(delBeforeTime.Format("2006-01-02T15:04:05")),
color.HiYellowString("deleted"),
)
if err := tui.PromptForConfirmOrAbortError("Do you want to continue? [y/N]:"); err != nil {
return err
}
}
fList, err := getHistoryFileList(env.LocalPath(HistoryDir))
if err != nil {
return err
}
if len(fList) == 0 {
return nil
}
for _, f := range fList {
if f.info.ModTime().Before(delBeforeTime) {
err := os.Remove(f.path)
if err != nil {
return err
}
continue
}
}
return nil
}
// getHistory get tiup history execution row
func (i *historyItem) getHistory() ([]*historyRow, error) {
rows := []*historyRow{}
fi, err := os.Open(i.path)
if err != nil {
return rows, err
}
defer fi.Close()
br := bufio.NewReader(fi)
for {
a, _, c := br.ReadLine()
if c == io.EOF {
break
}
r := &historyRow{}
// ignore
err := json.Unmarshal(a, r)
if err != nil {
continue
}
rows = append(rows, r)
}
return rows, nil
}
// getHistoryFileList get the history file list
func getHistoryFileList(dir string) ([]historyItem, error) {
fileInfos, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
hfileList := []historyItem{}
for _, fi := range fileInfos {
if fi.IsDir() {
continue
}
// another suffix
// ex: tiup-history-0.bak
i, err := strconv.Atoi((strings.TrimPrefix(fi.Name(), historyPrefix)))
if err != nil {
continue
}
fInfo, _ := fi.Info()
hfileList = append(hfileList, historyItem{
path: filepath.Join(dir, fi.Name()),
index: i,
info: fInfo,
})
}
sort.Slice(hfileList, func(i, j int) bool {
return hfileList[i].index > hfileList[j].index
})
return hfileList, nil
}
// getLatestHistoryFile get the latest history file, use index 0 if it doesn't exist
func getLatestHistoryFile(dir string) (item historyItem) {
fileList, err := getHistoryFileList(dir)
// start from 0
if len(fileList) == 0 || err != nil {
item.index = 0
item.path = filepath.Join(dir, fmt.Sprintf("%s%s", historyPrefix, strconv.Itoa(item.index)))
return
}
latestItem := fileList[0]
if latestItem.info.Size() >= historySize {
item.index = latestItem.index + 1
item.path = filepath.Join(dir, fmt.Sprintf("%s%s", historyPrefix, strconv.Itoa(item.index)))
} else {
item = latestItem
}
return
}
// HidePassword replace password with ******
func HidePassword(args []string) []string {
var record []string
for i := 0; i < len(args); i++ {
arg := args[i]
if strings.HasPrefix(arg, "-p") && len(arg) > 2 {
record = append(record, "-p******")
} else if arg == "-p" && i+1 < len(args) {
record = append(record, "-p", "******")
i++ // skip next word that may be password
} else {
record = append(record, arg)
}
}
return record
}