File size: 1,283 Bytes
530729e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package trace

import (
	"fmt"
	"net"
	"os"
	"sync"
	"sync/atomic"
	"time"

	"github.com/GoAdminGroup/go-admin/context"
)

var (
	machineIDOnce sync.Once
	machineID     string
	counter       uint32
)

func getMachineID() string {
	machineIDOnce.Do(func() {
		addrs, err := net.InterfaceAddrs()
		if err == nil {
			for _, addr := range addrs {
				if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
					if ipNet.IP.To4() != nil {
						machineID = ipNet.IP.String()
						break
					}
				}
			}
		}

		if machineID == "" {
			machineID = "127.0.0.1"
		}
	})

	return machineID
}

func GenerateTraceID() string {
	machineID := getMachineID()
	timestamp := time.Now().UnixNano() / int64(time.Millisecond)
	processID := os.Getpid()
	id := atomic.AddUint32(&counter, 1)
	id = id % 1000
	traceID := fmt.Sprintf("%08x%05d%013d%04d", machineIDToHex(machineID), processID, timestamp, id)

	return traceID
}

func machineIDToHex(machineID string) uint32 {
	ip := net.ParseIP(machineID)
	ipUint32 := uint32(ip[12])<<24 | uint32(ip[13])<<16 | uint32(ip[14])<<8 | uint32(ip[15])
	return ipUint32
}

func GetTraceID(ctx *context.Context) string {
	traceID, ok := ctx.GetUserValue(TraceIDKey).(string)
	if !ok {
		return ""
	}
	return traceID
}

const (
	TraceIDKey = "traceID"
)