dtm/dtmsvr/utils.go
2021-07-31 11:45:14 +08:00

81 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package dtmsvr
import (
"encoding/hex"
"fmt"
"net"
"strings"
"github.com/bwmarrin/snowflake"
"github.com/sirupsen/logrus"
"github.com/yedf/dtm/common"
)
// M a short name
type M = map[string]interface{}
var p2e = common.P2E
var e2p = common.E2P
func dbGet() *common.DB {
return common.DbGet(config.DB)
}
func writeTransLog(gid string, action string, status string, branch string, detail string) {
// if detail == "" {
// detail = "{}"
// }
// dbGet().Must().Table("trans_log").Create(M{
// "gid": gid,
// "action": action,
// "new_status": status,
// "branch": branch,
// "detail": detail,
// })
}
// TransProcessedTestChan only for test usage. when transaction processed once, write gid to this chan
var TransProcessedTestChan chan string = nil
// WaitTransProcessed only for test usage. wait for transaction processed once
func WaitTransProcessed(gid string) {
logrus.Printf("waiting for gid %s", gid)
id := <-TransProcessedTestChan
for id != gid {
logrus.Errorf("-------id %s not match gid %s", id, gid)
id = <-TransProcessedTestChan
}
logrus.Printf("finish for gid %s", gid)
}
var gNode *snowflake.Node = nil
func init() {
node, err := snowflake.NewNode(1)
e2p(err)
gNode = node
}
// GenGid generate gid, use ip + snowflake
func GenGid() string {
return getOneHexIP() + "_" + gNode.Generate().Base58()
}
func getOneHexIP() string {
addrs, err := net.InterfaceAddrs()
if err == nil {
for _, address := range addrs {
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil {
ip := ipnet.IP.To4().String()
ns := strings.Split(ip, ".")
r := []byte{}
for _, n := range ns {
r = append(r, byte(common.MustAtoi(n)))
}
return hex.EncodeToString(r)
}
}
}
fmt.Printf("err is: %s", err.Error())
return "" // 获取不到IP则直接返回空
}