-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswarm.py
More file actions
77 lines (69 loc) · 2.45 KB
/
Copy pathswarm.py
File metadata and controls
77 lines (69 loc) · 2.45 KB
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
import docker
import docker.errors
try:
from kazoo.client import KazooClient
except ImportError:
print("Kazoo library not found, Zookeeper connect URLs will not work")
KazooClient = None
class SwarmClient:
def __init__(self, swarm_url):
assert isinstance(swarm_url, str)
self.cli = None
self._connect(swarm_url)
assert self.cli is not None
def _connect(self, swarm_url):
if swarm_url.startswith('tcp://'):
self._connect_tcp(swarm_url)
elif swarm_url.startswith('zk://'):
self._connect_zookeeper(swarm_url)
else:
print("Unknown connection URL schema")
return
def _connect_zookeeper(self, zk_url):
"""
Find the active Swarm master using Zookeeper
"""
aux = zk_url[len('zk://'):]
zk_hosts = aux.split('/')[0]
path = aux[aux.find('/'):] + '/docker/swarm/leader'
zk = KazooClient(hosts=zk_hosts)
zk.start()
master, stat = zk.get(path)
zk.stop()
self._connect_tcp('tcp://' + master.decode('ascii'))
def _connect_tcp(self, tcp_url):
self.cli = docker.Client(base_url=tcp_url)
print("Connected to Swarm at {}".format(tcp_url))
def manage_event(self, callback):
for event in self.cli.events(decode=True):
if not callback(event):
break
def inspect_container(self, docker_id) -> dict:
try:
docker_info = self.cli.inspect_container(container=docker_id)
except docker.errors.APIError:
return None
info = {
"ip_address": docker_info["NetworkSettings"]["IPAddress"],
"docker_id": docker_id,
"hostname": docker_info["Config"]["Hostname"]
}
if docker_info["State"]["Running"]:
info["state"] = "running"
info["running"] = True
elif docker_info["State"]["Paused"]:
info["state"] = "paused"
info["running"] = True
elif docker_info["State"]["Restarting"]:
info["state"] = "restarting"
info["running"] = True
elif docker_info["State"]["OOMKilled"]:
info["state"] = "killed"
info["running"] = False
elif docker_info["State"]["Dead"]:
info["state"] = "killed"
info["running"] = False
else:
info["state"] = "unknown"
info["running"] = False
return info