-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.go
1352 lines (1142 loc) · 29.7 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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package utils
import (
"bufio"
"bytes"
"context"
"crypto/md5"
"crypto/sha1"
"encoding/asn1"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
"reflect"
"regexp"
"runtime"
"runtime/debug"
"slices"
"strconv"
"strings"
"syscall"
"time"
"unsafe"
"github.com/GoWebProd/uuid7"
"github.com/Laisky/errors/v2"
"github.com/Laisky/zap"
"github.com/google/go-cpy/cpy"
"github.com/google/uuid"
jsoniter "github.com/json-iterator/go"
"go.uber.org/automaxprocs/maxprocs"
"golang.org/x/sync/singleflight"
"github.com/Laisky/go-utils/v5/algorithm"
"github.com/Laisky/go-utils/v5/common"
"github.com/Laisky/go-utils/v5/json"
"github.com/Laisky/go-utils/v5/log"
)
type jsonT struct {
jsoniter.API
}
var (
// JSON effective json
//
// Deprecated: use github.com/Laisky/go-utils/v5/json instead
JSON = jsonT{API: jsoniter.ConfigCompatibleWithStandardLibrary}
internalSFG singleflight.Group
// for compatibility to old version
// =====================================
// Str2Bytes unsafe convert str to bytes
Str2Bytes = common.Str2Bytes
// Bytes2Str unsafe convert bytes to str
Bytes2Str = common.Bytes2Str
// Number2Roman convert number to roman
Number2Roman = common.Number2Roman
)
const (
defaultCgroupMemLimitPath = "/sys/fs/cgroup/memory/memory.limit_in_bytes"
defaultGCMemRatio = uint64(85)
)
func init() {
if _, err := maxprocs.Set(maxprocs.Logger(func(s string, i ...interface{}) {
log.Shared.Debug(fmt.Sprintf(s, i...))
})); err != nil {
log.Shared.Error("auto set maxprocs", zap.Error(err))
}
}
var cloner = cpy.New(
cpy.IgnoreAllUnexported(),
)
// DeepClone deep clone a struct
//
// will ignore all unexported fields
func DeepClone[T any](src T) (dst T) {
return cloner.Copy(src).(T) //nolint:forcetypeassert
}
var dedentMarginChar = regexp.MustCompile(`^[ \t]*`)
type dedentOpt struct {
replaceTabBySpaces int
}
func (d *dedentOpt) fillDefault() *dedentOpt {
d.replaceTabBySpaces = 4
return d
}
func (d *dedentOpt) applyOpts(optfs ...DedentOptFunc) *dedentOpt {
for _, optf := range optfs {
optf(d)
}
return d
}
// SilentClose close and ignore error
//
// Example
//
// defer SilentClose(fp)
func SilentClose(v interface{ Close() error }) {
_ = v.Close()
}
// SilentFlush flush and ignore error
func SilentFlush(v interface{ Flush() error }) {
_ = v.Flush()
}
// CloseWithLog close and log error.
// logger could be nil, then will use internal log.Shared logger instead.
func CloseWithLog(ins interface{ Close() error },
logger interface{ Error(string, ...zap.Field) }) {
LogErr(ins.Close, logger)
}
// LogErr invoke f and log error if got error.
func LogErr(f func() error, logger interface{ Error(string, ...zap.Field) }) {
if logger == nil {
logger = log.Shared
}
if err := f(); err != nil {
logger.Error("close ins", zap.Error(err))
}
}
// FlushWithLog flush and log error.
// logger could be nil, then will use internal log.Shared logger instead.
func FlushWithLog(ins interface{ Flush() error },
logger interface{ Error(string, ...zap.Field) }) {
if logger == nil {
logger = log.Shared
}
if err := ins.Flush(); err != nil {
logger.Error("flush ins", zap.Error(err))
}
}
// DedentOptFunc dedent option
type DedentOptFunc func(opt *dedentOpt)
// WithReplaceTabBySpaces replace tab to spaces
func WithReplaceTabBySpaces(spaces int) DedentOptFunc {
return func(opt *dedentOpt) {
opt.replaceTabBySpaces = spaces
}
}
// Dedent removes leading whitespace or tab from the beginning of each line
//
// will replace all tab to 4 blanks.
func Dedent(v string, optfs ...DedentOptFunc) string {
opt := new(dedentOpt).fillDefault().applyOpts(optfs...)
ls := strings.Split(v, "\n")
var (
NSpaceTobeTrim int
firstLine = true
result = make([]string, 0, len(ls))
)
for _, l := range ls {
if strings.TrimSpace(l) == "" {
if !firstLine {
result = append(result, "")
}
continue
}
m := dedentMarginChar.FindString(l)
spaceIndent := strings.ReplaceAll(m, "\t", strings.Repeat(" ", opt.replaceTabBySpaces))
n := len(spaceIndent)
l = strings.Replace(l, m, spaceIndent, 1)
if firstLine {
NSpaceTobeTrim = n
firstLine = false
} else if n != 0 && n < NSpaceTobeTrim {
// choose the smallest margin
NSpaceTobeTrim = n
}
result = append(result, l)
}
for i := range result {
if result[i] == "" {
continue
}
result[i] = result[i][NSpaceTobeTrim:]
}
// remove tail blank lines
for i := len(result) - 1; i >= 0; i-- {
if result[i] == "" {
result = result[:i]
} else {
break
}
}
return strings.Join(result, "\n")
}
// HasField check is struct has field
//
// inspired by https://mrwaggel.be/post/golang-reflect-if-initialized-struct-has-member-method-or-fields/
func HasField(st any, fieldName string) bool {
valueIface := reflect.ValueOf(st)
// Check if the passed interface is a pointer
if valueIface.Type().Kind() != reflect.Ptr {
// Create a new type of Iface's Type, so we have a pointer to work with
valueIface = reflect.New(reflect.TypeOf(st))
}
// 'dereference' with Elem() and get the field by name
field := valueIface.Elem().FieldByName(fieldName)
return field.IsValid()
}
// HasMethod check is struct has method
//
// inspired by https://mrwaggel.be/post/golang-reflect-if-initialized-struct-has-member-method-or-fields/
func HasMethod(st any, methodName string) bool {
valueIface := reflect.ValueOf(st)
// Check if the passed interface is a pointer
if valueIface.Type().Kind() != reflect.Ptr {
// Create a new type of Iface, so we have a pointer to work with
valueIface = reflect.New(reflect.TypeOf(st))
}
// Get the method by name
method := valueIface.MethodByName(methodName)
return method.IsValid()
}
// MD5JSON calculate md5(jsonify(data))
func MD5JSON(data any) (string, error) {
if NilInterface(data) {
return "", errors.New("data is nil")
}
b, err := json.Marshal(data)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", md5.Sum(b)), nil
}
// NilInterface make sure data is nil interface or another type with nil value
//
// Example:
//
// type foo struct{}
// var f *foo
// var v any
// v = f
// v == nil // false
// NilInterface(v) // true
func NilInterface(data any) bool {
if data == nil {
return true
}
if reflect.TypeOf(data).Kind() == reflect.Ptr &&
reflect.ValueOf(data).IsNil() {
return true
}
return false
}
// GetStructFieldByName get struct field by name
func GetStructFieldByName(st any, fieldName string) any {
stv := reflect.ValueOf(st)
if IsPtr(st) {
stv = stv.Elem()
}
v := stv.FieldByName(fieldName)
if !v.IsValid() {
return nil
}
switch v.Kind() {
case reflect.Chan,
reflect.Func,
reflect.Slice,
reflect.Array,
reflect.Interface,
reflect.Ptr,
reflect.Map:
if v.IsNil() {
return nil
}
default:
// do nothing
}
return v.Interface()
}
// ValidateFileHash validate file content with hashed string
//
// Args:
// - filepath: file path to check
// - hashed: hashed string, like `sha256: xxxx`
func ValidateFileHash(filepath string, hashed string) error {
hs := strings.Split(hashed, ":")
if len(hs) != 2 {
return errors.Errorf("unknown hashed format, expect is `sha256:xxxx`, but got `%s`", hashed)
}
var hasher HashType
switch hs[0] {
case "sha256":
hasher = HashTypeSha256
case "md5":
hasher = HashTypeMD5
default:
return errors.Errorf("unknown hasher `%s`", hs[0])
}
fp, err := os.Open(filepath)
if err != nil {
return errors.Wrapf(err, "open file `%s`", filepath)
}
defer SilentClose(fp)
sig, err := Hash(hasher, fp)
if err != nil {
return errors.Wrapf(err, "calculate hash for file %q", filepath)
}
actualHash := hex.EncodeToString(sig)
if hs[1] != actualHash {
return errors.Errorf("hash `%s` not match expect `%s`", actualHash, hs[1])
}
return nil
}
// GetFuncName return the name of func
func GetFuncName(f any) string {
return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
}
// FallBack return the fallback when orig got error
// utils.FallBack(func() any { return getIOStatMetric(fs) }, &IOStat{}).(*IOStat)
func FallBack(orig func() any, fallback any) (ret any) {
defer func() {
if recover() != nil {
ret = fallback
}
}()
ret = orig()
return
}
// RegexNamedSubMatch extract key:val map from string by group match
//
// Deprecated: use RegexNamedSubMatch2 instead
func RegexNamedSubMatch(r *regexp.Regexp, str string, subMatchMap map[string]string) error {
match := r.FindStringSubmatch(str)
names := r.SubexpNames()
if len(names) != len(match) {
return errors.New("the number of args in `regexp` and `str` not matched")
}
for i, name := range r.SubexpNames() {
if i != 0 && name != "" {
subMatchMap[name] = match[i]
}
}
return nil
}
// RegexNamedSubMatch2 extract key:val map from string by group match
func RegexNamedSubMatch2(r *regexp.Regexp, str string) (subMatchMap map[string]string, err error) {
match := r.FindStringSubmatch(str)
names := r.SubexpNames()
if len(names) != len(match) {
return nil, errors.New("the number of args in `regexp` and `str` not matched")
}
subMatchMap = make(map[string]string)
for i, name := range r.SubexpNames() {
if i != 0 && name != "" {
subMatchMap[name] = match[i]
}
}
return subMatchMap, nil
}
// FlattenMap make embedded map into flatten map
func FlattenMap(data map[string]any, delimiter string) {
for k, vi := range data {
if v2i, ok := vi.(map[string]any); ok {
FlattenMap(v2i, delimiter)
for k3, v3i := range v2i {
data[k+delimiter+k3] = v3i
}
delete(data, k)
}
}
}
// ForceGCBlocking force to run blocking manual gc.
func ForceGCBlocking() {
log.Shared.Debug("force gc")
runtime.GC()
debug.FreeOSMemory()
}
// ForceGCUnBlocking trigger GC unblocking
func ForceGCUnBlocking() {
go func() {
_, _, _ = internalSFG.Do("ForceGCUnBlocking", func() (any, error) {
ForceGC()
return struct{}{}, nil
})
}()
}
type gcOption struct {
memRatio uint64
memLimitFilePath string
}
// GcOptFunc option for GC utils
type GcOptFunc func(*gcOption) error
// WithGCMemRatio set mem ratio trigger for GC
//
// default to 85
func WithGCMemRatio(ratio int) GcOptFunc {
return func(opt *gcOption) error {
if ratio <= 0 {
return errors.Errorf("ratio must > 0, got %d", ratio)
}
if ratio > 100 {
return errors.Errorf("ratio must <= 0, got %d", ratio)
}
log.Shared.Debug("set memRatio", zap.Int("ratio", ratio))
opt.memRatio = uint64(ratio)
return nil
}
}
// WithGCMemLimitFilePath set memory limit file
func WithGCMemLimitFilePath(path string) GcOptFunc {
return func(opt *gcOption) error {
if _, err := os.Open(path); err != nil {
return errors.Wrapf(err, "try open path `%s`", path)
}
log.Shared.Debug("set memLimitFilePath", zap.String("file", path))
opt.memLimitFilePath = path
return nil
}
}
// AutoGC auto trigger GC when memory usage exceeds the custom ration
//
// default to /sys/fs/cgroup/memory/memory.limit_in_bytes
func AutoGC(ctx context.Context, opts ...GcOptFunc) (err error) {
opt := &gcOption{
memRatio: defaultGCMemRatio,
memLimitFilePath: defaultCgroupMemLimitPath,
}
for _, optf := range opts {
if err = optf(opt); err != nil {
return errors.Wrap(err, "set option")
}
}
var (
fp *os.File
memByte []byte
memLimit uint64
)
if fp, err = os.Open(opt.memLimitFilePath); err != nil {
return errors.Wrapf(err, "open file got error: %+v", opt.memLimitFilePath)
}
defer SilentClose(fp)
if memByte, err = io.ReadAll(fp); err != nil {
return errors.Wrap(err, "read cgroup mem limit file")
}
if err = fp.Close(); err != nil {
log.Shared.Error("close cgroup mem limit file", zap.Error(err), zap.String("file", opt.memLimitFilePath))
}
if memLimit, err = strconv.ParseUint(string(bytes.TrimSpace(memByte)), 10, 64); err != nil {
return errors.Wrap(err, "parse cgroup memory limit")
}
if memLimit == 0 {
return errors.Errorf("mem limit should > 0, but got: %d", memLimit)
}
log.Shared.Info("enable auto gc", zap.Uint64("ratio", opt.memRatio), zap.Uint64("limit", memLimit))
go func(ctx context.Context) {
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
var (
m runtime.MemStats
ratio uint64
)
for {
select {
case <-ticker.C:
case <-ctx.Done():
return
}
runtime.ReadMemStats(&m)
ratio = (m.Alloc * 100) / memLimit
log.Shared.Debug("mem stat",
zap.Uint64("mem", m.Alloc),
zap.Uint64("limit_mem", memLimit),
zap.Uint64("ratio", ratio),
zap.Uint64("limit_ratio", opt.memRatio),
)
if ratio >= opt.memRatio {
ForceGCBlocking()
}
}
}(ctx)
return nil
}
var (
// ForceGC force to start gc blocking
ForceGC = ForceGCBlocking
// TriggerGC force to start gc unblocking
TriggerGC = ForceGCUnBlocking
)
var defaultTemplateWithMappReg = regexp.MustCompile(`(?sm)\$\{([^}]+)\}`)
// TemplateWithMap replace `${var}` in template string
func TemplateWithMap(tpl string, data map[string]any) string {
return TemplateWithMapAndRegexp(defaultTemplateWithMappReg, tpl, data)
}
// TemplateWithMapAndRegexp replace `${var}` in template string
func TemplateWithMapAndRegexp(tplReg *regexp.Regexp, tpl string, data map[string]any) string {
var (
k, vs string
vi any
)
for _, kg := range tplReg.FindAllStringSubmatch(tpl, -1) {
k = kg[1]
vi = data[k]
switch vi := vi.(type) {
case string:
vs = vi
case []byte:
vs = string(vi)
case int:
vs = strconv.FormatInt(int64(vi), 10)
case int64:
vs = strconv.FormatInt(vi, 10)
case float64:
vs = strconv.FormatFloat(vi, 'f', -1, 64)
}
tpl = strings.ReplaceAll(tpl, "${"+k+"}", vs)
}
return tpl
}
var (
urlMaskingRegexp = regexp.MustCompile(`(\S+:)\S+(@\w+)`)
)
// URLMasking masking password in url
func URLMasking(url, mask string) string {
return urlMaskingRegexp.ReplaceAllString(url, `${1}`+mask+`${2}`)
}
// SetStructFieldsBySlice set field value of structs slice by values slice
func SetStructFieldsBySlice(structs, vals any) (err error) {
sv := reflect.ValueOf(structs)
vv := reflect.ValueOf(vals)
typeCheck := func(name string, v *reflect.Value) error {
switch v.Kind() {
case reflect.Slice:
case reflect.Array:
default:
return errors.Errorf(name + " must be array/slice")
}
return nil
}
if err = typeCheck("structs", &sv); err != nil {
return err
}
if err = typeCheck("vals", &vv); err != nil {
return err
}
var (
eachGrpValsV reflect.Value
iField, nFields int
)
for i := 0; i < Min(sv.Len(), vv.Len()); i++ {
eachGrpValsV = vv.Index(i)
if err = typeCheck("vals."+strconv.FormatInt(int64(i), 10), &eachGrpValsV); err != nil {
return err
}
switch sv.Index(i).Kind() {
case reflect.Ptr:
nFields = sv.Index(i).Elem().NumField()
default:
nFields = sv.Index(i).NumField()
}
for iField = 0; iField < Min(eachGrpValsV.Len(), nFields); iField++ {
switch sv.Index(i).Kind() {
case reflect.Ptr:
sv.Index(i).Elem().Field(iField).Set(eachGrpValsV.Index(iField))
default:
sv.Index(i).Field(iField).Set(eachGrpValsV.Index(iField))
}
}
}
return
}
// UniqueStrings remove duplicate string in slice
func UniqueStrings(vs []string) []string {
seen := make(map[string]struct{})
j := 0
for _, v := range vs {
if _, ok := seen[v]; !ok {
seen[v] = struct{}{}
vs[j] = v
j++
}
}
clear(vs[j:])
return vs[:j:j]
}
// RemoveEmpty remove duplicate string in slice
func RemoveEmpty(vs []string) (r []string) {
for _, v := range vs {
if strings.TrimSpace(v) != "" {
r = append(r, v)
}
}
return
}
// TrimEleSpaceAndRemoveEmpty remove duplicate string in slice
func TrimEleSpaceAndRemoveEmpty(vs []string) (r []string) {
for _, v := range vs {
v = strings.TrimSpace(v)
if v != "" {
r = append(r, v)
}
}
return
}
// Contains if collection contains ele
func Contains[V comparable](collection []V, ele V) bool {
return slices.Contains(collection, ele)
}
// IsPtr check if t is pointer
func IsPtr(t any) bool {
return reflect.TypeOf(t).Kind() == reflect.Ptr
}
var reInvalidCMDChars = regexp.MustCompile(`[;&|]`)
// SanitizeCMDArgs sanitizes the given command arguments.
func SanitizeCMDArgs(args []string) (sanitizedArgs []string, err error) {
for i, arg := range args {
// Check for invalid characters using a regular expression
if reInvalidCMDChars.MatchString(arg) {
return nil, errors.New("invalid characters in args")
}
// Check for command substitution
if strings.Contains(arg, "$(") || strings.Contains(arg, "`") {
return nil, errors.New("invalid command substitution in args")
}
// Trim leading and trailing whitespace
args[i] = strings.TrimSpace(arg)
}
return args, nil
}
// RunCMD run command script
func RunCMD(ctx context.Context, app string, args ...string) (stdout []byte, err error) {
return RunCMDWithEnv(ctx, app, args, nil)
}
// RunCMDWithEnv run command with environments
//
// # Args
// - envs: []string{"FOO=BAR"}
func RunCMDWithEnv(ctx context.Context, app string,
args []string, envs []string) (stdout []byte, err error) {
cmd := exec.CommandContext(ctx, app, args...)
if len(envs) != 0 {
cmd.Env = append(cmd.Env, envs...)
}
stdout, err = cmd.CombinedOutput()
if err != nil {
cmd := strings.Join(append([]string{app}, args...), " ")
return stdout, errors.Wrapf(err, "run %q got %q", cmd, stdout)
}
return stdout, nil
}
// RunCMD2 run command script and handle stdout/stderr by pipe
func RunCMD2(ctx context.Context, app string,
args []string, envs []string,
stdoutHandler, stderrHandler func(string),
) (err error) {
cmd := exec.CommandContext(ctx, app, args...)
cmd.Env = append(cmd.Env, envs...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return errors.Wrap(err, "get stdout")
}
stderr, err := cmd.StderrPipe()
if err != nil {
return errors.Wrap(err, "get stderr")
}
if stdoutHandler == nil {
stdoutHandler = func(s string) {
log.Shared.Debug("run cmd", zap.String("msg", s), zap.String("app", app))
}
}
if stderrHandler == nil {
stderrHandler = func(s string) {
log.Shared.Error("run cmd", zap.String("msg", s), zap.String("app", app))
}
}
if err := cmd.Start(); err != nil {
return errors.Wrap(err, "start cmd")
}
go func() {
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
out := scanner.Text()
stdoutHandler(out)
}
if err := scanner.Err(); err != nil {
log.Shared.Warn("read stdout", zap.Error(err))
}
}()
go func() {
scanner := bufio.NewScanner(stderr)
for scanner.Scan() {
out := scanner.Text()
stderrHandler(out)
}
if err := scanner.Err(); err != nil {
log.Shared.Warn("read stderr", zap.Error(err))
}
}()
if err := cmd.Wait(); err != nil {
return errors.Wrap(err, "wait cmd")
}
return nil
}
// EncodeByBase64 encode bytes to string by base64
func EncodeByBase64(raw []byte) string {
return base64.URLEncoding.EncodeToString(raw)
}
// DecodeByBase64 decode string to bytes by base64
func DecodeByBase64(encoded string) ([]byte, error) {
return base64.URLEncoding.DecodeString(encoded)
}
var (
// EncodeByHex encode bytes to string by hex
EncodeByHex = hex.EncodeToString
// DecodeByHex decode string to bytes by hex
DecodeByHex = hex.DecodeString
)
// ConvertMap2StringKey convert any map to `map[string]any`
func ConvertMap2StringKey(inputMap any) map[string]any {
v := reflect.ValueOf(inputMap)
if v.Kind() != reflect.Map {
return nil
}
m2 := map[string]any{}
ks := v.MapKeys()
for _, k := range ks {
if k.Kind() == reflect.Interface {
m2[k.Elem().String()] = v.MapIndex(k).Interface()
} else {
m2[fmt.Sprint(k)] = v.MapIndex(k).Interface()
}
}
return m2
}
// func CalculateCRC(cnt []byte) {
// cw := crc64.New(crc64.MakeTable(crc64.ISO))
// }
// IsPanic is `f()` throw panic
//
// if you want to get the data throwed by panic, use `IsPanic2`
func IsPanic(f func()) (isPanic bool) {
defer func() {
if deferErr := recover(); deferErr != nil {
isPanic = true
}
}()
f()
return false
}
// IsPanic2 check is `f()` throw panic, and return panic as error
func IsPanic2(f func()) (err error) {
defer func() {
if panicRet := recover(); panicRet != nil {
err = errors.Errorf("panic: %v", panicRet)
}
}()
f()
return nil
}
var onlyOneSignalHandler = make(chan struct{})
type stopSignalOpt struct {
closeSignals []os.Signal
// closeFunc func()
}
// StopSignalOptFunc options for StopSignal
type StopSignalOptFunc func(*stopSignalOpt)
// WithStopSignalCloseSignals set signals that will trigger close
func WithStopSignalCloseSignals(signals ...os.Signal) StopSignalOptFunc {
if len(signals) == 0 {
log.Shared.Panic("signals cannot be empty")
}
return func(opt *stopSignalOpt) {
opt.closeSignals = signals
}
}
// // WithStopSignalCloseFunc set func that will be called when signal is triggered
// func WithStopSignalCloseFunc(f func()) StopSignalOptFunc {
// if f == nil {
// log.Shared.Panic("f cannot be nil")
// }
// return func(opt *stopSignalOpt) {
// opt.closeFunc = f
// }
// }
// StopSignal registered for SIGTERM and SIGINT. A stop channel is returned
// which is closed on one of these signals. If a second signal is caught, the program
// is terminated with exit code 1.
//
// Copied from https://github.com/kubernetes/sample-controller
func StopSignal(optfs ...StopSignalOptFunc) (stopCh <-chan struct{}) {
opt := &stopSignalOpt{
closeSignals: []os.Signal{syscall.SIGTERM, syscall.SIGINT},
// closeFunc: func() { os.Exit(1) },
}
for _, optf := range optfs {
optf(opt)
}
close(onlyOneSignalHandler) // panics when called twice
stop := make(chan struct{})
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)
go func() {
<-c
close(stop)
}()
return stop
}
// PanicIfErr panic if err is not nil
func PanicIfErr(err error) {
if err != nil {
panic(err)
}
}
// GracefulCancel is a function that will be called when the process is about to be terminated.
func GracefulCancel(cancel func()) {
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
cancel()
}
// EmptyAllChans receive all thins in all chans
func EmptyAllChans[T any](chans ...chan T) {
for _, c := range chans {
for range c { //nolint: revive
}
}
}
type prettyBuildInfoOption struct {
withDeps bool
}
func (o *prettyBuildInfoOption) apply(fs ...PrettyBuildInfoOption) *prettyBuildInfoOption {
for _, f := range fs {
f(o)
}
return o
}
// PrettyBuildInfoOption options for PrettyBuildInfo
type PrettyBuildInfoOption func(*prettyBuildInfoOption)
// WithPrettyBuildInfoDeps include deps in build info
func WithPrettyBuildInfoDeps() PrettyBuildInfoOption {
return func(opt *prettyBuildInfoOption) {
opt.withDeps = true
}
}
// PrettyBuildInfo get build info in formatted json
//
// Print:
//
// {
// "Path": "github.com/Laisky/go-ramjet",
// "Version": "v0.0.0-20220718014224-2b10e57735f1",
// "Sum": "h1:08Ty2gR+Xxz0B3djHVuV71boW4lpNdQ9hFn4ZIGrhec=",
// "Replace": null
// }
func PrettyBuildInfo(opts ...PrettyBuildInfoOption) string {