/
bridge.go
103 lines (87 loc) · 2.18 KB
/
bridge.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
package main
import (
"log"
"os"
"strings"
"sync"
dockerapi "github.com/fsouza/go-dockerclient"
)
type Job struct {
ID string // the hostname:containerid combo or FLEETSTREET_NAME env
IP string // the IP of the docker host
Container *dockerapi.Container // the stringified container data
}
func defaultJobName(container *dockerapi.Container) string {
hostname, err := os.Hostname()
if err != nil {
hostname = *hostIp
}
return hostname + ":" + container.ID
}
func jobName(container *dockerapi.Container) string {
name := defaultJobName(container)
hit := false
for _, kv := range container.Config.Env {
kvp := strings.SplitN(kv, "=", 2)
if kvp[0] == *varName {
name = kvp[1]
hit = true
}
}
if *requireVarName && !hit {
name = ""
}
return name
}
func NewJob(container *dockerapi.Container) *Job {
log.Println("fleetstreet: new job", container.ID)
job := new(Job)
job.ID = jobName(container)
job.IP = *hostIp
job.Container = container
return job
}
type RegistryBridge struct {
sync.Mutex
docker *dockerapi.Client
registry ServiceRegistry
jobs map[string][]*Job
}
func (b *RegistryBridge) Add(containerId string) {
b.Lock()
defer b.Unlock()
container, err := b.docker.InspectContainer(containerId)
if err != nil {
log.Println("fleetstreet: unable to inspect container:", containerId, err)
return
}
job := NewJob(container)
if(job.ID == "" ){
log.Println("fleetstreet: non-published container:", containerId)
return
}
err = retry(func() error {
return b.registry.Register(job)
})
if err != nil {
log.Println("fleetstreet: unable to register container:", job, err)
return
}
b.jobs[container.ID] = append(b.jobs[container.ID], job)
log.Println("fleetstreet: added:", container.ID[:12], job.ID)
}
func (b *RegistryBridge) Remove(containerId string) {
b.Lock()
defer b.Unlock()
for _, job := range b.jobs[containerId] {
err := retry(func() error {
return b.registry.Deregister(job)
})
if err != nil {
log.Println("fleetstreet: unable to deregister job:", job.ID, err)
continue
}
log.Println("fleetstreet: removed:", containerId[:12], job.ID)
}
delete(b.jobs, containerId)
}