-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathswarm.py
More file actions
87 lines (74 loc) · 2.84 KB
/
swarm.py
File metadata and controls
87 lines (74 loc) · 2.84 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
78
79
80
81
82
83
84
85
86
87
import logging
from docker import Client
from django.conf import settings
class SwarmClient(object):
def __init__(self,target, auth, options, pkey):
self.target = settings.SWARM_HOST
# single global connection
self.registry = settings.REGISTRY_HOST+":"+settings.REGISTRY_PORT
self.docker_cli = Client(base_url='tcp://'+self.target+':'+"2395",timeout=1200)
def create(self, name, image, command='', template=None, **kwargs):
"""Create a container"""
cimage=self.registry+"/"+image
cname=name
ccommand=command
# self.docker_cli.pull(cimage, stream=False,insecure_registry=True)
self.docker_cli.create_container(image=cimage,name=cname,command=ccommand)#,hostname=self._get_hostname(cname),ports=self._get_ports(cimage))
self.docker_cli.start(cname, port_bindings=self._get_portbindings(cimage),publish_all_ports=True)
def start(self, name):
"""
Start a container
"""
self.docker_cli.start(name)
return
def stop(self, name):
"""
Stop a container
"""
self.docker_cli.stop(name)
return
def destroy(self, name):
"""
Destroy a container
"""
self.docker_cli.stop(name)
self.docker_cli.remove_container(name)
return
def run(self, name, image, entrypoint, command):
"""
Run a one-off command
"""
# dump input into a json object for testing purposes
return 0, json.dumps({'name': name,
'image': image,
'entrypoint': entrypoint,
'command': command})
def attach(self, name):
"""
Attach to a job's stdin, stdout and stderr
"""
return StringIO(), StringIO(), StringIO()
def _get_hostname(self, application_name):
hostname = settings.UNIT_HOSTNAME
if hostname == "default":
return ''
elif hostname == "application":
# replace underscore with dots, since underscore is not valid in DNS hostnames
dns_name = application_name.replace("_", ".")
return dns_name
elif hostname == "server":
raise NotImplementedError
else:
raise RuntimeError('Unsupported hostname: ' + hostname)
def _get_portbindings(self,image):
dictports=self.docker_cli.inspect_image(image)["ContainerConfig"]["ExposedPorts"]
for port,mapping in dictports.items():
dictports[port]=None
return dictports
def _get_ports(self,image):
ports=[]
dictports=self.docker_cli.inspect_image(image)["ContainerConfig"]["ExposedPorts"]
for port,mapping in dictports.items():
ports.append(int(port.split('/')[0]))
return ports
SchedulerClient = SwarmClient