11package server
22
33import (
4- "errors"
54 "fmt"
65 "log"
7- "net"
86 "os"
97 "regexp"
108 "strconv"
@@ -44,6 +42,8 @@ func (s *Server) Listen(ttl time.Duration) {
4442 continue
4543 }
4644 s .publishContainer (container , ttl )
45+ } else if event .Status == "stop" {
46+ s .removeContainer (event .ID )
4747 }
4848 }
4949 }
@@ -73,7 +73,7 @@ func (s *Server) getContainer(id string) (*docker.APIContainers, error) {
7373 return & container , nil
7474 }
7575 }
76- return nil , errors . New ("could not find container" )
76+ return nil , fmt . Errorf ("could not find container with id %v" , id )
7777}
7878
7979// publishContainer publishes the docker container to etcd.
@@ -89,19 +89,35 @@ func (s *Server) publishContainer(container *docker.APIContainers, ttl time.Dura
8989 continue
9090 }
9191 appName := match [1 ]
92- keyPath := fmt .Sprintf ("/deis/services/%s/%s" , appName , containerName )
92+ appPath := fmt .Sprintf ("%s/%s" , appName , containerName )
93+ keyPath := fmt .Sprintf ("/deis/services/%s" , appPath )
9394 for _ , p := range container .Ports {
9495 port := strconv .Itoa (int (p .PublicPort ))
9596 hostAndPort := host + ":" + port
9697 if s .IsPublishableApp (containerName ) && s .IsPortOpen (hostAndPort ) {
9798 s .setEtcd (keyPath , hostAndPort , uint64 (ttl .Seconds ()))
99+ s .setEtcd ("/deis/publisher/containers/" + container .ID , appPath , uint64 (ttl .Seconds ()))
98100 }
99101 // TODO: support multiple exposed ports
100102 break
101103 }
102104 }
103105}
104106
107+ // removeContainer remove a container published by this component
108+ func (s * Server ) removeContainer (event string ) {
109+ containerPath := "/deis/publisher/containers/" + event
110+ appPath , err := s .getEtcd (containerPath )
111+ if err != nil {
112+ log .Println (err )
113+ return
114+ }
115+
116+ keyPath := fmt .Sprintf ("/deis/services/%s" , appPath )
117+ s .removeEtcd (keyPath , false )
118+ s .removeEtcd (containerPath , false )
119+ }
120+
105121// IsPublishableApp determines if the application should be published to etcd.
106122func (s * Server ) IsPublishableApp (name string ) bool {
107123 r := regexp .MustCompile (appNameRegex )
@@ -183,3 +199,21 @@ func (s *Server) setEtcd(key, value string, ttl uint64) {
183199 }
184200 log .Println ("set" , key , "->" , value )
185201}
202+
203+ func (s * Server ) getEtcd (key string ) (string , error ) {
204+ result , err := s .EtcdClient .Get (key , false , false )
205+ if err != nil {
206+ return "" , err
207+ }
208+
209+ log .Println ("get" , key , "->" , result .Node .Value )
210+ return result .Node .Value , nil
211+ }
212+
213+ // removeEtcd removes the corresponding etcd key
214+ func (s * Server ) removeEtcd (key string , recursive bool ) {
215+ if _ , err := s .EtcdClient .Delete (key , recursive ); err != nil {
216+ log .Println (err )
217+ }
218+ log .Println ("del" , key )
219+ }
0 commit comments