@@ -7,21 +7,17 @@ package main
77// ZSET and write changes to AWS Route53.
88
99import (
10- docker_router "redecs/docker_router"
1110 "errors"
1211 "fmt"
1312 log "github.com/Sirupsen/logrus"
1413 "github.com/aws/aws-sdk-go/aws/ec2metadata"
1514 "github.com/aws/aws-sdk-go/aws/session"
16- "github.com/fsouza/go-dockerclient"
1715 "gopkg.in/redis.v5"
1816 "os"
19- "strconv"
20- "strings"
2117 "time"
2218)
2319
24- const checkInterval = 30 * time .Second // how often to check Docker
20+ const reportInterval = 30 * time .Second // how often to report
2521
2622type config struct {
2723 LocalIp string
@@ -42,12 +38,11 @@ func logErrorNoFatal(err error) {
4238 }
4339}
4440
45- var dockerClient * docker.Client
4641var redisClient * redis.Client
4742
4843// This reports an instance as active. It adds it to the redecs:service_pings set
4944// and publishes a redecs:service_channel event.
50- func reportServiceActive (serviceName string ) error {
45+ func reportActiveService (serviceName string ) error {
5146 log .Debugf ("Reporting %s as active with IP %s" , serviceName , configuration .LocalIp )
5247 value := serviceName + "_" + configuration .LocalIp
5348 // write {timestamp => SERVICENAME_IP} to redecs:service_pings
@@ -60,65 +55,16 @@ func reportServiceActive(serviceName string) error {
6055 return err
6156}
6257
63- // This reports an instance as inactive. It removes it from the redecs:service_pings set
64- // and publishes a redecs:service_channel event.
65- func reportServiceInactive (serviceName string ) error {
66- log .Debugf ("Reporting %s as inactive with IP %s" , serviceName , configuration .LocalIp )
67- value := serviceName + "_" + configuration .LocalIp
68- // remove SERVICENAME_IP from redecs:service_pings
69- err := redisClient .ZRem ("redecs:service_pings" , value ).Err ()
70- if err != nil {
71- return err
72- }
73- // notify the channel that this service has been reported active
74- err = redisClient .Publish ("redecs:service_channel" , "-" + value ).Err ()
75- return err
76- }
77-
78- // Gets the service name from a Docker container environment variable, if present.
79- func getServiceName (container * docker.Container ) string {
80- // One of the environment variables should be SERVICE_<port>_NAME = <name of the service>
81- // We look for this environment variable doing a split in the "=" and another one in the "_"
82- // So envEval = [SERVICE_<port>_NAME, <name>]
83- // nameEval = [SERVICE, <port>, NAME]
84- for _ , env := range container .Config .Env {
85- envEval := strings .Split (env , "=" )
86- nameEval := strings .Split (envEval [0 ], "_" )
87- if len (envEval ) == 2 && len (nameEval ) == 3 && nameEval [0 ] == "SERVICE" && nameEval [2 ] == "NAME" {
88- if _ , err := strconv .Atoi (nameEval [1 ]); err == nil {
89- return envEval [1 ]
90- }
91- }
92- }
93- return ""
94- }
95-
96- func processContainers () {
97- log .Debug ("Listing active containers..." )
98-
99- // only get running ones
100- containers , err := dockerClient .ListContainers (docker.ListContainersOptions {All : false })
101- // bail out completely if we can't list containers.
102- logErrorAndFail (err )
103- for _ , containerEntry := range containers {
104- // have to inspect to get the environment variable
105- container , err := dockerClient .InspectContainer (containerEntry .ID )
106- // retry logic?
107- logErrorAndFail (err )
108- serviceName := getServiceName (container )
109- if serviceName != "" {
110- reportServiceActive (serviceName )
111- }
112- }
113-
114- log .Debug ("Done checking active containers" )
58+ // Gets the service name from the SERVICE_NAME environment variable.
59+ func getServiceName () string {
60+ return os .Getenv ("SERVICE_NAME" )
11561}
11662
11763func main () {
11864 var err error
11965 var sum int
12066 if len (os .Args ) < 2 || len (os .Args ) > 3 {
121- err = errors .New (fmt .Sprintf ("Usage: %s [Redis host] {host IP ( for testing) }\n " , os .Args [0 ]))
67+ err = errors .New (fmt .Sprintf ("Usage: %s [Redis host] {IP for testing purposes }\n " , os .Args [0 ]))
12268 logErrorAndFail (err )
12369 }
12470 if len (os .Args ) == 3 {
@@ -130,11 +76,12 @@ func main() {
13076 configuration .LocalIp = localIp
13177 }
13278 configuration .RedisHost = os .Args [1 ]
133- endpoint := "unix:///var/run/docker.sock"
134- dockerClient , err = docker .NewClient (endpoint )
13579
136- // bail out if we can't talk to Docker
137- logErrorAndFail (err )
80+ serviceName := getServiceName ()
81+ if serviceName == "" {
82+ err = errors .New ("'SERVICE_NAME' environment variable is not defined! Exiting." )
83+ logErrorAndFail (err )
84+ }
13885
13986 sum = 1
14087 for {
@@ -158,64 +105,13 @@ func main() {
158105 sum += 2
159106 }
160107
161- startFn := func (event * docker.APIEvents ) error {
162- var err error
163- container , err := dockerClient .InspectContainer (event .ID )
164- logErrorAndFail (err )
165- service := getServiceName (container )
166- if service != "" {
167- sum = 1
168- for {
169- if err = reportServiceActive (service ); err == nil {
170- break
171- }
172- if sum > 8 {
173- log .Errorf ("Error reporting service %s active" , service )
174- break
175- }
176- time .Sleep (time .Duration (sum ) * time .Second )
177- sum += 2
178- }
179- }
180- log .Debugf ("Docker %s started" , event .ID )
181- return nil
182- }
183-
184- stopFn := func (event * docker.APIEvents ) error {
185- var err error
186- container , err := dockerClient .InspectContainer (event .ID )
187- logErrorAndFail (err )
188- service := getServiceName (container )
189- if service != "" {
190- sum = 1
191- for {
192- if err = reportServiceInactive (service ); err == nil {
193- break
194- }
195- if sum > 8 {
196- log .Errorf ("Error reporting service %s inactive" , service )
197- break
198- }
199- time .Sleep (time .Duration (sum ) * time .Second )
200- sum += 2
201- }
202- }
203- log .Debugf ("Docker %s stopped" , event .ID )
204- return nil
205- }
206-
207- dockerRouter , err := docker_router .AddStartStopHandlers (startFn , stopFn , dockerClient )
208- defer dockerRouter .Stop ()
209- logErrorAndFail (err )
210- dockerRouter .Start ()
211-
212- log .Debug ("Waiting for Docker events" )
108+ log .Debug ("redecs_agent started" )
213109
214110 // continue processing once per minute
215- ticker := time .NewTicker (checkInterval )
111+ ticker := time .NewTicker (reportInterval )
216112
217113 for {
218- processContainers ( )
114+ reportActiveService ( serviceName )
219115 <- ticker .C
220116 }
221117}
0 commit comments