-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
285 lines (235 loc) · 7.87 KB
/
service.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package admin
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"time"
"github.com/savannahghi/onboarding/pkg/onboarding/application/extension"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel"
"github.com/savannahghi/enumutils"
"github.com/savannahghi/firebasetools"
"github.com/savannahghi/onboarding/pkg/onboarding/application/utils"
"github.com/savannahghi/onboarding/pkg/onboarding/domain"
)
var tracer = otel.Tracer("github.com/savannahghi/onboarding/pkg/onboarding/usecases/admin")
const (
validURLSchema = "https"
validGraphEndpoinTail = "/graphql"
invalidGraphEndpoint = "Invalid graph detected. Please add a endpoint that ends with > graphql"
)
// Usecase ...
type Usecase interface {
RegisterMicroservice(
ctx context.Context,
input domain.Microservice,
) (*domain.Microservice, error)
ListMicroservices(ctx context.Context) ([]*domain.Microservice, error)
DeregisterMicroservice(ctx context.Context, id string) (bool, error)
DeregisterAllMicroservices(ctx context.Context) (bool, error)
FindMicroserviceByID(ctx context.Context, id string) (*domain.Microservice, error)
PollMicroservicesStatus(ctx context.Context) ([]*domain.MicroserviceStatus, error)
}
// Service is an admin tools service e.g for registering and deregistering micro-services
type Service struct {
baseExt extension.BaseExtension
}
// NewService initializes a valid OTP service
func NewService(ext extension.BaseExtension) *Service {
return &Service{
baseExt: ext,
}
}
// CheckPreconditions ...
func (s *Service) CheckPreconditions() {
if s.baseExt == nil {
log.Panicf("admin service infrastructure is nil")
}
}
// RegisterMicroservice registers a micro-service
func (s *Service) RegisterMicroservice(
ctx context.Context,
input domain.Microservice,
) (*domain.Microservice, error) {
s.CheckPreconditions()
ctx, span := tracer.Start(ctx, "RegisterMicroservice")
defer span.End()
//validate endpoint
parseURL, err := url.Parse(input.URL)
if err != nil {
utils.RecordSpanError(span, err)
return nil, fmt.Errorf("expected a valid URL, Found %v ", input.URL)
}
if parseURL.Scheme != validURLSchema {
return nil, fmt.Errorf("expected a secure URL, Found %v ", input.URL)
}
if parseURL.Path != validGraphEndpoinTail {
return nil, fmt.Errorf("%v", invalidGraphEndpoint)
}
endPoint, err := utils.ServiceHealthEndPoint(input.URL)
if err != nil {
utils.RecordSpanError(span, err)
return nil, fmt.Errorf("%s url is incorrect", input.Name)
}
if !s.CheckHealthEndpoint(ctx, endPoint) {
return nil, fmt.Errorf("%s service is not online", input.Name)
}
// check if the service exists first
filter := &firebasetools.FilterInput{
FilterBy: []*firebasetools.FilterParam{
{
FieldName: "url",
FieldType: enumutils.FieldTypeString,
ComparisonOperation: enumutils.OperationEqual,
FieldValue: input.URL,
},
},
}
existing, _, err := firebasetools.QueryNodes(ctx, nil, filter, nil, &domain.Microservice{})
if err != nil {
utils.RecordSpanError(span, err)
return nil, fmt.Errorf("unable to query microservices: %w", err)
}
if len(existing) > 0 {
return nil, fmt.Errorf("a service(s) with the URL %s is already registered", input.URL)
}
node := &domain.Microservice{
Name: input.Name,
URL: input.URL,
Description: input.Description,
}
id, _, err := firebasetools.CreateNode(ctx, node)
if err != nil {
utils.RecordSpanError(span, err)
return nil, fmt.Errorf("unable to register microservice: %w", err)
}
node.SetID(id)
return node, nil
}
//CheckHealthEndpoint Check if service is reachable
func (s Service) CheckHealthEndpoint(ctx context.Context, healthEndpoint string) bool {
ctx, span := tracer.Start(ctx, "CheckHealthEndpoint")
defer span.End()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, healthEndpoint, nil)
if err != nil {
log.Printf("Failed to create action request with error; %v", err)
return false
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("Connection", "keep-alive")
c := &http.Client{Timeout: time.Second * 300}
resp, err := c.Do(req)
if err != nil {
log.Print(err)
return false
}
defer resp.Body.Close()
var b bool
/* #nosec*/
json.NewDecoder(resp.Body).Decode(&b)
if resp.StatusCode == http.StatusOK && b {
return true
}
return false
}
// ListMicroservices returns all registered micro-services
func (s *Service) ListMicroservices(ctx context.Context) ([]*domain.Microservice, error) {
s.CheckPreconditions()
ctx, span := tracer.Start(ctx, "ListMicroservices")
defer span.End()
docs, _, err := firebasetools.QueryNodes(ctx, nil, nil, nil, &domain.Microservice{})
if err != nil {
utils.RecordSpanError(span, err)
return nil, fmt.Errorf("unable to query microservices: %w", err)
}
services := []*domain.Microservice{}
for _, doc := range docs {
service := &domain.Microservice{}
err = doc.DataTo(service)
if err != nil {
utils.RecordSpanError(span, err)
return nil, fmt.Errorf("unable to unmarshal Firebase doc to microservice: %w", err)
}
services = append(services, service)
}
return services, nil
}
// DeregisterMicroservice removes a micro-service
func (s *Service) DeregisterMicroservice(ctx context.Context, id string) (bool, error) {
s.CheckPreconditions()
ctx, span := tracer.Start(ctx, "DeregisterMicroservice")
defer span.End()
return firebasetools.DeleteNode(ctx, id, &domain.Microservice{})
}
// DeregisterAllMicroservices removes all services at once. This is called internally when running in CLI mode
func (s *Service) DeregisterAllMicroservices(ctx context.Context) (bool, error) {
s.CheckPreconditions()
ctx, span := tracer.Start(ctx, "DeregisterAllMicroservices")
defer span.End()
services, err := s.ListMicroservices(ctx)
if err != nil {
utils.RecordSpanError(span, err)
return false, fmt.Errorf("unable to list all microservices: %w", err)
}
successCount := 0
for _, srv := range services {
_, err := firebasetools.DeleteNode(ctx, srv.ID, &domain.Microservice{})
if err != nil {
utils.RecordSpanError(span, err)
// silent
logrus.Errorf("failed to remove %v with error : %v", srv.Name, err)
}
successCount++
}
if successCount == len(services) {
return true, nil
}
// not fatal. Recreation will happen in the next step of CLI mode
return false, fmt.Errorf("unable to deregister all services")
}
// FindMicroserviceByID retrieves a micro-service by it's ID
func (s *Service) FindMicroserviceByID(ctx context.Context, id string) (*domain.Microservice, error) {
s.CheckPreconditions()
ctx, span := tracer.Start(ctx, "FindMicroserviceByID")
defer span.End()
node, err := firebasetools.RetrieveNode(ctx, id, &domain.Microservice{})
if err != nil {
utils.RecordSpanError(span, err)
return nil, fmt.Errorf("can't get microservice with ID %s: %w", id, err)
}
service, ok := node.(*domain.Microservice)
if !ok {
return nil, fmt.Errorf("can't convert retrieved node to *Microservice")
}
return service, nil
}
// PollMicroservicesStatus checks if the registered microservices are serving HTTP requests/ healthy
func (s *Service) PollMicroservicesStatus(ctx context.Context) ([]*domain.MicroserviceStatus, error) {
s.CheckPreconditions()
ctx, span := tracer.Start(ctx, "PollMicroservicesStatus")
defer span.End()
services, err := s.ListMicroservices(ctx)
if err != nil {
utils.RecordSpanError(span, err)
return nil, fmt.Errorf("can't get registered microservices")
}
statuses := []*domain.MicroserviceStatus{}
for _, service := range services {
url, err := utils.ServiceHealthEndPoint(service.URL)
if err != nil {
utils.RecordSpanError(span, err)
return nil, fmt.Errorf("cannot form health url: %v", err)
}
reachable := s.CheckHealthEndpoint(ctx, url)
status := &domain.MicroserviceStatus{
Service: service,
Active: reachable,
}
statuses = append(statuses, status)
}
return statuses, nil
}