This repository has been archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
registrator.go
92 lines (77 loc) · 2.52 KB
/
registrator.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
// Copyright 2014-2016 Fraunhofer Institute for Applied Information Technology FIT
package client
import (
"fmt"
"sync"
"time"
"code.linksmart.eu/com/go-sec/auth/obtainer"
"code.linksmart.eu/sc/service-catalog/catalog"
)
// RegisterService registers service into a catalog
func RegisterService(endpoint string, service catalog.Service, ticket *obtainer.Client) (*catalog.Service, error) {
// Configure client
client, err := NewHTTPClient(endpoint, ticket)
if err != nil {
return nil, fmt.Errorf("error creating HTTP client: %s", err)
}
updatedService, err := client.Put(&service)
if err != nil {
return nil, fmt.Errorf("error PUTing registration: %v", err)
}
return updatedService, nil
}
// UnregisterService removes service from a catalog
func UnregisterService(endpoint string, service catalog.Service, ticket *obtainer.Client) error {
// Configure client
client, err := NewHTTPClient(endpoint, ticket)
if err != nil {
return fmt.Errorf("error creating HTTP client: %s", err)
}
err = client.Delete(service.ID)
if err != nil {
return fmt.Errorf("error PUTing registration: %v", err)
}
return nil
}
// RegisterServiceAndKeepalive registers a service into a catalog and continuously updates it in order to avoid expiry
// endpoint: catalog endpoint.
// service: service registration
// ticket: set to nil for no auth
// It returns a function for stopping the keepalive and another function for updating the service in keepalive routine
func RegisterServiceAndKeepalive(endpoint string, service catalog.Service, ticket *obtainer.Client) (func() error, func(catalog.Service), error) {
mutex := sync.RWMutex{}
client, err := NewHTTPClient(endpoint, ticket)
if err != nil {
return nil, nil, err
}
ticker := time.NewTicker(time.Duration(service.TTL/2) * time.Second)
go func() {
for ; true; <-ticker.C {
mutex.RLock()
_, err := client.Put(&service)
if err != nil {
logger.Printf("Error updating service registration for %s: %s", service.ID, err)
continue
}
mutex.RUnlock()
logger.Printf("Updated service registration for %s", service.ID)
}
}()
stop := func() error {
ticker.Stop()
mutex.RLock()
client.Delete(service.ID)
if err != nil {
logger.Printf("Error removing service registration for %s: %s", service.ID, err)
}
mutex.RUnlock()
return nil
}
update := func(updatedService catalog.Service) {
logger.Printf("Service registration for %s will be updated in the next heartbeat.", service.ID)
mutex.Lock()
service = updatedService
mutex.Unlock()
}
return stop, update, nil
}