forked from jlewallen/docker-manifests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdock
executable file
·187 lines (155 loc) · 5.37 KB
/
dock
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/usr/bin/python
#
#
import sys
import json
import docker.client
import random
import time
import subprocess
import os
import string
import optparse
from urlparse import urlparse
def new_id(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
class Configuration:
def __init__(self):
self.cfg = json.load(open('settings.json'))
def get_offset_ip(offset):
None
class Instance:
def __init__(self, name, cfg):
self.name = name
self.cfg = cfg
def short_id(self):
return self.cfg.get('container')
def exists(self, docker):
if self.short_id() is None:
return False
try:
details = docker.inspect_container(self.short_id())
return True
except:
return False
def is_running(self, docker):
if self.short_id() is None:
return False
try:
details = docker.inspect_container(self.short_id())
return details["State"]["Running"]
except:
return False
def make_params(self):
return { 'image': self.cfg['image'],
'command': self.cfg.get('command'),
'ports': self.cfg.get('ports'),
'environment': self.cfg.get('env'),
'detach': True,
'hostname': self.name,
}
def provision(self, docker):
if self.exists(docker):
if self.is_running(docker):
print "%s: skipping, %s is running" % (self.name, self.short_id())
else:
print "%s: %s exists, starting" % (self.name, self.short_id())
docker.start(self.short_id())
return self.short_id()
print "%s: starting instance" % (self.name)
container = docker.create_container(**self.make_params())
short_id = container['Id']
details = docker.inspect_container(short_id)
long_id = details['ID']
docker.start(short_id)
# this is all kinds of race condition prone, too bad we
# can't do this before we start the container
self.configure_networking(short_id, long_id, "br0", self.cfg['ip'])
print "%s: instance started %s" % (self.name, short_id)
self.cfg['container'] = short_id
return short_id
def configure_networking(self, short_id, long_id, bridge, ip):
iface_suffix = new_id()
iface_local_name = "pvnetl%s" % iface_suffix
iface_remote_name = "pvnetr%s" % iface_suffix
# poll for the file, it'll be created when the container starts
# up and we should spend very little time waiting
while True:
try:
npsid = open("/sys/fs/cgroup/devices/lxc/" + long_id + "/tasks", "r").readline().strip()
break
except IOError:
print "%s: waiting for container %s cgroup" % (self.name, short_id)
time.sleep(0.1)
print "%s: configuring %s networking, assigning %s" % (self.name, short_id, ip)
# strategy from unionize.sh
commands = [
"mkdir -p /var/run/netns",
"rm -f /var/run/netns/%s" % long_id,
"ln -s /proc/%s/ns/net /var/run/netns/%s" % (npsid, long_id),
"ip link add name %s type veth peer name %s" % (iface_local_name, iface_remote_name),
"brctl addif %s %s" % (bridge, iface_local_name),
"ifconfig %s up" % (iface_local_name),
"ip link set %s netns %s" % (iface_remote_name, npsid),
"ip netns exec %s ip link set %s name eth1" % (long_id, iface_remote_name),
"ip netns exec %s ifconfig eth1 %s" % (long_id, ip)
]
for command in commands:
if os.system(command) != 0:
raise Exception("Error configuring networking: '%s' failed!" % command)
def stop(self, docker):
if self.is_running(docker):
print "%s: stopping %s" % (self.name, self.short_id())
docker.stop(self.short_id())
return self.short_id()
def kill(self, docker):
if self.is_running(docker):
print "%s: killing %s" % (self.name, self.short_id())
docker.kill(self.short_id())
return self.short_id()
class Manifest:
def __init__(self, path):
self.path = path
self.cfg = json.load(open(self.path))
def apply(self, docker, callback):
for name in self.cfg:
for index, instance in enumerate(self.cfg[name]):
instance_name = "%s-%d" % (name, index)
callback(Instance(instance_name, instance), docker)
def provision(self, docker):
self.apply(docker, lambda instance, docker: instance.provision(docker))
def stop(self, docker):
self.apply(docker, lambda instance, docker: instance.stop(docker))
def kill(self, docker):
self.apply(docker, lambda instance, docker: instance.kill(docker))
def save(self):
json.dump(self.cfg, open(self.path, "w"), sort_keys=True, indent=4, separators=(',', ': '))
class Options:
def __init__(self, entries, args):
self.__dict__.update(entries)
self.manifest = args[0]
def get_docker():
docker_url = urlparse("http://127.0.0.1:4243")
return docker.Client(base_url = docker_url.geturl())
def get_options():
parser = optparse.OptionParser()
parser.add_option("--stop", action="store_true", dest="stop", default=False, help="stop instances")
parser.add_option("--kill", action="store_true", dest="kill", default=False, help="kill instances")
raw_options, args = parser.parse_args()
if not args:
exit("No manifest given.")
return Options(vars(raw_options), args)
def main():
options = get_options()
docker = get_docker()
if os.geteuid() != 0:
exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.")
manifest = Manifest(options.manifest)
if options.stop:
manifest.stop(docker)
elif options.kill:
manifest.kill(docker)
else:
manifest.provision(docker)
manifest.save()
main()