1616logging .getLogger ("docker" ).setLevel (logging .INFO )
1717
1818def getDockerHostFromContext ():
19+ """
20+ Get docker remote host uri from current docker context
21+ """
1922 current_context_cmd = subprocess .run (["docker" , "context" , "inspect" ], capture_output = True )
2023 current_context_json = json .loads (current_context_cmd .stdout .decode ())
2124 return current_context_json [0 ]["Endpoints" ]["docker" ]["Host" ]
2225
2326def manageProxies (remote_docker_host_name , published_ports , listen_system_ports ):
27+ """
28+ Manage proxy to publisher containers.
29+ Getting new published ports, stopping proxies for stopped containers (published ports)
30+ starting new proxies to new published ports
31+ """
2432 global ACTIVE_PROXIES
2533 # Get only tcp services because only tcp proxy implemented
2634 published_ports = list (x ["published" ] for x in published_ports if x ["internal" ].endswith ("tcp" ))
@@ -34,17 +42,22 @@ def manageProxies(remote_docker_host_name, published_ports, listen_system_ports)
3442 published_ports .remove (proxy .proxy_port )
3543 else :
3644 proxy .stop ()
37- # Add and start new proxies
38- for port in published_ports :
39- proxy = ProxyServer (remote_docker_host_name , port , ProxyType .TCP )
40- proxy .start ()
41- new_active_proxies .append (proxy )
42- # Update proxy list
43- ACTIVE_PROXIES = new_active_proxies
45+ try :
46+ # Add and start new proxies
47+ for port in published_ports :
48+ proxy = ProxyServer (remote_docker_host_name , port , ProxyType .TCP )
49+ proxy .start ()
50+ new_active_proxies .append (proxy )
51+ # Update proxy list
52+ finally :
53+ ACTIVE_PROXIES = new_active_proxies
4454
4555
4656
4757def mainLoop (docker_host , listen_system_ports , use_docker_cli ):
58+ """
59+ Main loop where getting published ports and launch managing proxies with 60s intervals
60+ """
4861 global ACTIVE_PROXIES
4962 logging .info ("Initialize docker remote proxy to `%s`" % docker_host )
5063 docker_service = DockerService (docker_host , use_docker_cli )
@@ -59,10 +72,12 @@ def mainLoop(docker_host, listen_system_ports, use_docker_cli):
5972 logging .error (e )
6073 time .sleep (60 )
6174 except KeyboardInterrupt :
75+ return
76+ finally :
6277 for proxy in ACTIVE_PROXIES :
6378 proxy .stop ()
6479 logging .info ('Docker remote proxy stopped!' )
65- return
80+
6681
6782if __name__ == "__main__" :
6883 logging .info ('Starting docker remote proxy!' )
0 commit comments