-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.go
334 lines (288 loc) · 8.01 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
// Package agent contains the public interfaces, functions, consts, and vars for the viam-server agent.
package agent
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"errors"
"io"
"io/fs"
"math/rand"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"syscall"
"time"
errw "github.com/pkg/errors"
"github.com/ulikunitz/xz"
"golang.org/x/sys/unix"
"google.golang.org/protobuf/types/known/structpb"
)
var (
// versions embedded at build time.
Version = ""
GitRevision = ""
ViamDirs = map[string]string{"viam": "/opt/viam"}
)
// GetVersion returns the version embedded at build time.
func GetVersion() string {
if Version == "" {
return "custom"
}
return Version
}
// GetRevision returns the git revision embedded at build time.
func GetRevision() string {
if GitRevision == "" {
return "unknown"
}
return GitRevision
}
func init() {
ViamDirs["bin"] = filepath.Join(ViamDirs["viam"], "bin")
ViamDirs["cache"] = filepath.Join(ViamDirs["viam"], "cache")
ViamDirs["tmp"] = filepath.Join(ViamDirs["viam"], "tmp")
ViamDirs["etc"] = filepath.Join(ViamDirs["viam"], "etc")
}
func InitPaths() error {
uid := os.Getuid()
for _, p := range ViamDirs {
info, err := os.Stat(p)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
//nolint:gosec
if err := os.MkdirAll(p, 0o755); err != nil {
return errw.Wrapf(err, "creating directory %s", p)
}
continue
}
return errw.Wrapf(err, "checking directory %s", p)
}
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
// should be impossible on Linux
return errw.New("cannot convert to syscall.Stat_t")
}
if uid != int(stat.Uid) {
return errw.Errorf("%s is owned by UID %d but the current UID is %d", p, stat.Uid, uid)
}
if !info.IsDir() {
return errw.Errorf("%s should be a directory, but is not", p)
}
if info.Mode().Perm() != 0o755 {
return errw.Errorf("%s should be have permission set to 0755, but has permissions %d", p, info.Mode().Perm())
}
}
return nil
}
// DownloadFile downloads a file into the cache directory and returns a path to the file.
func DownloadFile(ctx context.Context, rawURL string) (outPath string, errRet error) {
parsedURL, err := url.Parse(rawURL)
if err != nil {
return "", err
}
outPath = filepath.Join(ViamDirs["cache"], path.Base(parsedURL.Path))
//nolint:nestif
if parsedURL.Scheme == "file" {
infd, err := os.Open(parsedURL.Path)
if err != nil {
return "", err
}
defer func() {
errRet = errors.Join(errRet, infd.Close())
}()
//nolint:gosec
if err := os.MkdirAll(ViamDirs["tmp"], 0o755); err != nil {
return "", err
}
outfd, err := os.CreateTemp(ViamDirs["tmp"], "*")
if err != nil {
return "", err
}
defer func() {
errRet = errors.Join(errRet, outfd.Close(), SyncFS(outPath))
if err := os.Remove(outfd.Name()); err != nil && !os.IsNotExist(err) {
errRet = errors.Join(errRet, err)
}
}()
_, err = io.Copy(outfd, infd)
if err != nil {
return "", err
}
errRet = errors.Join(errRet, os.Rename(outfd.Name(), outPath))
return outPath, errRet
}
if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
return "", errw.Errorf("unsupported url scheme %s", parsedURL.Scheme)
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsedURL.String(), nil)
if err != nil {
return "", errw.Wrap(err, "checking viam-server status")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", errw.Wrap(err, "checking viam-server status")
}
defer func() {
errRet = errors.Join(errRet, resp.Body.Close())
}()
//nolint:gosec
if err := os.MkdirAll(ViamDirs["tmp"], 0o755); err != nil {
return "", err
}
out, err := os.CreateTemp(ViamDirs["tmp"], "*")
if err != nil {
return "", err
}
defer func() {
errRet = errors.Join(errRet, out.Close(), SyncFS(out.Name()))
if err := os.Remove(out.Name()); err != nil && !os.IsNotExist(err) {
errRet = errors.Join(errRet, err)
}
}()
_, err = io.Copy(out, resp.Body)
if err != nil && !os.IsNotExist(err) {
errRet = errors.Join(errRet, err)
}
errRet = errors.Join(errRet, os.Rename(out.Name(), outPath), SyncFS(outPath))
return outPath, errRet
}
// DecompressFile extracts a compressed file and returns the path to the extracted file.
func DecompressFile(inPath string) (outPath string, errRet error) {
//nolint:gosec
in, err := os.Open(inPath)
if err != nil {
return "", err
}
defer func() {
errRet = errors.Join(errRet, in.Close())
}()
reader, err := xz.NewReader(bufio.NewReader(in))
if err != nil {
return "", err
}
out, err := os.CreateTemp(ViamDirs["tmp"], "*")
if err != nil {
return "", err
}
defer func() {
errRet = errors.Join(errRet, out.Close(), SyncFS(ViamDirs["tmp"]))
if err := os.Remove(out.Name()); err != nil && !os.IsNotExist(err) {
errRet = errors.Join(errRet, err)
}
}()
_, err = io.Copy(out, reader)
if err != nil && !os.IsNotExist(err) {
errRet = errors.Join(errRet, err)
}
outPath = filepath.Join(ViamDirs["cache"], strings.Replace(filepath.Base(inPath), ".xz", "", 1))
errRet = errors.Join(errRet, os.Rename(out.Name(), outPath), SyncFS(outPath))
return outPath, errRet
}
func GetFileSum(filepath string) (outSum []byte, errRet error) {
//nolint:gosec
in, err := os.Open(filepath)
if err != nil {
return nil, err
}
defer func() {
errRet = errors.Join(errRet, in.Close())
}()
h := sha256.New()
_, errRet = io.Copy(h, in)
return h.Sum(nil), errRet
}
func fuzzTime(duration time.Duration, pct float64) time.Duration {
// pct is fuzz factor percentage 0.0 - 1.0
// example +/- 5% is 0.05
//nolint:gosec
random := rand.New(rand.NewSource(time.Now().UnixNano())).Float64()
slop := float64(duration) * pct * 2
return time.Duration(float64(duration) - slop + (random * slop))
}
func CheckIfSame(path1, path2 string) (bool, error) {
curPath, err := filepath.EvalSymlinks(path1)
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
if err != nil {
return false, errw.Wrapf(err, "evaluating symlinks pointing to %s", path1)
}
stat1, err := os.Stat(curPath)
if err != nil {
return false, errw.Wrapf(err, "statting %s", curPath)
}
realPath, err := filepath.EvalSymlinks(path2)
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
if err != nil {
return false, errw.Wrapf(err, "evaluating symlinks pointing to %s", path2)
}
stat2, err := os.Stat(realPath)
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
if err != nil {
return false, errw.Wrapf(err, "statting %s", realPath)
}
return os.SameFile(stat1, stat2), nil
}
func ForceSymlink(orig, symlink string) error {
err := os.Remove(symlink)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return errw.Wrap(err, "removing old symlink")
}
err = os.Symlink(orig, symlink)
if err != nil {
return errw.Wrap(err, "symlinking file")
}
return SyncFS(symlink)
}
func SyncFS(syncPath string) (errRet error) {
file, errRet := os.Open(filepath.Dir(syncPath))
if errRet != nil {
return errw.Wrapf(errRet, "syncing fs %s", syncPath)
}
_, _, err := unix.Syscall(unix.SYS_SYNCFS, file.Fd(), 0, 0)
if err != 0 {
errRet = errw.Wrapf(err, "syncing fs %s", syncPath)
}
return errors.Join(errRet, file.Close())
}
func WriteFileIfNew(outPath string, data []byte) (bool, error) {
//nolint:gosec
curFileBytes, err := os.ReadFile(outPath)
if err != nil {
if !errw.Is(err, fs.ErrNotExist) {
return false, errw.Wrapf(err, "opening %s for reading", outPath)
}
} else if bytes.Equal(curFileBytes, data) {
return false, nil
}
//nolint:gosec
if err := os.MkdirAll(path.Dir(outPath), 0o755); err != nil {
return true, errw.Wrapf(err, "creating directory for %s", outPath)
}
//nolint:gosec
if err := os.WriteFile(outPath, data, 0o644); err != nil {
return true, errw.Wrapf(err, "writing %s", outPath)
}
return true, nil
}
func ConvertAttributes[T any](attributes *structpb.Struct) (*T, error) {
jsonBytes, err := attributes.MarshalJSON()
if err != nil {
return new(T), err
}
newConfig := new(T)
if err = json.Unmarshal(jsonBytes, newConfig); err != nil {
return new(T), err
}
return newConfig, nil
}