-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
116 lines (97 loc) · 2.76 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
package main
import (
"encoding/json"
"os"
"fmt"
"errors"
"strings"
"time"
"math/rand"
"strconv"
"path/filepath"
)
type globalConfiguration struct {
Registry string
Administrators []string
Locks pathLocks
}
func newGlobalConfiguration(registry string) globalConfiguration {
return globalConfiguration{
Registry: registry,
Administrators: []string{},
Locks: newPathLocks(),
}
}
type httpError struct {
Status int
Reason error
}
func (r *httpError) Error() string {
return r.Reason.Error()
}
func (r *httpError) Unwrap() error {
return r.Reason
}
func newHttpError(status int, reason error) *httpError {
return &httpError{ Status: status, Reason: reason }
}
func dumpJson(path string, content interface{}) error {
// Using the save-and-rename paradigm to avoid clients picking up partial writes.
temp, err := os.CreateTemp(filepath.Dir(path), ".temp*.json")
if err != nil {
return fmt.Errorf("failed to create temporary file when saving %q; %w", path, err)
}
is_closed := false
defer func() {
if !is_closed {
temp.Close()
}
}()
err = os.Chmod(temp.Name(), 0644)
if err != nil {
return fmt.Errorf("failed to set temporary file permissions when saving %q; %w", path, err);
}
as_str, err := json.MarshalIndent(content, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal JSON to save to %q; %w", path, err)
}
_, err = temp.Write(as_str)
if err != nil {
return fmt.Errorf("failed to write JSON to temporary file for %q; %w", path, err)
}
temp_name := temp.Name()
is_closed = true
err = temp.Close()
if err != nil {
return fmt.Errorf("failed to close temporary file when saving to %q; %w", path, err)
}
err = os.Rename(temp_name, path)
if err != nil {
return fmt.Errorf("failed to rename temporary file to %q; %w", path, err)
}
return nil
}
func isBadName(name string) error {
if len(name) == 0 {
return errors.New("name cannot be empty")
}
if strings.Contains(name, "/") || strings.Contains(name, "\\") {
return errors.New("name cannot contain '/' or '\\'")
}
if strings.HasPrefix(name, "..") {
return errors.New("name cannot start with '..'")
}
return nil
}
func isMissingOrBadName(name *string) error {
if name == nil {
return errors.New("missing name")
} else {
return isBadName(*name)
}
}
const logDirName = "..logs"
func dumpLog(registry string, content interface{}) error {
path := time.Now().Format(time.RFC3339) + "_" + strconv.Itoa(100000 + rand.Intn(900000))
return dumpJson(filepath.Join(registry, logDirName, path), content)
}