-
Notifications
You must be signed in to change notification settings - Fork 159
/
utils.go
293 lines (255 loc) · 7.48 KB
/
utils.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Copyright (C) 2017 ScyllaDB
package mermaidclient
import (
"fmt"
"io"
"math"
"net/url"
"path"
"regexp"
"strconv"
"strings"
"time"
"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
"github.com/scylladb/scylla-operator/pkg/util/duration"
"github.com/scylladb/scylla-operator/pkg/util/timeutc"
"github.com/scylladb/scylla-operator/pkg/util/uuid"
)
const (
nowSafety = 30 * time.Second
rfc822WithSec = "02 Jan 06 15:04:05 MST"
)
// TaskSplit attempts to split a string into type and id.
func TaskSplit(s string) (taskType string, taskID uuid.UUID, err error) {
i := strings.LastIndex(s, "/")
if i != -1 {
taskType = s[:i]
}
taskID, err = uuid.Parse(s[i+1:])
return
}
// TaskJoin creates a new type id string in the form `taskType/taskId`.
func TaskJoin(taskType string, taskID interface{}) string {
return fmt.Sprint(taskType, "/", taskID)
}
// ParseStartDate parses the supplied string as a strfmt.DateTime.
func ParseStartDate(value string) (strfmt.DateTime, error) {
now := timeutc.Now()
if value == "now" {
return strfmt.DateTime(now.Add(nowSafety)), nil
}
if strings.HasPrefix(value, "now") {
d, err := duration.ParseDuration(value[3:])
if err != nil {
return strfmt.DateTime{}, err
}
if d < 0 {
return strfmt.DateTime(time.Time{}), errors.New("start date cannot be in the past")
}
if d.Duration() < nowSafety {
return strfmt.DateTime(time.Time{}), errors.Errorf("start date must be at least in %s", nowSafety)
}
return strfmt.DateTime(now.Add(d.Duration())), nil
}
// No more heuristics, assume the user passed a date formatted string
t, err := timeutc.Parse(time.RFC3339, value)
if err != nil {
return strfmt.DateTime(t), err
}
if t.Before(now) {
return strfmt.DateTime(time.Time{}), errors.New("start date cannot be in the past")
}
if t.Before(now.Add(nowSafety)) {
return strfmt.DateTime(time.Time{}), errors.Errorf("start date must be at least in %s", nowSafety)
}
return strfmt.DateTime(t), nil
}
// ParseDate parses the supplied string as a strfmt.DateTime.
func ParseDate(value string) (strfmt.DateTime, error) {
now := timeutc.Now()
if value == "now" {
return strfmt.DateTime(now), nil
}
if strings.HasPrefix(value, "now") {
d, err := duration.ParseDuration(value[3:])
if err != nil {
return strfmt.DateTime{}, err
}
return strfmt.DateTime(now.Add(d.Duration())), nil
}
// No more heuristics, assume the user passed a date formatted string
t, err := timeutc.Parse(time.RFC3339, value)
if err != nil {
return strfmt.DateTime(t), err
}
return strfmt.DateTime(t), nil
}
func uuidFromLocation(location string) (uuid.UUID, error) {
l, err := url.Parse(location)
if err != nil {
return uuid.Nil, err
}
_, id := path.Split(l.Path)
return uuid.Parse(id)
}
// FormatProgress creates complete vs. failed representation.
func FormatProgress(complete, failed float32) string {
if failed == 0 {
return FormatPercent(complete)
}
return FormatPercent(complete) + " / " + FormatPercent(failed)
}
// FormatPercent simply creates a percent representation of the supplied value.
func FormatPercent(p float32) string {
return fmt.Sprintf("%0.2f%%", p)
}
// FormatUploadProgress calculates percentage of success and failed uploads
func FormatUploadProgress(size, uploaded, skipped, failed int64) string {
if size == 0 {
return "100%"
}
transferred := uploaded + skipped
out := fmt.Sprintf("%d%%",
transferred*100/size,
)
if failed > 0 {
out += fmt.Sprintf("/%d%%", failed*100/size)
}
return out
}
// ByteCountBinary returns string representation of the byte count with proper
// unit appended if withUnit is true.
func ByteCountBinary(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%dB", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
// One decimal by default, two decimals for GiB and three for more than
// that.
format := "%.0f%ciB"
if exp == 2 {
format = "%.2f%ciB"
} else if exp > 2 {
format = "%.3f%ciB"
}
return fmt.Sprintf(format, float64(b)/float64(div), "KMGTPE"[exp])
}
// FormatTime formats the supplied DateTime in `02 Jan 06 15:04:05 MST` format.
func FormatTime(t strfmt.DateTime) string {
if isZero(t) {
return ""
}
return time.Time(t).Local().Format(rfc822WithSec)
}
// FormatDuration creates and formats the duration between
// the supplied DateTime values.
func FormatDuration(t0, t1 strfmt.DateTime) string {
if isZero(t0) && isZero(t1) {
return "0s"
}
var d time.Duration
if isZero(t1) {
d = timeutc.Now().Sub(time.Time(t0))
} else {
d = time.Time(t1).Sub(time.Time(t0))
}
return fmt.Sprint(d.Truncate(time.Second))
}
func isZero(t strfmt.DateTime) bool {
return time.Time(t).IsZero()
}
// FormatError formats messages created by using multierror with
// errors wrapped with host IP so that each host error is in it's own line.
// It also adds "failed to" prefix if needed.
func FormatError(msg string) string {
const prefix = " "
// Fairly relaxed IPv4 and IPv6 heuristic pattern, a proper pattern can
// be very complex
const ipRegex = `([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}|(\d{1,3}\.){3}\d{1,3}`
// Move host errors to newline
r := regexp.MustCompile(`(^|: |; )(` + ipRegex + `): `)
msg = r.ReplaceAllString(msg, "\n"+prefix+"${2}: ")
// Add "failed to" prefix if needed
if !strings.HasPrefix(msg, "failed to") && !strings.HasPrefix(msg, "\n") {
msg = "failed to " + msg
}
return msg
}
// FormatTables returns tables listing if number of tables is lower than
// threshold. It prints (n tables) or (table_a, table_b, ...).
func FormatTables(threshold int, tables []string, all bool) string {
var out string
if len(tables) == 0 || threshold == 0 || (threshold > 0 && len(tables) > threshold) {
if len(tables) == 1 {
out = "(1 table)"
} else {
out = fmt.Sprintf("(%d tables)", len(tables))
}
}
if out == "" {
out = "(" + strings.Join(tables, ", ") + ")"
}
if all {
out = "all " + out
}
return out
}
// FormatClusterName writes cluster name and id to the writer.
func FormatClusterName(w io.Writer, c *Cluster) {
fmt.Fprintf(w, "Cluster: %s (%s)\n", c.Name, c.ID)
}
// StringByteCount returns string representation of the byte count with proper
// unit.
func StringByteCount(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%dB", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
// No decimals by default, two decimals for GiB and three for more than
// that.
format := "%.0f%ciB"
if exp == 2 {
format = "%.2f%ciB"
} else if exp > 2 {
format = "%.3f%ciB"
}
return fmt.Sprintf(format, float64(b)/float64(div), "KMGTPE"[exp])
}
var (
byteCountRe = regexp.MustCompile(`([0-9]+(?:\.[0-9]+)?)(B|[KMGTPE]iB)`)
byteCountReValueIdx = 1
byteCountReSuffixIdx = 2
)
// ParseByteCount returns byte count parsed from input string.
// This is opposite of StringByteCount function.
func ParseByteCount(s string) (int64, error) {
const unit = 1024
var exps = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
parts := byteCountRe.FindStringSubmatch(s)
if len(parts) != 3 {
return 0, errors.Errorf("invalid byte size string: %q; it must be real number with unit suffix: %s", s, strings.Join(exps, ","))
}
v, err := strconv.ParseFloat(parts[byteCountReValueIdx], 64)
if err != nil {
return 0, errors.Wrapf(err, "parsing value for byte size string: %s", s)
}
pow := 0
for i, e := range exps {
if e == parts[byteCountReSuffixIdx] {
pow = i
}
}
mul := math.Pow(unit, float64(pow))
return int64(v * mul), nil
}