forked from GuanceCloud/datakit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
381 lines (318 loc) · 6.65 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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the MIT License.
// This product includes software developed at Guance Cloud (https://www.guance.com/).
// Copyright 2021-present Guance, Inc.
package datakit
import (
"bytes"
"compress/gzip"
"context"
"fmt"
"io"
"net"
"os"
"runtime"
"strconv"
"strings"
"syscall"
"time"
bstoml "github.com/BurntSushi/toml"
pr "github.com/shirou/gopsutil/v3/process"
"gitlab.jiagouyun.com/cloudcare-tools/cliutils"
)
func TrimSuffixAll(s, sfx string) string {
var x string
for {
x = strings.TrimSuffix(s, sfx)
if x == s {
break
}
s = x
}
return x
}
func MonitProc(proc *os.Process, name string, stopCh *cliutils.Sem) error {
tick := time.NewTicker(time.Second)
defer tick.Stop()
if proc == nil {
return fmt.Errorf("invalid proc %s", name)
}
for {
select {
case <-tick.C:
p, err := os.FindProcess(proc.Pid)
if err != nil {
continue
}
switch runtime.GOOS {
case OSWindows:
default:
if err := p.Signal(syscall.Signal(0)); err != nil {
return err
}
}
case <-Exit.Wait():
return doKill(proc, name)
case <-stopCh.Wait():
return doKill(proc, name)
}
}
}
func doKill(proc *os.Process, name string) error {
if err := proc.Kill(); err != nil { // XXX: should we wait here?
return err
}
sts, err := proc.Wait()
if err != nil {
return err
}
l.Infof("proc wait, proc name: %ss exit code: %v", name, sts.ExitCode())
return nil
}
func RndTicker(s string) (*time.Ticker, error) {
du, err := time.ParseDuration(s)
if err != nil {
return nil, err
}
if du <= 0 {
return nil, fmt.Errorf("duration should larger than 0")
}
now := time.Now().UnixNano()
rnd := now % int64(du)
time.Sleep(time.Duration(rnd))
return time.NewTicker(du), nil
}
func RawTicker(s string) (*time.Ticker, error) {
du, err := time.ParseDuration(s)
if err != nil {
return nil, err
}
if du <= 0 {
return nil, fmt.Errorf("duration should larger than 0")
}
return time.NewTicker(du), nil
}
// SleepContext sleeps until the context is closed or the duration is reached.
func SleepContext(ctx context.Context, duration time.Duration) error {
if duration == 0 {
return nil
}
t := time.NewTimer(duration)
select {
case <-t.C:
return nil
case <-ctx.Done():
t.Stop()
return ctx.Err()
}
}
// Duration just wraps time.Duration.
type Duration struct {
Duration time.Duration
}
// UnmarshalText parses the duration from the TOML config file.
func (d *Duration) UnmarshalText(b []byte) error {
b = bytes.Trim(b, "'")
// see if we can directly convert it
if du, err := time.ParseDuration(string(b)); err == nil {
d.Duration = du
return nil
}
// Parse string duration, ie, "1s"
if uq, err := strconv.Unquote(string(b)); err == nil && len(uq) > 0 {
d.Duration, err = time.ParseDuration(uq)
if err == nil {
return nil
}
}
// First try parsing as integer seconds
if sI, err := strconv.ParseInt(string(b), 10, 64); err == nil {
d.Duration = time.Second * time.Duration(sI)
return nil
}
// Second try parsing as float seconds
if sF, err := strconv.ParseFloat(string(b), 64); err == nil {
d.Duration = time.Second * time.Duration(sF)
} else {
return err
}
return nil
}
func (d *Duration) UnitString(unit time.Duration) string {
ts := fmt.Sprintf("%d", d.Duration/unit)
switch unit {
case time.Second:
return ts + "s"
case time.Millisecond:
return ts + "ms"
case time.Microsecond:
return ts + "mics"
case time.Minute:
return ts + "m"
case time.Hour:
return ts + "h"
case time.Nanosecond:
return ts + "ns"
default:
return ts + "unknow"
}
}
// Size just wraps an int64.
type Size struct {
Size int64
}
func (s *Size) UnmarshalTOML(b []byte) error {
var err error
b = bytes.Trim(b, `'`)
val, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return err
}
s.Size = val
return nil
}
func NumberFormat(str string) string {
// 1,234.0
arr := strings.Split(str, ".")
if len(arr) == 0 {
return str
}
part1 := arr[0]
ps := strings.Split(part1, ",")
if len(ps) == 0 {
return str
}
n := strings.Join(ps, "")
if len(arr) > 1 {
n += "." + arr[1]
}
return n
}
func GZipStr(str string) ([]byte, error) {
var z bytes.Buffer
zw := gzip.NewWriter(&z)
if _, err := io.WriteString(zw, str); err != nil {
return nil, err
}
if err := zw.Flush(); err != nil {
return nil, err
}
if err := zw.Close(); err != nil {
return nil, err
}
return z.Bytes(), nil
}
func GZip(data []byte) ([]byte, error) {
var z bytes.Buffer
zw := gzip.NewWriter(&z)
if _, err := zw.Write(data); err != nil {
return nil, err
}
if err := zw.Flush(); err != nil {
return nil, err
}
if err := zw.Close(); err != nil {
return nil, err
}
return z.Bytes(), nil
}
var dnsdests = []string{
`114.114.114.114:80`,
`8.8.8.8:80`,
}
func LocalIP() (string, error) {
for _, dest := range dnsdests {
conn, err := net.DialTimeout("udp", dest, time.Second)
if err == nil {
defer conn.Close() //nolint:errcheck
localAddr, ok := conn.LocalAddr().(*net.UDPAddr)
if !ok {
return "", fmt.Errorf("expect net.UDPAddr")
}
return localAddr.IP.String(), nil
}
}
return GetFirstGlobalUnicastIP()
}
func GetFirstGlobalUnicastIP() (string, error) {
ifaces, err := net.Interfaces()
if err != nil {
return "", err
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
default:
// pass
}
switch {
case ip.IsGlobalUnicast():
return ip.String(), nil
default:
// pass
}
}
}
return "", fmt.Errorf("no IP found")
}
func TomlMarshal(v interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
if err := bstoml.NewEncoder(buf).Encode(v); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func FileExist(filename string) bool {
_, err := os.Stat(filename)
return err == nil || os.IsExist(err)
}
func CheckExcluded(item string, blacklist, whitelist []string) bool {
for _, v := range blacklist {
if v == item {
return true
}
}
if len(whitelist) > 0 {
exclude := true
for _, v := range whitelist {
if v == item {
exclude = false
break
}
}
return exclude
}
return false
}
func TimestampMsToTime(ms int64) time.Time {
return time.Unix(0, ms*1000000)
}
func GetEnv(env string) string {
if v, ok := os.LookupEnv(env); ok {
if v != "" {
return v
}
}
return ""
}
func OpenFiles() int {
pid := os.Getpid()
p, err := pr.NewProcess(int32(pid))
if err != nil {
return -1
}
if fs, err := p.OpenFiles(); err != nil {
return -1
} else {
return len(fs)
}
}