/
util.go
179 lines (154 loc) · 4.08 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
package main
import (
"bufio"
"bytes"
"context"
"encoding/hex"
"fmt"
"io/ioutil"
"net"
"os"
"strings"
"syscall"
"time"
"github.com/pkg/errors"
log "github.com/xlab/suplog"
"golang.org/x/crypto/ssh/terminal"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
)
// readEnv is a special utility that reads `.env` file into actual environment variables
// of the current app, similar to `dotenv` Node package.
func readEnv() {
if envdata, _ := ioutil.ReadFile(".env"); len(envdata) > 0 {
s := bufio.NewScanner(bytes.NewReader(envdata))
for s.Scan() {
txt := s.Text()
valIdx := strings.IndexByte(txt, '=')
if valIdx < 0 {
continue
}
strValue := strings.Trim(txt[valIdx+1:], `"`)
if err := os.Setenv(txt[:valIdx], strValue); err != nil {
log.WithField("name", txt[:valIdx]).WithError(err).Warningln("failed to override ENV variable")
}
}
}
}
func keyPassphraseFromStdin() (string, error) {
defer func() {
fmt.Println()
}()
bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
err := errors.Wrap(err, "failed to read password from stdin")
return "", err
}
password := string(bytePassword)
return strings.TrimSpace(password), nil
}
// stdinConfirm checks the user's confirmation, if not forced to Yes
func stdinConfirm(msg string) bool {
var response string
fmt.Println(msg)
if _, err := fmt.Scanln(&response); err != nil {
return false
}
switch strings.ToLower(strings.TrimSpace(response)) {
case "y", "yes":
return true
default:
return false
}
}
// logLevel converts vague log level name into typed level.
func logLevel(s string) log.Level {
switch s {
case "1", "error":
return log.ErrorLevel
case "2", "warn":
return log.WarnLevel
case "3", "info":
return log.InfoLevel
case "4", "debug":
return log.DebugLevel
default:
return log.FatalLevel
}
}
// toBool is used to parse vague bool definition into typed bool.
func toBool(s string) bool {
switch strings.ToLower(s) {
case "true", "1", "t", "yes":
return true
default:
return false
}
}
// duration parses duration from string with a provided default fallback.
func duration(s string, defaults time.Duration) time.Duration {
dur, err := time.ParseDuration(s)
if err != nil {
dur = defaults
}
return dur
}
// checkStatsdPrefix ensures that the statsd prefix really
// have "." at end.
func checkStatsdPrefix(s string) string {
if !strings.HasSuffix(s, ".") {
return s + "."
}
return s
}
func hexToBytes(str string) ([]byte, error) {
if strings.HasPrefix(str, "0x") {
str = str[2:]
}
data, err := hex.DecodeString(str)
if err != nil {
return nil, err
}
return data, nil
}
func waitForService(ctx context.Context, conn *grpc.ClientConn) error {
for {
select {
case <-ctx.Done():
return errors.Errorf("Service wait timed out. Please run injectived node.")
default:
state := conn.GetState()
if state != connectivity.Ready {
time.Sleep(time.Second)
continue
}
return nil
}
}
}
func grpcDialEndpoint(protoAddr string) (conn *grpc.ClientConn, err error) {
conn, err = grpc.Dial(protoAddr, grpc.WithInsecure(), grpc.WithContextDialer(dialerFunc))
if err != nil {
err := errors.Wrapf(err, "failed to connect to the gRPC: %s", protoAddr)
return nil, err
}
return conn, nil
}
// dialerFunc dials the given address and returns a net.Conn. The protoAddr argument should be prefixed with the protocol,
// eg. "tcp://127.0.0.1:8080" or "unix:///tmp/test.sock"
func dialerFunc(ctx context.Context, protoAddr string) (net.Conn, error) {
proto, address := protocolAndAddress(protoAddr)
conn, err := net.Dial(proto, address)
return conn, err
}
// protocolAndAddress splits an address into the protocol and address components.
// For instance, "tcp://127.0.0.1:8080" will be split into "tcp" and "127.0.0.1:8080".
// If the address has no protocol prefix, the default is "tcp".
func protocolAndAddress(listenAddr string) (string, string) {
protocol, address := "tcp", listenAddr
parts := strings.SplitN(address, "://", 2)
if len(parts) == 2 {
protocol, address = parts[0], parts[1]
}
return protocol, address
}