This repository was archived by the owner on Sep 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathutils.go
356 lines (319 loc) · 8.24 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package models
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/mohae/deepcopy"
"github.com/VictorLowther/jsonpatch2"
yaml "github.com/ghodss/yaml"
)
var (
baseModels = func() map[string]reflect.Type {
res := map[string]reflect.Type{}
for _, m := range All() {
vv := reflect.ValueOf(m)
for vv.Kind() == reflect.Interface || vv.Kind() == reflect.Ptr {
vv = vv.Elem()
}
res[m.Prefix()] = vv.Type()
}
return res
}()
)
func copyMap(m map[string]interface{}) map[string]interface{} {
res := map[string]interface{}{}
for k, v := range m {
res[k] = v
}
return res
}
// BlobInfo contains information on an uploaded file or ISO.
// swagger:model
type BlobInfo struct {
Path string
Size int64
}
// Model is the interface that pretty much all non-Error objects
// returned by the API satisfy.
type Model interface {
Prefix() string
Key() string
KeyName() string
}
// Filler interface defines if a model can be filled/initialized
type Filler interface {
Model
Fill()
}
// Slicer interface defines is a model can be operated on as slices
type Slicer interface {
Filler
SliceOf() interface{}
ToModels(interface{}) []Model
}
// All returns a slice containing a single blank instance of all the
// Models.
func All() []Model {
return []Model{
&BootEnv{},
&Interface{},
&Job{},
&Lease{},
&Context{},
&Machine{},
&Param{},
&PluginProvider{},
&Plugin{},
&Pref{},
&Profile{},
&Reservation{},
&Role{},
&Stage{},
&Subnet{},
&Task{},
&Template{},
&User{},
&Workflow{},
&Tenant{},
&Pool{},
&Endpoint{},
&VersionSet{},
&CatalogItem{},
}
}
// AllPrefixes returns a slice containing the prefix names of all the
// Models.
func AllPrefixes() []string {
all := All()
res := make([]string, len(all))
for i := range all {
res[i] = all[i].Prefix()
}
return res
}
// New returns a new blank instance of the Model with the passed-in
// prefix.
func New(prefix string) (Slicer, error) {
var res Slicer
if v, ok := baseModels[prefix]; ok {
res = reflect.New(v).Interface().(Slicer)
} else if v, ok = baseModels[strings.TrimSuffix(prefix, "s")]; ok {
res = reflect.New(v).Interface().(Slicer)
} else {
res = &RawModel{"Type": prefix}
}
res.Fill()
return res, nil
}
// Clone returns a deep copy of the passed-in Model
func Clone(m Model) Model {
if m == nil {
return nil
}
return deepcopy.Copy(m).(Model)
}
var (
validMachineName = regexp.MustCompile(`^(\pL|\pN)+([- _.]+|\pN+|\pL+)+$`)
validEndpointName = regexp.MustCompile(`^(\pL|\pN)+([- _.:]+|\pN+|\pL+)+$`)
validName = regexp.MustCompile(`^\pL+([- _.]+|\pN+|\pL+)+$`)
validUserName = regexp.MustCompile(`^\pL+([- @_.]+|\pN+|\pL+)+$`)
validParamName = regexp.MustCompile(`^\pL+([- _./]+|\pN+|\pL+)+$`)
validNumberName = validMachineName
)
func validMatch(msg, s string, re *regexp.Regexp) error {
if re.MatchString(s) {
return nil
}
return fmt.Errorf("%s `%s`", msg, s)
}
// ValidMachineName validates that the string is a valid Machine Name
func ValidMachineName(msg, s string) error {
return validMatch(msg, s, validMachineName)
}
// ValidEndpointName validates that the string is a valid Endpoint Name
func ValidEndpointName(msg, s string) error {
return validMatch(msg, s, validEndpointName)
}
func ValidNumberName(msg, s string) error {
return validMatch(msg, s, validNumberName)
}
// ValidName validates that the string is a valid Name
func ValidName(msg, s string) error {
return validMatch(msg, s, validName)
}
// ValidUserName validates that the string is a valid Username
func ValidUserName(msg, s string) error {
return validMatch(msg, s, validUserName)
}
// ValidParamName validates that the string is a valid Param Name
func ValidParamName(msg, s string) error {
return validMatch(msg, s, validParamName)
}
// NameSetter interface if the model can change names
type NameSetter interface {
Model
SetName(string)
}
// Paramer interface defines if the model has parameters
type Paramer interface {
Model
GetParams() map[string]interface{}
SetParams(map[string]interface{})
}
// Profiler interface defines if the model has profiles
type Profiler interface {
Model
GetProfiles() []string
SetProfiles([]string)
}
// BootEnver interface defines if the model has a boot env
type BootEnver interface {
Model
GetBootEnv() string
SetBootEnv(string)
}
// Tasker interface defines if the model has a task list
type Tasker interface {
Model
GetTasks() []string
SetTasks([]string)
}
// TaskRunner interface defines if the object can run tasks
type TaskRunner interface {
Tasker
RunningTask() int
}
// Docer interface defines if the object has a documentation field
type Docer interface {
Model
GetDocumentation() string
}
// Descer interface defines if the object has a description field
type Descer interface {
Model
GetDescription() string
}
// Actor interface should be implemented this if you want actions
type Actor interface {
Model
CanHaveActions() bool
}
// FibBackoff takes function and retries it in a fibonacci backup sequence
func FibBackoff(thunk func() error) {
timeouts := []time.Duration{
time.Second,
time.Second,
2 * time.Second,
3 * time.Second,
5 * time.Second,
8 * time.Second,
}
for _, d := range timeouts {
if thunk() == nil {
return
}
time.Sleep(d)
}
}
// GenPatch generates a JSON patch that will transform source into target.
// The generated patch will have all the applicable test clauses.
func GenPatch(source, target interface{}, paranoid bool) (jsonpatch2.Patch, error) {
srcBuf, err := json.Marshal(source)
if err != nil {
return nil, err
}
tgtBuf, err := json.Marshal(target)
if err != nil {
return nil, err
}
return jsonpatch2.GenerateFull(srcBuf, tgtBuf, true, paranoid)
}
// DecodeYaml is a helper function for dealing with user input -- when
// accepting input from the user, we want to treat both YAML and JSON
// as first-class citizens. The YAML library we use makes that easier
// by using the json struct tags for all marshalling and unmarshalling
// purposes.
//
// Note that the REST API does not use YAML as a wire protocol, so
// this function should never be used to decode data coming from the
// provision service.
func DecodeYaml(buf []byte, ref interface{}) error {
return yaml.Unmarshal(buf, ref)
}
// Remarshal remarshals src onto dest.
func Remarshal(src, dest interface{}) error {
buf, err := json.Marshal(src)
if err == nil {
err = json.Unmarshal(buf, dest)
}
return err
}
// RandString returns a random string of n characters
// The range of characters is limited to the base64 set
func RandString(n int) string {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
fmt.Printf("Failed to read random\n")
return "ARGH!"
}
base64 := base64.URLEncoding.EncodeToString(b)
return base64[:n]
}
var (
unitMap = map[string]time.Duration{
"ns": time.Nanosecond,
"us": time.Microsecond,
"µs": time.Microsecond, // U+00B5 = micro symbol
"μs": time.Microsecond, // U+03BC = Greek letter mu
"ms": time.Millisecond,
"s": time.Second,
"m": time.Minute,
"h": time.Hour,
`d`: time.Hour * 24,
`w`: time.Hour * 24 * 7,
`mo`: time.Hour * 24 * 30,
`y`: time.Hour * 24 * 365,
}
lengthRE = regexp.MustCompile(`^([.0-9]+)`)
durationRE = regexp.MustCompile(`[.0-9]+\s?((mo|(n|u|m|µ|μ)?s|m|h|d|w|y)?[a-z]*)$`)
)
func ParseDuration(s, unit string) (time.Duration, error) {
if s == "never" {
// never = 100 years, more or less
return time.Hour * 24 * 365 * 100, nil
}
parts := lengthRE.FindStringSubmatch(s)
if parts == nil || len(parts) != 2 || parts[1] == "" {
return 0, fmt.Errorf("Invalid duration '%s': number not valid", s)
}
length, err := strconv.ParseFloat(parts[1], 64)
if err != nil {
return 0, fmt.Errorf("Invalid duration '%s': number not valid", s)
}
parts = durationRE.FindStringSubmatch(s)
switch len(parts) {
case 3:
if parts[2] != "" {
unit = parts[2]
break
}
fallthrough
case 2:
if parts[1] != "" {
unit = parts[1]
break
}
}
duration, ok := unitMap[unit]
if !ok {
return 0, fmt.Errorf("Invalid duration '%s': unit must be [ns] nanoseconds, [us] microseconds, [ms] milliseconds, [s]seconds, [m]inutes, [h]ours, [d]ays, [w]eeks, [mo]nths, [y]ears, or never", s)
}
return time.Duration(int64(length * float64(duration))), nil
}