forked from VertebrateResequencing/wr
/
utils.go
461 lines (408 loc) · 12.4 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// Copyright © 2016-2018 Genome Research Limited
// Author: Sendu Bala <sb10@sanger.ac.uk>.
//
// This file is part of wr.
//
// wr is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// wr is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with wr. If not, see <http://www.gnu.org/licenses/>.
package internal
// this file has general utility functions
import (
"crypto/md5" // #nosec not used for security purposes
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
infoblox "github.com/fanatic/go-infoblox"
"github.com/inconshreveable/log15"
"github.com/ricochet2200/go-disk-usage/du"
"github.com/shirou/gopsutil/mem"
)
const gb = uint64(1.07374182e9) // for byte to GB conversion
const mb100 = uint64(104857600) // 100MB in bytes
// for the RandomString implementation
const (
randBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
randIdxBits = 6 // 6 bits to represent a rand index
randIdxMask = 1<<randIdxBits - 1 // All 1-bits, as many as letterIdxBits
randIdxMax = 63 / randIdxBits // # of letter indices fitting in 63 bits
)
var username string
var userid int
// SortMapKeysByIntValue sorts the keys of a map[string]int by its values,
// reversed if you supply true as the second arg.
func SortMapKeysByIntValue(imap map[string]int, reverse bool) []string {
// from http://stackoverflow.com/a/18695428/675083 *** should also try the
// idiomatic way to see if that's better in any way
valToKeys := map[int][]string{}
for key, val := range imap {
valToKeys[val] = append(valToKeys[val], key)
}
var vals []int
for val := range valToKeys {
vals = append(vals, val)
}
if reverse {
sort.Sort(sort.Reverse(sort.IntSlice(vals)))
} else {
sort.Sort(sort.IntSlice(vals))
}
var sortedKeys []string
for _, val := range vals {
sortedKeys = append(sortedKeys, valToKeys[val]...)
}
return sortedKeys
}
// SortMapKeysByMapIntValue sorts the keys of a map[string]map[string]int by
// a the values found at a given sub value, reversed if you supply true as the
// second arg.
func SortMapKeysByMapIntValue(imap map[string]map[string]int, criterion string, reverse bool) []string {
criterionValueToKeys := make(map[int][]string)
for key, submap := range imap {
val := submap[criterion]
criterionValueToKeys[val] = append(criterionValueToKeys[val], key)
}
var criterionValues []int
for val := range criterionValueToKeys {
criterionValues = append(criterionValues, val)
}
if reverse {
sort.Sort(sort.Reverse(sort.IntSlice(criterionValues)))
} else {
sort.Sort(sort.IntSlice(criterionValues))
}
var sortedKeys []string
for _, val := range criterionValues {
sortedKeys = append(sortedKeys, criterionValueToKeys[val]...)
}
return sortedKeys
}
// Username returns the username of the current user. This avoids problems
// with static compilation as it avoids the use of os/user. It will only work
// on linux-like systems where 'id -u -n' works.
func Username() (string, error) {
if username == "" {
var err error
username, err = parseIDCmd("-u", "-n")
if err != nil {
return "", err
}
}
return username, nil
}
// Userid returns the user id of the current user. This avoids problems
// with static compilation as it avoids the use of os/user. It will only work
// on linux-like systems where 'id -u' works.
func Userid() (int, error) {
if userid == 0 {
uidStr, err := parseIDCmd("-u")
if err != nil {
return 0, err
}
userid, err = strconv.Atoi(uidStr)
if err != nil {
return 0, err
}
}
return userid, nil
}
// parseIDCmd parses the output of the unix 'id' command.
func parseIDCmd(idopts ...string) (string, error) {
idcmd := exec.Command("/usr/bin/id", idopts...) // #nosec
idout, err := idcmd.Output()
if err != nil {
return "", err
}
return strings.TrimSuffix(string(idout), "\n"), err
}
// TildaToHome converts a path beginning with ~/ to the absolute path based in
// the current home directory (according to the environment variable $HOME).
func TildaToHome(path string) string {
home := os.Getenv("HOME")
if home != "" && strings.HasPrefix(path, "~/") {
path = strings.TrimLeft(path, "~/")
path = filepath.Join(home, path)
}
return path
}
// ProcMeminfoMBs uses gopsutil (amd64 freebsd, linux, windows, darwin, openbds
// only!) to find the total number of MBs of memory physically installed on the
// current system.
func ProcMeminfoMBs() (int, error) {
v, err := mem.VirtualMemory()
if err != nil {
return 0, err
}
// convert bytes to MB
return int((v.Total / 1024) / 1024), err
}
// DiskSize returns the size of the disk (mounted at the given directory, "."
// for current) in GB.
func DiskSize(dir string) int {
usage := du.NewDiskUsage(dir)
return int(usage.Size() / gb)
}
// NoDiskSpaceLeft tells you if the disk (mounted at the given directory, "."
// for current) has no more space left (or is within 100MB of being full).
func NoDiskSpaceLeft(dir string) bool {
usage := du.NewDiskUsage(dir)
return usage.Free() < mb100
}
// LogClose is for use to Close() an object during a defer when you don't care
// if the Close() returns an error, but do want non-EOF errors logged. Extra
// args are passed as additional context for the logger.
func LogClose(logger log15.Logger, obj io.Closer, msg string, extra ...interface{}) {
err := obj.Close()
if err != nil && err.Error() != "EOF" {
extra = append(extra, "err", err)
logger.Warn("failed to close "+msg, extra...)
}
}
// LogPanic is for use in a go routines, deferred at the start of them, to
// figure out what is causing runtime panics. If the die bool is true, the
// program exits, otherwise it continues, after logging the error message and
// stack trace. Desc string should be used to describe briefly what the
// goroutine you call this in does.
func LogPanic(logger log15.Logger, desc string, die bool) {
if err := recover(); err != nil {
logger.Crit(desc+" panic", "err", err)
if die {
os.Exit(1)
}
}
}
// Which returns the full path to the executable with the given name that is
// found first in the set of $PATH directories, ignoring any path that is
// actually a symlink to ourselves.
func Which(exeName string) string {
self, _ := os.Executable()
self, _ = filepath.EvalSymlinks(self)
for _, dir := range strings.Split(os.Getenv("PATH"), string(os.PathListSeparator)) {
stat, err := os.Stat(dir)
if err != nil || !stat.IsDir() {
continue
}
exes, err := ioutil.ReadDir(dir)
if err != nil {
continue
}
for _, exe := range exes {
if exe.Name() != exeName {
continue
}
path := filepath.Join(dir, exe.Name())
// check that it's not a symlink to ourselves
path, err := filepath.EvalSymlinks(path)
if err != nil || path == self {
continue
}
// check it's executable
stat, err := os.Stat(path)
if err == nil && (runtime.GOOS == "windows" || stat.Mode()&0111 != 0) {
return path
}
}
}
return ""
}
// WaitForFile waits as long as timeout for the given file to exist. When it
// exists, returns true. Otherwise false.
func WaitForFile(file string, timeout time.Duration) bool {
limit := time.After(timeout)
ticker := time.NewTicker(50 * time.Millisecond)
for {
select {
case <-ticker.C:
_, err := os.Stat(file)
if err == nil {
ticker.Stop()
return true
}
continue
case <-limit:
ticker.Stop()
return false
}
}
}
// InfobloxSetDomainIP uses infoblox to set the IP of a domain. Returns an error
// if INFOBLOX_HOST, INFOBLOX_USER or INFOBLOX_PASS env vars are not set.
func InfobloxSetDomainIP(domain, ip string) error {
if domain == "localhost" {
return fmt.Errorf("can't set domain IP when domain is configured as localhost")
}
// turn off logging built in to go-infoblox
log.SetFlags(0)
log.SetOutput(ioutil.Discard)
// check env vars are defined
host := os.Getenv("INFOBLOX_HOST")
if host == "" {
return fmt.Errorf("INFOBLOX_HOST env var not set")
}
user := os.Getenv("INFOBLOX_USER")
if user == "" {
return fmt.Errorf("INFOBLOX_USER env var not set")
}
password := os.Getenv("INFOBLOX_PASS")
if password == "" {
return fmt.Errorf("INFOBLOX_PASS env var not set")
}
// create infoblox client
ib := infoblox.NewClient("https://"+host+"/", user, password, true, false)
// check if it's already set
objs, err := ib.FindRecordA(domain)
if err != nil {
return fmt.Errorf("finding A records failed: %s", err)
}
if len(objs) == 1 {
if objs[0].Ipv4Addr == ip {
return nil
}
}
// delete any existing entries
for _, obj := range objs {
err = ib.NetworkObject(obj.Ref).Delete(nil)
if err != nil {
return fmt.Errorf("delete of A record failed: %s", err)
}
}
// now add an A record for domain pointing to ip
d := url.Values{}
d.Set("ipv4addr", ip)
d.Set("name", domain)
_, err = ib.RecordA().Create(d, nil, nil)
if err != nil {
return fmt.Errorf("create of A record failed: %s", err)
}
// wait a while for things to "really" work
<-time.After(500 * time.Millisecond)
return nil
}
// FileMD5 calculates the MD5 hash checksum of a file, returned as HEX encoded.
func FileMD5(path string, logger log15.Logger) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer LogClose(logger, file, "fileMD5", "path", path)
h := md5.New() // #nosec not used for security purposes
if _, err := io.Copy(h, file); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// RandomString generates a random string of length 8 characters.
func RandomString() string {
// based on http://stackoverflow.com/a/31832326/675083
b := make([]byte, 8)
src := rand.NewSource(time.Now().UnixNano())
for i, cache, remain := 7, src.Int63(), randIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), randIdxMax
}
if idx := int(cache & randIdxMask); idx < len(randBytes) {
b[i] = randBytes[idx]
i--
}
cache >>= randIdxBits
remain--
}
return string(b)
}
// CurrentIP returns the IP address of the machine we're running on right now.
// The cidr argument can be an empty string, but if set to the CIDR of the
// machine's primary network, it helps us be sure of getting the correct IP
// address (for when there are multiple network interfaces on the machine).
func CurrentIP(cidr string) (string, error) {
var ipNet *net.IPNet
if cidr != "" {
_, ipn, err := net.ParseCIDR(cidr)
if err == nil {
ipNet = ipn
}
// *** ignoring error since I don't want to change the return value of
// this method...
}
conn, err := net.Dial("udp", "8.8.8.8:80") // doesn't actually connect, dest doesn't need to exist
if err != nil {
// fall-back on the old method we had...
// first just hope http://stackoverflow.com/a/25851186/675083 gives us a
// cross-linux&MacOS solution that works reliably...
var out []byte
out, err = exec.Command("sh", "-c", "ip -4 route get 8.8.8.8 | head -1 | cut -d' ' -f8 | tr -d '\\n'").Output() // #nosec
var ip string
if err != nil {
ip = string(out)
// paranoid confirmation this ip is in our CIDR
if ip != "" && ipNet != nil {
pip := net.ParseIP(ip)
if pip != nil {
if !ipNet.Contains(pip) {
ip = ""
}
}
}
}
// if the above fails, fall back on manually going through all our
// network interfaces
if ip == "" {
var addrs []net.Addr
addrs, err = net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, address := range addrs {
if thisIPNet, ok := address.(*net.IPNet); ok && !thisIPNet.IP.IsLoopback() {
if thisIPNet.IP.To4() != nil {
if ipNet != nil {
if ipNet.Contains(thisIPNet.IP) {
ip = thisIPNet.IP.String()
break
}
} else {
ip = thisIPNet.IP.String()
break
}
}
}
}
}
return ip, nil
}
defer func() {
err = conn.Close()
}()
localAddr := conn.LocalAddr().(*net.UDPAddr)
ip := localAddr.IP
// paranoid confirmation this ip is in our CIDR
if ipNet != nil {
if ipNet.Contains(ip) {
return ip.String(), err
}
} else {
return ip.String(), err
}
return "", err
}