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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
|
#!/usr/bin/python
import unittest, subprocess, sys
import platform, os, shutil
import time
#
# Prerequisites:
# sudo apt-get -y install lxc libvirt-bin make gcc
class Lxc:
def __init__(self, template="ubuntu", relnum = "12.04", release=None, config = "/etc/lxc-test.conf", name=None):
self.name = name
if not name:
if release:
self.name = "test-%s" % release
else:
self.name="test-container"
self.release = release
self.config = config
self.template = template
# Clone - for now only supports copies of directory backed containers
# add lvm and btrfs supports
def Clone(self, clonefrom):
if not clonefrom:
raise ValueError, "Clone requires clonefrom"
cmd = ["lxc-clone", "-o", clonefrom.name, "-n", self.name]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed cloning %s from %s" % (self.name, clonefrom.name)
def Create(self, config = None):
cmd = ["lxc-create", "-t", self.template, "-n", self.name]
if self.config != None:
cmd.append("-f")
cmd.append(self.config)
if self.release:
cmd.append("--")
cmd.append("-r %s" % self.release)
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed creating %s" % (self.name)
def Destroy(self, ignorefail=False):
ret = subprocess.call(["lxc-destroy", "-f", "-n", self.name], stdout=None, stderr=None)
if ret != 0 and not ignorefail:
raise ValueError, "Failed destroying %s" % (self.name)
def PkgSetup(self):
rootpath = "/var/lib/lxc/%s/rootfs" % (self.name)
cmd = ["chroot", rootpath, "apt-get", "update"]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError("Failed apt-get update in container %s" %
(self.name))
override='''manual'''
f=open("/var/lib/lxc/%s/rootfs/etc/init/lxc.override" % (self.name), "w")
f.write(override)
f.close()
f=open("/var/lib/lxc/%s/rootfs/etc/init/lxc-net.override" % (self.name), "w")
f.write(override)
f.close()
updatetxt='''#!/bin/sh
exit 101
'''
f=open("/var/lib/lxc/%s/rootfs/usr/sbin/policy-rc.d" % (self.name), "w")
f.write(updatetxt)
f.close()
cmd = ["chmod", "+x", "/var/lib/lxc/%s/rootfs/usr/sbin/policy-rc.d" % (self.name)]
ret = subprocess.call(cmd, stdout=None, stderr=None)
cmd = ["chroot", rootpath, "apt-get", "-y", "install",
"--no-install-recommends", "lxc"]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError("Failed installing lxc in container %s" %
(self.name))
cmd = ["rm", "-f", "/var/lib/lxc/%s/rootfs/usr/sbin/policy-rc.d" % (self.name)]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed removing policy-rc.d in container %s" % (self.name)
def Execute(self, program="/bin/true"):
cmd = ["lxc-execute", "-n", self.name, "--", program]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed executing %s in %s" % (program, self.name)
def Start(self, init="/sbin/init"):
cmd = ["lxc-start", "-d", "-n", self.name]
if init != "/sbin/init":
cmd.append("--")
cmd.append(init)
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed starting %s in %s" % (init, self.name)
def ConfirmRunning(self, notrunning=False):
# ideally lxc-wait would take a timeout and we could do
# lxc-wait -n test-$release -s RUNNING -t 5. We don't though.
time.sleep(2)
cmd1 = ["lxc-info", "-n", self.name, "-s"]
sp = subprocess.Popen(cmd1, stderr = subprocess.STDOUT, stdout = subprocess.PIPE)
output = sp.communicate()[0]
if not notrunning:
output.index("RUNNING") # this will raise a ValueError if not found.
else:
output.index("STOPPED") # this will raise a ValueError if not found.
def TrySsh(self):
True
# not yet implemented
# should we be trying a clean shutdown?
def Stop(self):
cmd = ["lxc-stop", "-n", self.name]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed stopping %s" % (self.name)
def apparmor_profile(self, profile):
# remove any existing lxc.aa_profile lines, and add a new one
# saying lxc.aa_profile = unconfined.
configfile = "/var/lib/lxc/%s/config" % (self.name)
cmd = ["sed", "-i", "/aa_profile/d", configfile]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed to remove existing aa_profile lines"
newprofile = '''$a\
lxc.aa_profile = unconfined'''
cmd = ["sed", "-i", newprofile, configfile]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed to set unconfined profile"
# a class whose setUp creates a container of a certain suite,
# and tearDown stops and destroys it.
# TODO: add options, like backing store.
class SimpleLxcTests(unittest.TestCase):
def setUp(self):
# get lsb release
dist=platform.dist()
self.hostrelease = float(dist[1])
self.arch=platform.machine()
if self.arch == "x86_64":
self.arch="amd64"
elif self.arch == "i686" or self.arch == "x86":
self.arch="i386"
elif self.arch == "armv7l":
self.arch="armel"
if self.arch == "armel":
self.tests = [["ubuntu", 12.04, "precise"],
# ["ubuntu", 12.10, "quantal"],
["ubuntu", 13.04, "raring"]]
elif self.arch == "armhf":
self.tests = [["ubuntu", 12.04, "precise"],
# ["ubuntu", 12.10, "quantal"],
["ubuntu", 13.04, "raring"]]
else:
self.tests = [["ubuntu", 8.04, "lucid"],
["ubuntu", 12.04, "precise"],
# ["ubuntu", 12.10, "quantal"],
["ubuntu", 13.04, "raring"],
#["ubuntu-cloud", 8.04, "lucid"],
#["ubuntu-cloud", 12.04, "precise"],
# ["ubuntu-cloud", 12.10, "quantal"],
#["ubuntu-cloud", 13.04, "raring"],
]
lxctestconf = '''
lxc.network.type=veth
lxc.network.link=virbr0
lxc.network.flags=up
'''
f = open("/etc/lxc-test.conf", "w")
f.write(lxctestconf)
f.close()
def tearDown(self):
os.remove("/etc/lxc-test.conf")
def runTest(self):
for (t,relnum,r) in self.tests:
try:
test = "initialization"
l = Lxc(template=t, relnum=relnum, release=r)
test = "destroy preexisting"
l.Destroy(ignorefail=True)
test = "create"
l.Create()
if t == 'ubuntu':
test = "lxc package setup in container"
l.PkgSetup()
test = "lxc-execute"
l.Execute("/bin/true")
test = "destroy"
l.Destroy()
test = "second create"
l.Create()
test = "lxc-start"
l.Start()
test = "confirm container is running"
l.ConfirmRunning()
test = "ssh into container"
l.TrySsh()
test = "stopping the container"
l.Stop()
test = "final destroy"
l.Destroy()
except ValueError, e:
self.assertTrue(False, "Failed with release %s at test %s\nError: %s" % (r, test, e))
return True
# Create a container and clone it
try:
test = "Create original container"
f = open("lxc:globtest", "w")
f.close();
l = Lxc(release="precise", config=None) # this also tests a container without '-f config'
l.Destroy(ignorefail=True)
l.Create();
test = "Clone container"
l2 = Lxc(name="test-clone")
l2.Destroy(ignorefail=True)
l2.Clone(clonefrom=l)
test = "Start cloned container"
l2.Start()
test = "Confirm container clone is running"
l2.ConfirmRunning()
test = "Stop cloned container"
l2.Stop()
test = "Destroy cloned container"
l2.Destroy()
test = "Destroy original container"
l.Destroy()
except ValueError, e:
try:
l.Destroy(ignorefail=True)
l2.Destroy(ignorefail=True)
except:
pass
self.assertTrue(False, "Failed at container clone test %s\nError: %s" % (test, e))
# test container autostart
try:
test = "Create autostart container"
l = Lxc(name="autotest1")
l.Destroy(ignorefail=True)
l.Create();
cmd = ["ln", "-s", "/var/lib/lxc/autotest1/config", "/etc/lxc/auto/autostart1.conf"]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed creating autostart symlink"
test = "stop lxc"
subprocess.call(["stop", "lxc"], stdout=None, stderr=None)
test = "start lxc"
subprocess.call(["start", "lxc"], stdout=None, stderr=None)
test = "check autostart container is running"
l.ConfirmRunning()
test = "stop lxc(2)"
subprocess.call(["stop", "lxc"], stdout=None, stderr=None)
l.ConfirmRunning(notrunning=True)
l.Destroy()
autolinksurvived=True
try:
os.stat("/etc/lxc/auto/autostart1.conf");
except:
autolinksurvived=False
if autolinksurvived:
raise ValueError, "Destroy did not remove auto symlink"
l.Destroy(ignorefail=True)
except ValueError, e:
try:
l.Destroy(ignorefail=True)
except:
pass
self.assertTrue(False, "Failed at container autostart test %s\nError: %s" % (test, e))
class ApiTest(unittest.TestCase):
def setUp(self):
rc = subprocess.call(["bzr", "branch", "lp:ubuntu/raring/lxc"], stdout=None, stderr=None)
if rc != 0:
raise ValueError, "Failed branching ubuntu:lxc"
def tearDown(self):
shutil.rmtree("lxc")
def runTest(self):
cmd = [ "python3", "lxc/src/python-lxc/examples/api_test.py" ]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed running api test"
class RebootTest(unittest.TestCase):
def setUp(self):
rc = subprocess.call(["make", "reboot-test"], stdout=None, stderr=None)
if rc != 0:
raise ValueError, "Failed building reboot test"
def tearDown(self):
os.remove("reboot-test")
def runTest(self):
cmd = ["./reboot-test"]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
raise ValueError, "Failed running reboot test"
class ApparmorTests(unittest.TestCase):
def setUp(self):
self.lxc = Lxc(config=None,release="precise")
self.lxc.Destroy(ignorefail=True)
self.lxc.Create()
self.lxc.apparmor_profile("unconfined")
def tearDown(self):
self.lxc.Destroy(ignorefail=True)
def runTest(self):
try:
self.lxc.Start()
self.lxc.ConfirmRunning()
self.lxc.Stop()
except ValueError, e:
#self.assertTrue(False, "Failed apparmor test with error %s" % (e)
print "Apparmor test failed as expected (see LP bug 987371)"
if __name__ == '__main__':
# set keepcache true if you're developing and want to save some time...
keepcache=False
# check for uid 0
uid = os.getuid()
if uid != 0:
print >>sys.stderr, "Run this test suite as root"
sys.exit(1)
# worry about what to do about other distros later
dist=platform.dist()
if dist[0] != "Ubuntu":
print >>sys.stderr, "This test suite does not yet support %s" % (dist[0])
sys.exit(1)
hostrelease = float(dist[1])
# make sure the needed prereqs are installed
cmd = ["sudo", "apt-get", "-y", "install", "lxc", "libvirt-bin", "make", "gcc"]
if hostrelease >= 12.10:
cmd += [ "bzr", "python3-lxc" ]
ret = subprocess.call(cmd, stdout=None, stderr=None)
if ret != 0:
print "Failed installing prerequisites"
sys.exit(1)
# apt-get install -y cgroup-lite libvirt-bin lxc lsb-release make gcc
if hostrelease < 11.10:
print >>sys.stderr, "testsuite only supported on oneiric and precise"
sys.exit(1)
suite = unittest.TestSuite()
if hostrelease >= 12.04:
suite.addTest(RebootTest())
# The apitest is run by utah's ubuntu-test-cases by hand. Don't try to
# run them here.
# if hostrelease >= 12.10:
# suite.addTest(ApiTest())
suite.addTest(SimpleLxcTests())
if not keepcache:
suite.addTest(SimpleLxcTests())
if hostrelease >= 12.04:
suite.addTest(ApparmorTests())
# clear the caches for the first run. we'll do two runs
if not keepcache:
try:
shutil.rmtree("/var/cache/lxc")
os.mkdir("/var/cache/lxc", 0755)
except:
pass
rc = unittest.TextTestRunner(verbosity=2).run(suite)
if not rc.wasSuccessful():
sys.exit(1)
# set et sw=4 ts=4 ai si sm background=dark
|