feat: useable

This commit is contained in:
Samuel N Cui
2022-12-12 22:48:28 +08:00
parent af8c37b18e
commit f87ec06af6
134 changed files with 18715 additions and 1343 deletions
+25
View File
@@ -0,0 +1,25 @@
package tools
import (
"context"
"io"
"os/exec"
)
func RunCommand(ctx context.Context, name string, args []string, stdin io.Reader, stdout, stderr io.Writer) (<-chan error, error) {
cmd := exec.CommandContext(ctx, name, args...)
cmd.Stdin = stdin
cmd.Stdout = stdout
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
return nil, err
}
ch := make(chan error, 1)
go func() {
ch <- cmd.Wait()
}()
return ch, nil
}
+28
View File
@@ -0,0 +1,28 @@
package tools
import (
"fmt"
"syscall"
)
type FileSystem struct {
TypeName string
MountPoint string
TotalSize int64
AvailableSize int64
}
func GetFileSystem(path string) (*FileSystem, error) {
stat := new(syscall.Statfs_t)
if err := syscall.Statfs(path, stat); err != nil {
return nil, fmt.Errorf("read statfs fail, err= %w", err)
}
return &FileSystem{
// TypeName: UnpaddingInt8s(stat.Fstypename[:]),
// MountPoint: UnpaddingInt8s(stat.Mntonname[:]),
TotalSize: int64(stat.Blocks) * int64(stat.Bsize),
AvailableSize: int64(stat.Bavail) * int64(stat.Bsize),
}, nil
}
+16
View File
@@ -0,0 +1,16 @@
package tools
import (
"testing"
"github.com/davecgh/go-spew/spew"
)
func TestGetFileSystem(t *testing.T) {
fs, err := GetFileSystem("/")
if err != nil {
panic(err)
}
t.Log(spew.Sdump(fs))
}
+32
View File
@@ -0,0 +1,32 @@
package tools
import (
"net/http"
"net/http/pprof"
"strings"
"github.com/sirupsen/logrus"
)
// NewDebugServer .
func NewDebugServer(addr string) {
debugMux := http.NewServeMux()
debugMux.HandleFunc("/debug/pprof/", pprof.Index)
debugMux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
debugMux.HandleFunc("/debug/pprof/profile", pprof.Profile)
debugMux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
debugMux.HandleFunc("/debug/pprof/trace", pprof.Trace)
if err := http.ListenAndServe(addr, debugMux); err != nil {
if err == nil {
return
}
if strings.Contains(err.Error(), "interrupt") {
return
}
logrus.WithError(err).Errorf("debug server listen and serve fail: addr= %s", addr)
}
}
+30
View File
@@ -0,0 +1,30 @@
package tools
import (
"context"
"fmt"
"runtime/debug"
"github.com/sirupsen/logrus"
)
func Wrap(ctx context.Context, f func()) {
defer func() {
e := recover()
if e == nil {
return
}
var err error
switch v := e.(type) {
case error:
err = v
default:
err = fmt.Errorf("%v", err)
}
logrus.WithContext(ctx).WithError(err).Errorf("panic: %s", debug.Stack())
}()
f()
}
+14
View File
@@ -0,0 +1,14 @@
package tools
func UnpaddingInt8s(buf []int8) string {
result := make([]byte, 0, len(buf))
for _, c := range buf {
if c == 0x00 {
break
}
result = append(result, byte(c))
}
return string(result)
}