status.go 1.3 KB
Newer Older
E
eoLinker API Management 已提交
1 2 3 4
package node

import (
	"fmt"
黄孟柱 已提交
5
	entity "github.com/eolinker/goku-api-gateway/server/entity/console-entity"
E
eoLinker API Management 已提交
6 7 8 9
	"sync"
	"time"
)

Y
Your Name 已提交
10 11 12
const EXPIRE = time.Second * 10

var (
E
eoLinker API Management 已提交
13
	manager = _StatusManager{
Y
Your Name 已提交
14 15
		locker:        sync.RWMutex{},
		lastHeartBeat: make(map[string]time.Time),
E
eoLinker API Management 已提交
16 17
	}
)
Y
Your Name 已提交
18

E
eoLinker API Management 已提交
19
type _StatusManager struct {
Y
Your Name 已提交
20
	locker        sync.RWMutex
E
eoLinker API Management 已提交
21 22 23
	lastHeartBeat map[string]time.Time
}

Y
Your Name 已提交
24 25
func (m *_StatusManager) refresh(id string) {
	t := time.Now()
E
eoLinker API Management 已提交
26 27
	m.locker.Lock()

Y
Your Name 已提交
28
	m.lastHeartBeat[id] = t
E
eoLinker API Management 已提交
29 30 31 32

	m.locker.Unlock()
}

Y
Your Name 已提交
33
func (m *_StatusManager) stop(id string) {
E
eoLinker API Management 已提交
34 35 36

	m.locker.Lock()

Y
Your Name 已提交
37
	delete(m.lastHeartBeat, id)
E
eoLinker API Management 已提交
38 39 40

	m.locker.Unlock()
}
Y
Your Name 已提交
41
func (m *_StatusManager) get(id string) (time.Time, bool) {
E
eoLinker API Management 已提交
42
	m.locker.RLock()
Y
Your Name 已提交
43
	t, b := m.lastHeartBeat[id]
E
eoLinker API Management 已提交
44
	m.locker.RUnlock()
Y
Your Name 已提交
45
	return t, b
E
eoLinker API Management 已提交
46 47
}

Y
Your Name 已提交
48 49
func Refresh(ip string, port string) {
	id := fmt.Sprintf("%s:%d", ip, port)
E
eoLinker API Management 已提交
50 51 52
	manager.refresh(id)
}

Y
Your Name 已提交
53 54
func NodeStop(ip, port string) {
	id := fmt.Sprintf("%s:%d", ip, port)
E
eoLinker API Management 已提交
55 56 57
	manager.stop(id)
}

Y
Your Name 已提交
58 59 60 61
func IsLive(ip string, port string) bool {
	id := fmt.Sprintf("%s:%d", ip, port)
	t, has := manager.get(id)
	if !has {
E
eoLinker API Management 已提交
62 63 64
		return false
	}

Y
Your Name 已提交
65
	if time.Now().Sub(t) > EXPIRE {
E
eoLinker API Management 已提交
66 67 68 69
		return false
	}
	return true
}
Y
Your Name 已提交
70 71
func ResetNodeStatus(nodes ...*entity.Node) {
	for _, node := range nodes {
E
eoLinker API Management 已提交
72

Y
Your Name 已提交
73
		if IsLive(node.NodeIP, node.NodePort) {
E
eoLinker API Management 已提交
74
			node.NodeStatus = 1
Y
Your Name 已提交
75
		} else {
E
eoLinker API Management 已提交
76 77 78
			node.NodeStatus = 0
		}
	}
Y
Your Name 已提交
79
}