/
node_repo.go
107 lines (85 loc) · 2.35 KB
/
node_repo.go
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package node
import (
"context"
"net/http"
"strconv"
"strings"
"github.com/egfanboy/mediapire-common/exceptions"
"github.com/egfanboy/mediapire-manager/internal/app"
"github.com/egfanboy/mediapire-manager/internal/consul"
"github.com/google/uuid"
"github.com/hashicorp/consul/api"
)
func nodeConfigFromConsul(source *api.AgentService, status string) (NodeConfig, error) {
nodeId, err := uuid.Parse(source.ID)
if err != nil {
return NodeConfig{}, err
}
cfg := NodeConfig{
NodeHost: source.Address,
NodePort: strconv.Itoa(source.Port),
NodeScheme: source.Meta[consul.KeyScheme],
Id: nodeId,
}
if status == api.HealthCritical {
cfg.IsUp = false
} else {
cfg.IsUp = true
}
return cfg, nil
}
type NodeRepo interface {
GetAllNodes(ctx context.Context) ([]NodeConfig, error)
GetNode(ctx context.Context, nodeId uuid.UUID) (NodeConfig, error)
}
type consulRepo struct {
app *app.App
client *api.Client
}
func (r *consulRepo) GetAllNodes(ctx context.Context) (result []NodeConfig, err error) {
result = make([]NodeConfig, 0)
services, err := r.client.Agent().ServicesWithFilter("Service == \"media-host-node\"")
if err != nil {
return
}
for _, service := range services {
status, _, errHealth := r.client.Agent().AgentHealthServiceByID(service.ID)
if errHealth != nil {
err = errHealth
return
}
cfg, err := nodeConfigFromConsul(service, status)
if err != nil {
return nil, err
}
result = append(result, cfg)
}
return
}
func (r *consulRepo) GetNode(ctx context.Context, nodeId uuid.UUID) (NodeConfig, error) {
service, _, err := r.client.Agent().Service(nodeId.String(), &api.QueryOptions{UseCache: false})
if err != nil {
if strings.Contains(err.Error(), "404") {
return NodeConfig{}, &exceptions.ApiException{
Err: err, StatusCode: http.StatusNotFound,
}
}
return NodeConfig{}, &exceptions.ApiException{
Err: err, StatusCode: http.StatusInternalServerError,
}
}
status, _, err := r.client.Agent().AgentHealthServiceByID(service.ID)
if err != nil {
return NodeConfig{}, &exceptions.ApiException{
Err: err, StatusCode: http.StatusInternalServerError,
}
}
return nodeConfigFromConsul(service, status)
}
func NewNodeRepo() (NodeRepo, error) {
consul, err := consul.GetClient()
if err != nil {
return nil, err
}
return &consulRepo{app: app.GetApp(), client: consul}, nil
}