status.go 1.4 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
//EXPIRE 过期时间
Y
Your Name 已提交
11 12 13
const EXPIRE = time.Second * 10

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

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

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

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

	m.locker.Unlock()
}

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

	m.locker.Lock()

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

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

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

Y
Your Name 已提交
55
//NodeStop 停止节点
Y
Your Name 已提交
56 57
func NodeStop(ip, port string) {
	id := fmt.Sprintf("%s:%d", ip, port)
E
eoLinker API Management 已提交
58 59 60
	manager.stop(id)
}

Y
Your Name 已提交
61
//IsLive 是否正常
Y
Your Name 已提交
62 63 64 65
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 已提交
66 67 68
		return false
	}

Y
Your Name 已提交
69
	if time.Now().Sub(t) > EXPIRE {
E
eoLinker API Management 已提交
70 71 72 73
		return false
	}
	return true
}
Y
Your Name 已提交
74 75

//ResetNodeStatus 重置节点状态
Y
Your Name 已提交
76 77
func ResetNodeStatus(nodes ...*entity.Node) {
	for _, node := range nodes {
E
eoLinker API Management 已提交
78

Y
Your Name 已提交
79
		if IsLive(node.NodeIP, node.NodePort) {
E
eoLinker API Management 已提交
80
			node.NodeStatus = 1
Y
Your Name 已提交
81
		} else {
E
eoLinker API Management 已提交
82 83 84
			node.NodeStatus = 0
		}
	}
Y
Your Name 已提交
85
}