-
Notifications
You must be signed in to change notification settings - Fork 327
/
util.go
350 lines (292 loc) · 6.54 KB
/
util.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
package util
import (
"bufio"
"fmt"
"io"
"math/rand"
"net"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/emccode/rexray/errors"
)
const (
LogDirPathSuffix = "/var/log/rexray"
EtcDirPathSuffix = "/etc/rexray"
BinDirPathSuffix = "/usr/bin"
RunDirPathSuffix = "/var/run/rexray"
LibDirPathSuffix = "/var/lib/rexray"
UnitFilePath = "/etc/systemd/system/rexray.service"
InitFilePath = "/etc/init.d/rexray"
EnvFileName = "rexray.env"
)
var (
prefix string
homeDir string
binDirPath string
binFilePath string
logDirPath string
libDirPath string
runDirPath string
etcDirPath string
pidFilePath string
)
func init() {
homeDir = HomeDir()
prefix = os.Getenv("REXRAY_HOME")
}
func GetPrefix() string {
return prefix
}
func Prefix(p string) {
if p == "" || p == "/" {
return
}
prefix = p
}
func IsPrefixed() bool {
return !(prefix == "" || prefix == "/")
}
func HomeDir() string {
if homeDir != "" {
return homeDir
}
hd := "$HOME"
curUser, curUserErr := user.Current()
if curUserErr == nil {
hd = curUser.HomeDir
}
return hd
}
func StringInSlice(a string, list []string) bool {
for _, b := range list {
if strings.ToLower(b) == strings.ToLower(a) {
return true
}
}
return false
}
func Install(args ...string) {
exec.Command("install", args...).Run()
}
func InstallChownRoot(args ...string) {
a := []string{"-o", "0", "-g", "0"}
for _, i := range args {
a = append(a, i)
}
exec.Command("install", a...).Run()
}
func InstallDirChownRoot(dirPath string) {
InstallChownRoot("-d", dirPath)
}
func EtcDirPath() string {
if etcDirPath == "" {
etcDirPath = fmt.Sprintf("%s%s", prefix, EtcDirPathSuffix)
os.MkdirAll(etcDirPath, 0755)
}
return etcDirPath
}
func RunDirPath() string {
if runDirPath == "" {
runDirPath = fmt.Sprintf("%s%s", prefix, RunDirPathSuffix)
os.MkdirAll(runDirPath, 0755)
}
return runDirPath
}
func LogDirPath() string {
if logDirPath == "" {
logDirPath = fmt.Sprintf("%s%s", prefix, LogDirPathSuffix)
os.MkdirAll(logDirPath, 0755)
}
return logDirPath
}
func LibDirPath() string {
if libDirPath == "" {
libDirPath = fmt.Sprintf("%s%s", prefix, LibDirPathSuffix)
os.MkdirAll(libDirPath, 0755)
}
return libDirPath
}
func BinDirPath() string {
if binDirPath == "" {
binDirPath = fmt.Sprintf("%s%s", prefix, BinDirPathSuffix)
os.MkdirAll(binDirPath, 0755)
}
return binDirPath
}
func PidFilePath() string {
if pidFilePath == "" {
pidFilePath = fmt.Sprintf("%s/rexray.pid", RunDirPath())
}
return pidFilePath
}
func BinFilePath() string {
if binFilePath == "" {
binFilePath = fmt.Sprintf("%s/rexray", BinDirPath())
}
return binFilePath
}
func EtcFilePath(fileName string) string {
return fmt.Sprintf("%s/%s", EtcDirPath(), fileName)
}
func LogFilePath(fileName string) string {
return fmt.Sprintf("%s/%s", LogDirPath(), fileName)
}
func LogFile(fileName string) (io.Writer, error) {
return os.OpenFile(
LogFilePath(fileName), os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
}
func StdOutAndLogFile(fileName string) (io.Writer, error) {
lf, lfErr := LogFile(fileName)
if lfErr != nil {
return nil, lfErr
}
return io.MultiWriter(os.Stdout, lf), nil
}
func WriteStringToFile(text, path string) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0644)
defer f.Close()
if err != nil {
return err
}
f.WriteString(text)
return nil
}
func ReadFileToString(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
scanner := bufio.NewScanner(f)
if !scanner.Scan() {
return "", errors.WithField("path", path, "error reading file")
}
return scanner.Text(), nil
}
func WritePidFile(pid int) error {
if pid < 0 {
pid = os.Getpid()
}
return WriteStringToFile(fmt.Sprintf("%d", pid), PidFilePath())
}
func ReadPidFile() (int, error) {
pidStr, pidStrErr := ReadFileToString(PidFilePath())
if pidStrErr != nil {
return -1, pidStrErr
}
pid, atoiErr := strconv.Atoi(pidStr)
if atoiErr != nil {
return -1, atoiErr
}
return pid, nil
}
func IsDirEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdir(1)
if err == io.EOF {
return true, nil
}
return false, err
}
func LineReader(filePath string) <-chan string {
if !FileExists(filePath) {
return nil
}
c := make(chan string)
go func() {
f, err := os.Open(filePath)
if err != nil {
panic(err)
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
c <- s.Text()
}
close(c)
}()
return c
}
func FileExists(filePath string) bool {
if _, err := os.Stat(filePath); !os.IsNotExist(err) {
return true
}
return false
}
func FileExistsInPath(fileName string) bool {
_, err := exec.LookPath(fileName)
return err == nil
}
func GetPathParts(path string) (dirPath, fileName, absPath string) {
lookup, lookupErr := exec.LookPath(path)
if lookupErr == nil {
path = lookup
}
absPath, _ = filepath.Abs(path)
dirPath = filepath.Dir(absPath)
fileName = filepath.Base(absPath)
return
}
func GetThisPathParts() (dirPath, fileName, absPath string) {
return GetPathParts(os.Args[0])
}
const (
LETTER_BYTES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
LETTER_INDEX_BITS = 6
LETTER_INDEX_MASK = 1<<LETTER_INDEX_BITS - 1
LETTER_INDEX_MAX = 63 / LETTER_INDEX_BITS
)
func RandomString(length int) string {
src := rand.NewSource(time.Now().UnixNano())
b := make([]byte, length)
for i, cache, remain := length-1, src.Int63(), LETTER_INDEX_MAX; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), LETTER_INDEX_MAX
}
if idx := int(cache & LETTER_INDEX_MASK); idx < len(LETTER_BYTES) {
b[i] = LETTER_BYTES[idx]
i--
}
cache >>= LETTER_INDEX_BITS
remain--
}
return string(b)
}
// GetLocalIP returns the non loopback local IP of the host
func GetLocalIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}
const ADDR_PATT = "(?i)^((?:(?:tcp|udp|ip)[46]?)|(?:unix(?:gram|packet)?))://(.+)$"
func ParseAddress(addr string) (proto string, path string, err error) {
rx, rxErr := regexp.Compile(ADDR_PATT)
if rxErr != nil {
return "", "", nil
}
if !rx.MatchString(addr) {
return "", "", errors.New(fmt.Sprintf("Invalid address '%s'", addr))
}
m := rx.FindStringSubmatch(addr)
return m[1], m[2], nil
}