root / test / py / ganeti.backend_unittest.py @ b544a3c2
History | View | Annotate | Download (29.9 kB)
1 |
#!/usr/bin/python
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2010, 2013 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
|
22 |
"""Script for testing ganeti.backend"""
|
23 |
|
24 |
import mock |
25 |
import os |
26 |
import shutil |
27 |
import tempfile |
28 |
import testutils |
29 |
import unittest |
30 |
|
31 |
from ganeti import backend |
32 |
from ganeti import constants |
33 |
from ganeti import errors |
34 |
from ganeti import hypervisor |
35 |
from ganeti import netutils |
36 |
from ganeti import objects |
37 |
from ganeti import utils |
38 |
|
39 |
|
40 |
class TestX509Certificates(unittest.TestCase): |
41 |
def setUp(self): |
42 |
self.tmpdir = tempfile.mkdtemp()
|
43 |
|
44 |
def tearDown(self): |
45 |
shutil.rmtree(self.tmpdir)
|
46 |
|
47 |
def test(self): |
48 |
(name, cert_pem) = backend.CreateX509Certificate(300, cryptodir=self.tmpdir) |
49 |
|
50 |
self.assertEqual(utils.ReadFile(os.path.join(self.tmpdir, name, |
51 |
backend._X509_CERT_FILE)), |
52 |
cert_pem) |
53 |
self.assert_(0 < os.path.getsize(os.path.join(self.tmpdir, name, |
54 |
backend._X509_KEY_FILE))) |
55 |
|
56 |
(name2, cert_pem2) = \ |
57 |
backend.CreateX509Certificate(300, cryptodir=self.tmpdir) |
58 |
|
59 |
backend.RemoveX509Certificate(name, cryptodir=self.tmpdir)
|
60 |
backend.RemoveX509Certificate(name2, cryptodir=self.tmpdir)
|
61 |
|
62 |
self.assertEqual(utils.ListVisibleFiles(self.tmpdir), []) |
63 |
|
64 |
def testNonEmpty(self): |
65 |
(name, _) = backend.CreateX509Certificate(300, cryptodir=self.tmpdir) |
66 |
|
67 |
utils.WriteFile(utils.PathJoin(self.tmpdir, name, "hello-world"), |
68 |
data="Hello World")
|
69 |
|
70 |
self.assertRaises(backend.RPCFail, backend.RemoveX509Certificate,
|
71 |
name, cryptodir=self.tmpdir)
|
72 |
|
73 |
self.assertEqual(utils.ListVisibleFiles(self.tmpdir), [name]) |
74 |
|
75 |
|
76 |
class TestGetCryptoTokens(testutils.GanetiTestCase): |
77 |
|
78 |
def setUp(self): |
79 |
self._digest_fn_orig = utils.GetClientCertificateDigest
|
80 |
self._ssl_digest = "12345" |
81 |
utils.GetClientCertificateDigest = mock.Mock( |
82 |
return_value=self._ssl_digest)
|
83 |
|
84 |
def tearDown(self): |
85 |
utils.GetClientCertificateDigest = self._digest_fn_orig
|
86 |
|
87 |
def testSslToken(self): |
88 |
result = backend.GetCryptoTokens([constants.CRYPTO_TYPE_SSL_DIGEST]) |
89 |
self.assertTrue((constants.CRYPTO_TYPE_SSL_DIGEST, self._ssl_digest) |
90 |
in result)
|
91 |
|
92 |
def testUnknownToken(self): |
93 |
self.assertRaises(errors.ProgrammerError,
|
94 |
backend.GetCryptoTokens, ["pink_bunny"])
|
95 |
|
96 |
|
97 |
class TestNodeVerify(testutils.GanetiTestCase): |
98 |
|
99 |
def setUp(self): |
100 |
testutils.GanetiTestCase.setUp(self)
|
101 |
self._mock_hv = None |
102 |
|
103 |
def _GetHypervisor(self, hv_name): |
104 |
self._mock_hv = hypervisor.GetHypervisor(hv_name)
|
105 |
self._mock_hv.ValidateParameters = mock.Mock()
|
106 |
self._mock_hv.Verify = mock.Mock()
|
107 |
return self._mock_hv |
108 |
|
109 |
def testMasterIPLocalhost(self): |
110 |
# this a real functional test, but requires localhost to be reachable
|
111 |
local_data = (netutils.Hostname.GetSysName(), |
112 |
constants.IP4_ADDRESS_LOCALHOST) |
113 |
result = backend.VerifyNode({constants.NV_MASTERIP: local_data}, |
114 |
None, {}, {}, {})
|
115 |
self.failUnless(constants.NV_MASTERIP in result, |
116 |
"Master IP data not returned")
|
117 |
self.failUnless(result[constants.NV_MASTERIP], "Cannot reach localhost") |
118 |
|
119 |
def testMasterIPUnreachable(self): |
120 |
# Network 192.0.2.0/24 is reserved for test/documentation as per
|
121 |
# RFC 5737
|
122 |
bad_data = ("master.example.com", "192.0.2.1") |
123 |
# we just test that whatever TcpPing returns, VerifyNode returns too
|
124 |
netutils.TcpPing = lambda a, b, source=None: False |
125 |
result = backend.VerifyNode({constants.NV_MASTERIP: bad_data}, |
126 |
None, {}, {}, {})
|
127 |
self.failUnless(constants.NV_MASTERIP in result, |
128 |
"Master IP data not returned")
|
129 |
self.failIf(result[constants.NV_MASTERIP],
|
130 |
"Result from netutils.TcpPing corrupted")
|
131 |
|
132 |
def testVerifyHvparams(self): |
133 |
test_hvparams = {constants.HV_XEN_CMD: constants.XEN_CMD_XL} |
134 |
test_what = {constants.NV_HVPARAMS: \ |
135 |
[("mynode", constants.HT_XEN_PVM, test_hvparams)]}
|
136 |
result = {} |
137 |
backend._VerifyHvparams(test_what, True, result,
|
138 |
get_hv_fn=self._GetHypervisor)
|
139 |
self._mock_hv.ValidateParameters.assert_called_with(test_hvparams)
|
140 |
|
141 |
def testVerifyHypervisors(self): |
142 |
hvname = constants.HT_XEN_PVM |
143 |
hvparams = {constants.HV_XEN_CMD: constants.XEN_CMD_XL} |
144 |
all_hvparams = {hvname: hvparams} |
145 |
test_what = {constants.NV_HYPERVISOR: [hvname]} |
146 |
result = {} |
147 |
backend._VerifyHypervisors( |
148 |
test_what, True, result, all_hvparams=all_hvparams,
|
149 |
get_hv_fn=self._GetHypervisor)
|
150 |
self._mock_hv.Verify.assert_called_with(hvparams=hvparams)
|
151 |
|
152 |
|
153 |
def _DefRestrictedCmdOwner(): |
154 |
return (os.getuid(), os.getgid())
|
155 |
|
156 |
|
157 |
class TestVerifyRestrictedCmdName(unittest.TestCase): |
158 |
def testAcceptableName(self): |
159 |
for i in ["foo", "bar", "z1", "000first", "hello-world"]: |
160 |
for fn in [lambda s: s, lambda s: s.upper(), lambda s: s.title()]: |
161 |
(status, msg) = backend._VerifyRestrictedCmdName(fn(i)) |
162 |
self.assertTrue(status)
|
163 |
self.assertTrue(msg is None) |
164 |
|
165 |
def testEmptyAndSpace(self): |
166 |
for i in ["", " ", "\t", "\n"]: |
167 |
(status, msg) = backend._VerifyRestrictedCmdName(i) |
168 |
self.assertFalse(status)
|
169 |
self.assertEqual(msg, "Missing command name") |
170 |
|
171 |
def testNameWithSlashes(self): |
172 |
for i in ["/", "./foo", "../moo", "some/name"]: |
173 |
(status, msg) = backend._VerifyRestrictedCmdName(i) |
174 |
self.assertFalse(status)
|
175 |
self.assertEqual(msg, "Invalid command name") |
176 |
|
177 |
def testForbiddenCharacters(self): |
178 |
for i in ["#", ".", "..", "bash -c ls", "'"]: |
179 |
(status, msg) = backend._VerifyRestrictedCmdName(i) |
180 |
self.assertFalse(status)
|
181 |
self.assertEqual(msg, "Command name contains forbidden characters") |
182 |
|
183 |
|
184 |
class TestVerifyRestrictedCmdDirectory(unittest.TestCase): |
185 |
def setUp(self): |
186 |
self.tmpdir = tempfile.mkdtemp()
|
187 |
|
188 |
def tearDown(self): |
189 |
shutil.rmtree(self.tmpdir)
|
190 |
|
191 |
def testCanNotStat(self): |
192 |
tmpname = utils.PathJoin(self.tmpdir, "foobar") |
193 |
self.assertFalse(os.path.exists(tmpname))
|
194 |
(status, msg) = \ |
195 |
backend._VerifyRestrictedCmdDirectory(tmpname, _owner=NotImplemented)
|
196 |
self.assertFalse(status)
|
197 |
self.assertTrue(msg.startswith("Can't stat(2) '")) |
198 |
|
199 |
def testTooPermissive(self): |
200 |
tmpname = utils.PathJoin(self.tmpdir, "foobar") |
201 |
os.mkdir(tmpname) |
202 |
|
203 |
for mode in [0777, 0706, 0760, 0722]: |
204 |
os.chmod(tmpname, mode) |
205 |
self.assertTrue(os.path.isdir(tmpname))
|
206 |
(status, msg) = \ |
207 |
backend._VerifyRestrictedCmdDirectory(tmpname, _owner=NotImplemented)
|
208 |
self.assertFalse(status)
|
209 |
self.assertTrue(msg.startswith("Permissions on '")) |
210 |
|
211 |
def testNoDirectory(self): |
212 |
tmpname = utils.PathJoin(self.tmpdir, "foobar") |
213 |
utils.WriteFile(tmpname, data="empty\n")
|
214 |
self.assertTrue(os.path.isfile(tmpname))
|
215 |
(status, msg) = \ |
216 |
backend._VerifyRestrictedCmdDirectory(tmpname, |
217 |
_owner=_DefRestrictedCmdOwner()) |
218 |
self.assertFalse(status)
|
219 |
self.assertTrue(msg.endswith("is not a directory")) |
220 |
|
221 |
def testNormal(self): |
222 |
tmpname = utils.PathJoin(self.tmpdir, "foobar") |
223 |
os.mkdir(tmpname) |
224 |
os.chmod(tmpname, 0755)
|
225 |
self.assertTrue(os.path.isdir(tmpname))
|
226 |
(status, msg) = \ |
227 |
backend._VerifyRestrictedCmdDirectory(tmpname, |
228 |
_owner=_DefRestrictedCmdOwner()) |
229 |
self.assertTrue(status)
|
230 |
self.assertTrue(msg is None) |
231 |
|
232 |
|
233 |
class TestVerifyRestrictedCmd(unittest.TestCase): |
234 |
def setUp(self): |
235 |
self.tmpdir = tempfile.mkdtemp()
|
236 |
|
237 |
def tearDown(self): |
238 |
shutil.rmtree(self.tmpdir)
|
239 |
|
240 |
def testCanNotStat(self): |
241 |
tmpname = utils.PathJoin(self.tmpdir, "helloworld") |
242 |
self.assertFalse(os.path.exists(tmpname))
|
243 |
(status, msg) = \ |
244 |
backend._VerifyRestrictedCmd(self.tmpdir, "helloworld", |
245 |
_owner=NotImplemented)
|
246 |
self.assertFalse(status)
|
247 |
self.assertTrue(msg.startswith("Can't stat(2) '")) |
248 |
|
249 |
def testNotExecutable(self): |
250 |
tmpname = utils.PathJoin(self.tmpdir, "cmdname") |
251 |
utils.WriteFile(tmpname, data="empty\n")
|
252 |
(status, msg) = \ |
253 |
backend._VerifyRestrictedCmd(self.tmpdir, "cmdname", |
254 |
_owner=_DefRestrictedCmdOwner()) |
255 |
self.assertFalse(status)
|
256 |
self.assertTrue(msg.startswith("access(2) thinks '")) |
257 |
|
258 |
def testExecutable(self): |
259 |
tmpname = utils.PathJoin(self.tmpdir, "cmdname") |
260 |
utils.WriteFile(tmpname, data="empty\n", mode=0700) |
261 |
(status, executable) = \ |
262 |
backend._VerifyRestrictedCmd(self.tmpdir, "cmdname", |
263 |
_owner=_DefRestrictedCmdOwner()) |
264 |
self.assertTrue(status)
|
265 |
self.assertEqual(executable, tmpname)
|
266 |
|
267 |
|
268 |
class TestPrepareRestrictedCmd(unittest.TestCase): |
269 |
_TEST_PATH = "/tmp/some/test/path"
|
270 |
|
271 |
def testDirFails(self): |
272 |
def fn(path): |
273 |
self.assertEqual(path, self._TEST_PATH) |
274 |
return (False, "test error 31420") |
275 |
|
276 |
(status, msg) = \ |
277 |
backend._PrepareRestrictedCmd(self._TEST_PATH, "cmd21152", |
278 |
_verify_dir=fn, |
279 |
_verify_name=NotImplemented,
|
280 |
_verify_cmd=NotImplemented)
|
281 |
self.assertFalse(status)
|
282 |
self.assertEqual(msg, "test error 31420") |
283 |
|
284 |
def testNameFails(self): |
285 |
def fn(cmd): |
286 |
self.assertEqual(cmd, "cmd4617") |
287 |
return (False, "test error 591") |
288 |
|
289 |
(status, msg) = \ |
290 |
backend._PrepareRestrictedCmd(self._TEST_PATH, "cmd4617", |
291 |
_verify_dir=lambda _: (True, None), |
292 |
_verify_name=fn, |
293 |
_verify_cmd=NotImplemented)
|
294 |
self.assertFalse(status)
|
295 |
self.assertEqual(msg, "test error 591") |
296 |
|
297 |
def testCommandFails(self): |
298 |
def fn(path, cmd): |
299 |
self.assertEqual(path, self._TEST_PATH) |
300 |
self.assertEqual(cmd, "cmd17577") |
301 |
return (False, "test error 25524") |
302 |
|
303 |
(status, msg) = \ |
304 |
backend._PrepareRestrictedCmd(self._TEST_PATH, "cmd17577", |
305 |
_verify_dir=lambda _: (True, None), |
306 |
_verify_name=lambda _: (True, None), |
307 |
_verify_cmd=fn) |
308 |
self.assertFalse(status)
|
309 |
self.assertEqual(msg, "test error 25524") |
310 |
|
311 |
def testSuccess(self): |
312 |
def fn(path, cmd): |
313 |
return (True, utils.PathJoin(path, cmd)) |
314 |
|
315 |
(status, executable) = \ |
316 |
backend._PrepareRestrictedCmd(self._TEST_PATH, "cmd22633", |
317 |
_verify_dir=lambda _: (True, None), |
318 |
_verify_name=lambda _: (True, None), |
319 |
_verify_cmd=fn) |
320 |
self.assertTrue(status)
|
321 |
self.assertEqual(executable, utils.PathJoin(self._TEST_PATH, "cmd22633")) |
322 |
|
323 |
|
324 |
def _SleepForRestrictedCmd(duration): |
325 |
assert duration > 5 |
326 |
|
327 |
|
328 |
def _GenericRestrictedCmdError(cmd): |
329 |
return "Executing command '%s' failed" % cmd |
330 |
|
331 |
|
332 |
class TestRunRestrictedCmd(unittest.TestCase): |
333 |
def setUp(self): |
334 |
self.tmpdir = tempfile.mkdtemp()
|
335 |
|
336 |
def tearDown(self): |
337 |
shutil.rmtree(self.tmpdir)
|
338 |
|
339 |
def testNonExistantLockDirectory(self): |
340 |
lockfile = utils.PathJoin(self.tmpdir, "does", "not", "exist") |
341 |
sleep_fn = testutils.CallCounter(_SleepForRestrictedCmd) |
342 |
self.assertFalse(os.path.exists(lockfile))
|
343 |
self.assertRaises(backend.RPCFail,
|
344 |
backend.RunRestrictedCmd, "test",
|
345 |
_lock_timeout=NotImplemented,
|
346 |
_lock_file=lockfile, |
347 |
_path=NotImplemented,
|
348 |
_sleep_fn=sleep_fn, |
349 |
_prepare_fn=NotImplemented,
|
350 |
_runcmd_fn=NotImplemented,
|
351 |
_enabled=True)
|
352 |
self.assertEqual(sleep_fn.Count(), 1) |
353 |
|
354 |
@staticmethod
|
355 |
def _TryLock(lockfile): |
356 |
sleep_fn = testutils.CallCounter(_SleepForRestrictedCmd) |
357 |
|
358 |
result = False
|
359 |
try:
|
360 |
backend.RunRestrictedCmd("test22717",
|
361 |
_lock_timeout=0.1,
|
362 |
_lock_file=lockfile, |
363 |
_path=NotImplemented,
|
364 |
_sleep_fn=sleep_fn, |
365 |
_prepare_fn=NotImplemented,
|
366 |
_runcmd_fn=NotImplemented,
|
367 |
_enabled=True)
|
368 |
except backend.RPCFail, err:
|
369 |
assert str(err) == _GenericRestrictedCmdError("test22717"), \ |
370 |
"Did not fail with generic error message"
|
371 |
result = True
|
372 |
|
373 |
assert sleep_fn.Count() == 1 |
374 |
|
375 |
return result
|
376 |
|
377 |
def testLockHeldByOtherProcess(self): |
378 |
lockfile = utils.PathJoin(self.tmpdir, "lock") |
379 |
|
380 |
lock = utils.FileLock.Open(lockfile) |
381 |
lock.Exclusive(blocking=True, timeout=1.0) |
382 |
try:
|
383 |
self.assertTrue(utils.RunInSeparateProcess(self._TryLock, lockfile)) |
384 |
finally:
|
385 |
lock.Close() |
386 |
|
387 |
@staticmethod
|
388 |
def _PrepareRaisingException(path, cmd): |
389 |
assert cmd == "test23122" |
390 |
raise Exception("test") |
391 |
|
392 |
def testPrepareRaisesException(self): |
393 |
lockfile = utils.PathJoin(self.tmpdir, "lock") |
394 |
|
395 |
sleep_fn = testutils.CallCounter(_SleepForRestrictedCmd) |
396 |
prepare_fn = testutils.CallCounter(self._PrepareRaisingException)
|
397 |
|
398 |
try:
|
399 |
backend.RunRestrictedCmd("test23122",
|
400 |
_lock_timeout=1.0, _lock_file=lockfile,
|
401 |
_path=NotImplemented, _runcmd_fn=NotImplemented, |
402 |
_sleep_fn=sleep_fn, _prepare_fn=prepare_fn, |
403 |
_enabled=True)
|
404 |
except backend.RPCFail, err:
|
405 |
self.assertEqual(str(err), _GenericRestrictedCmdError("test23122")) |
406 |
else:
|
407 |
self.fail("Didn't fail") |
408 |
|
409 |
self.assertEqual(sleep_fn.Count(), 1) |
410 |
self.assertEqual(prepare_fn.Count(), 1) |
411 |
|
412 |
@staticmethod
|
413 |
def _PrepareFails(path, cmd): |
414 |
assert cmd == "test29327" |
415 |
return ("some error message", None) |
416 |
|
417 |
def testPrepareFails(self): |
418 |
lockfile = utils.PathJoin(self.tmpdir, "lock") |
419 |
|
420 |
sleep_fn = testutils.CallCounter(_SleepForRestrictedCmd) |
421 |
prepare_fn = testutils.CallCounter(self._PrepareFails)
|
422 |
|
423 |
try:
|
424 |
backend.RunRestrictedCmd("test29327",
|
425 |
_lock_timeout=1.0, _lock_file=lockfile,
|
426 |
_path=NotImplemented, _runcmd_fn=NotImplemented, |
427 |
_sleep_fn=sleep_fn, _prepare_fn=prepare_fn, |
428 |
_enabled=True)
|
429 |
except backend.RPCFail, err:
|
430 |
self.assertEqual(str(err), _GenericRestrictedCmdError("test29327")) |
431 |
else:
|
432 |
self.fail("Didn't fail") |
433 |
|
434 |
self.assertEqual(sleep_fn.Count(), 1) |
435 |
self.assertEqual(prepare_fn.Count(), 1) |
436 |
|
437 |
@staticmethod
|
438 |
def _SuccessfulPrepare(path, cmd): |
439 |
return (True, utils.PathJoin(path, cmd)) |
440 |
|
441 |
def testRunCmdFails(self): |
442 |
lockfile = utils.PathJoin(self.tmpdir, "lock") |
443 |
|
444 |
def fn(args, env=NotImplemented, reset_env=NotImplemented, |
445 |
postfork_fn=NotImplemented):
|
446 |
self.assertEqual(args, [utils.PathJoin(self.tmpdir, "test3079")]) |
447 |
self.assertEqual(env, {})
|
448 |
self.assertTrue(reset_env)
|
449 |
self.assertTrue(callable(postfork_fn)) |
450 |
|
451 |
trylock = utils.FileLock.Open(lockfile) |
452 |
try:
|
453 |
# See if lockfile is still held
|
454 |
self.assertRaises(EnvironmentError, trylock.Exclusive, blocking=False) |
455 |
|
456 |
# Call back to release lock
|
457 |
postfork_fn(NotImplemented)
|
458 |
|
459 |
# See if lockfile can be acquired
|
460 |
trylock.Exclusive(blocking=False)
|
461 |
finally:
|
462 |
trylock.Close() |
463 |
|
464 |
# Simulate a failed command
|
465 |
return utils.RunResult(constants.EXIT_FAILURE, None, |
466 |
"stdout", "stderr406328567", |
467 |
utils.ShellQuoteArgs(args), |
468 |
NotImplemented, NotImplemented) |
469 |
|
470 |
sleep_fn = testutils.CallCounter(_SleepForRestrictedCmd) |
471 |
prepare_fn = testutils.CallCounter(self._SuccessfulPrepare)
|
472 |
runcmd_fn = testutils.CallCounter(fn) |
473 |
|
474 |
try:
|
475 |
backend.RunRestrictedCmd("test3079",
|
476 |
_lock_timeout=1.0, _lock_file=lockfile,
|
477 |
_path=self.tmpdir, _runcmd_fn=runcmd_fn,
|
478 |
_sleep_fn=sleep_fn, _prepare_fn=prepare_fn, |
479 |
_enabled=True)
|
480 |
except backend.RPCFail, err:
|
481 |
self.assertTrue(str(err).startswith("Restricted command 'test3079'" |
482 |
" failed:"))
|
483 |
self.assertTrue("stderr406328567" in str(err), |
484 |
msg="Error did not include output")
|
485 |
else:
|
486 |
self.fail("Didn't fail") |
487 |
|
488 |
self.assertEqual(sleep_fn.Count(), 0) |
489 |
self.assertEqual(prepare_fn.Count(), 1) |
490 |
self.assertEqual(runcmd_fn.Count(), 1) |
491 |
|
492 |
def testRunCmdSucceeds(self): |
493 |
lockfile = utils.PathJoin(self.tmpdir, "lock") |
494 |
|
495 |
def fn(args, env=NotImplemented, reset_env=NotImplemented, |
496 |
postfork_fn=NotImplemented):
|
497 |
self.assertEqual(args, [utils.PathJoin(self.tmpdir, "test5667")]) |
498 |
self.assertEqual(env, {})
|
499 |
self.assertTrue(reset_env)
|
500 |
|
501 |
# Call back to release lock
|
502 |
postfork_fn(NotImplemented)
|
503 |
|
504 |
# Simulate a successful command
|
505 |
return utils.RunResult(constants.EXIT_SUCCESS, None, "stdout14463", "", |
506 |
utils.ShellQuoteArgs(args), |
507 |
NotImplemented, NotImplemented) |
508 |
|
509 |
sleep_fn = testutils.CallCounter(_SleepForRestrictedCmd) |
510 |
prepare_fn = testutils.CallCounter(self._SuccessfulPrepare)
|
511 |
runcmd_fn = testutils.CallCounter(fn) |
512 |
|
513 |
result = backend.RunRestrictedCmd("test5667",
|
514 |
_lock_timeout=1.0, _lock_file=lockfile,
|
515 |
_path=self.tmpdir, _runcmd_fn=runcmd_fn,
|
516 |
_sleep_fn=sleep_fn, |
517 |
_prepare_fn=prepare_fn, |
518 |
_enabled=True)
|
519 |
self.assertEqual(result, "stdout14463") |
520 |
|
521 |
self.assertEqual(sleep_fn.Count(), 0) |
522 |
self.assertEqual(prepare_fn.Count(), 1) |
523 |
self.assertEqual(runcmd_fn.Count(), 1) |
524 |
|
525 |
def testCommandsDisabled(self): |
526 |
try:
|
527 |
backend.RunRestrictedCmd("test",
|
528 |
_lock_timeout=NotImplemented,
|
529 |
_lock_file=NotImplemented,
|
530 |
_path=NotImplemented,
|
531 |
_sleep_fn=NotImplemented,
|
532 |
_prepare_fn=NotImplemented,
|
533 |
_runcmd_fn=NotImplemented,
|
534 |
_enabled=False)
|
535 |
except backend.RPCFail, err:
|
536 |
self.assertEqual(str(err), |
537 |
"Restricted commands disabled at configure time")
|
538 |
else:
|
539 |
self.fail("Did not raise exception") |
540 |
|
541 |
|
542 |
class TestSetWatcherPause(unittest.TestCase): |
543 |
def setUp(self): |
544 |
self.tmpdir = tempfile.mkdtemp()
|
545 |
self.filename = utils.PathJoin(self.tmpdir, "pause") |
546 |
|
547 |
def tearDown(self): |
548 |
shutil.rmtree(self.tmpdir)
|
549 |
|
550 |
def testUnsetNonExisting(self): |
551 |
self.assertFalse(os.path.exists(self.filename)) |
552 |
backend.SetWatcherPause(None, _filename=self.filename) |
553 |
self.assertFalse(os.path.exists(self.filename)) |
554 |
|
555 |
def testSetNonNumeric(self): |
556 |
for i in ["", [], {}, "Hello World", "0", "1.0"]: |
557 |
self.assertFalse(os.path.exists(self.filename)) |
558 |
|
559 |
try:
|
560 |
backend.SetWatcherPause(i, _filename=self.filename)
|
561 |
except backend.RPCFail, err:
|
562 |
self.assertEqual(str(err), "Duration must be numeric") |
563 |
else:
|
564 |
self.fail("Did not raise exception") |
565 |
|
566 |
self.assertFalse(os.path.exists(self.filename)) |
567 |
|
568 |
def testSet(self): |
569 |
self.assertFalse(os.path.exists(self.filename)) |
570 |
|
571 |
for i in range(10): |
572 |
backend.SetWatcherPause(i, _filename=self.filename)
|
573 |
self.assertEqual(utils.ReadFile(self.filename), "%s\n" % i) |
574 |
self.assertEqual(os.stat(self.filename).st_mode & 0777, 0644) |
575 |
|
576 |
|
577 |
class TestGetBlockDevSymlinkPath(unittest.TestCase): |
578 |
def setUp(self): |
579 |
self.tmpdir = tempfile.mkdtemp()
|
580 |
|
581 |
def tearDown(self): |
582 |
shutil.rmtree(self.tmpdir)
|
583 |
|
584 |
def _Test(self, name, idx): |
585 |
self.assertEqual(backend._GetBlockDevSymlinkPath(name, idx,
|
586 |
_dir=self.tmpdir),
|
587 |
("%s/%s%s%s" % (self.tmpdir, name, |
588 |
constants.DISK_SEPARATOR, idx))) |
589 |
|
590 |
def test(self): |
591 |
for idx in range(100): |
592 |
self._Test("inst1.example.com", idx) |
593 |
|
594 |
|
595 |
class TestGetInstanceList(unittest.TestCase): |
596 |
|
597 |
def setUp(self): |
598 |
self._test_hv = self._TestHypervisor() |
599 |
self._test_hv.ListInstances = mock.Mock(
|
600 |
return_value=["instance1", "instance2", "instance3"] ) |
601 |
|
602 |
class _TestHypervisor(hypervisor.hv_base.BaseHypervisor): |
603 |
def __init__(self): |
604 |
hypervisor.hv_base.BaseHypervisor.__init__(self)
|
605 |
|
606 |
def _GetHypervisor(self, name): |
607 |
return self._test_hv |
608 |
|
609 |
def testHvparams(self): |
610 |
fake_hvparams = {constants.HV_XEN_CMD: constants.XEN_CMD_XL} |
611 |
hvparams = {constants.HT_FAKE: fake_hvparams} |
612 |
backend.GetInstanceList([constants.HT_FAKE], all_hvparams=hvparams, |
613 |
get_hv_fn=self._GetHypervisor)
|
614 |
self._test_hv.ListInstances.assert_called_with(hvparams=fake_hvparams)
|
615 |
|
616 |
|
617 |
class TestInstanceConsoleInfo(unittest.TestCase): |
618 |
|
619 |
def setUp(self): |
620 |
self._test_hv_a = self._TestHypervisor() |
621 |
self._test_hv_a.GetInstanceConsole = mock.Mock(
|
622 |
return_value = objects.InstanceConsole(instance="inst", kind="aHy") |
623 |
) |
624 |
self._test_hv_b = self._TestHypervisor() |
625 |
self._test_hv_b.GetInstanceConsole = mock.Mock(
|
626 |
return_value = objects.InstanceConsole(instance="inst", kind="bHy") |
627 |
) |
628 |
|
629 |
class _TestHypervisor(hypervisor.hv_base.BaseHypervisor): |
630 |
def __init__(self): |
631 |
hypervisor.hv_base.BaseHypervisor.__init__(self)
|
632 |
|
633 |
def _GetHypervisor(self, name): |
634 |
if name == "a": |
635 |
return self._test_hv_a |
636 |
else:
|
637 |
return self._test_hv_b |
638 |
|
639 |
def testRightHypervisor(self): |
640 |
dictMaker = lambda hyName: {
|
641 |
"instance":{"hypervisor":hyName}, |
642 |
"node":{},
|
643 |
"group":{},
|
644 |
"hvParams":{},
|
645 |
"beParams":{},
|
646 |
} |
647 |
|
648 |
call = { |
649 |
'i1':dictMaker("a"), |
650 |
'i2':dictMaker("b"), |
651 |
} |
652 |
|
653 |
res = backend.GetInstanceConsoleInfo(call, get_hv_fn=self._GetHypervisor)
|
654 |
|
655 |
self.assertTrue(res["i1"]["kind"] == "aHy") |
656 |
self.assertTrue(res["i2"]["kind"] == "bHy") |
657 |
|
658 |
|
659 |
class TestGetHvInfo(unittest.TestCase): |
660 |
|
661 |
def setUp(self): |
662 |
self._test_hv = self._TestHypervisor() |
663 |
self._test_hv.GetNodeInfo = mock.Mock()
|
664 |
|
665 |
class _TestHypervisor(hypervisor.hv_base.BaseHypervisor): |
666 |
def __init__(self): |
667 |
hypervisor.hv_base.BaseHypervisor.__init__(self)
|
668 |
|
669 |
def _GetHypervisor(self, name): |
670 |
return self._test_hv |
671 |
|
672 |
def testGetHvInfoAllNone(self): |
673 |
result = backend._GetHvInfoAll(None)
|
674 |
self.assertTrue(result is None) |
675 |
|
676 |
def testGetHvInfoAll(self): |
677 |
hvname = constants.HT_XEN_PVM |
678 |
hvparams = {constants.HV_XEN_CMD: constants.XEN_CMD_XL} |
679 |
hv_specs = [(hvname, hvparams)] |
680 |
|
681 |
backend._GetHvInfoAll(hv_specs, self._GetHypervisor)
|
682 |
self._test_hv.GetNodeInfo.assert_called_with(hvparams=hvparams)
|
683 |
|
684 |
|
685 |
class TestApplyStorageInfoFunction(unittest.TestCase): |
686 |
|
687 |
_STORAGE_KEY = "some_key"
|
688 |
_SOME_ARGS = ["some_args"]
|
689 |
|
690 |
def setUp(self): |
691 |
self.mock_storage_fn = mock.Mock()
|
692 |
|
693 |
def testApplyValidStorageType(self): |
694 |
storage_type = constants.ST_LVM_VG |
695 |
info_fn_orig = backend._STORAGE_TYPE_INFO_FN |
696 |
backend._STORAGE_TYPE_INFO_FN = { |
697 |
storage_type: self.mock_storage_fn
|
698 |
} |
699 |
|
700 |
backend._ApplyStorageInfoFunction( |
701 |
storage_type, self._STORAGE_KEY, self._SOME_ARGS) |
702 |
|
703 |
self.mock_storage_fn.assert_called_with(self._STORAGE_KEY, self._SOME_ARGS) |
704 |
backend._STORAGE_TYPE_INFO_FN = info_fn_orig |
705 |
|
706 |
def testApplyInValidStorageType(self): |
707 |
storage_type = "invalid_storage_type"
|
708 |
info_fn_orig = backend._STORAGE_TYPE_INFO_FN |
709 |
backend._STORAGE_TYPE_INFO_FN = {} |
710 |
|
711 |
self.assertRaises(KeyError, backend._ApplyStorageInfoFunction, |
712 |
storage_type, self._STORAGE_KEY, self._SOME_ARGS) |
713 |
backend._STORAGE_TYPE_INFO_FN = info_fn_orig |
714 |
|
715 |
def testApplyNotImplementedStorageType(self): |
716 |
storage_type = "not_implemented_storage_type"
|
717 |
info_fn_orig = backend._STORAGE_TYPE_INFO_FN |
718 |
backend._STORAGE_TYPE_INFO_FN = {storage_type: None}
|
719 |
|
720 |
self.assertRaises(NotImplementedError, |
721 |
backend._ApplyStorageInfoFunction, |
722 |
storage_type, self._STORAGE_KEY, self._SOME_ARGS) |
723 |
backend._STORAGE_TYPE_INFO_FN = info_fn_orig |
724 |
|
725 |
|
726 |
class TestGetLvmVgSpaceInfo(unittest.TestCase): |
727 |
|
728 |
def testValid(self): |
729 |
path = "somepath"
|
730 |
excl_stor = True
|
731 |
orig_fn = backend._GetVgInfo |
732 |
backend._GetVgInfo = mock.Mock() |
733 |
backend._GetLvmVgSpaceInfo(path, [excl_stor]) |
734 |
backend._GetVgInfo.assert_called_with(path, excl_stor) |
735 |
backend._GetVgInfo = orig_fn |
736 |
|
737 |
def testNoExclStorageNotBool(self): |
738 |
path = "somepath"
|
739 |
excl_stor = "123"
|
740 |
self.assertRaises(errors.ProgrammerError, backend._GetLvmVgSpaceInfo,
|
741 |
path, [excl_stor]) |
742 |
|
743 |
def testNoExclStorageNotInList(self): |
744 |
path = "somepath"
|
745 |
excl_stor = "123"
|
746 |
self.assertRaises(errors.ProgrammerError, backend._GetLvmVgSpaceInfo,
|
747 |
path, excl_stor) |
748 |
|
749 |
class TestGetLvmPvSpaceInfo(unittest.TestCase): |
750 |
|
751 |
def testValid(self): |
752 |
path = "somepath"
|
753 |
excl_stor = True
|
754 |
orig_fn = backend._GetVgSpindlesInfo |
755 |
backend._GetVgSpindlesInfo = mock.Mock() |
756 |
backend._GetLvmPvSpaceInfo(path, [excl_stor]) |
757 |
backend._GetVgSpindlesInfo.assert_called_with(path, excl_stor) |
758 |
backend._GetVgSpindlesInfo = orig_fn |
759 |
|
760 |
|
761 |
class TestCheckStorageParams(unittest.TestCase): |
762 |
|
763 |
def testParamsNone(self): |
764 |
self.assertRaises(errors.ProgrammerError, backend._CheckStorageParams,
|
765 |
None, NotImplemented) |
766 |
|
767 |
def testParamsWrongType(self): |
768 |
self.assertRaises(errors.ProgrammerError, backend._CheckStorageParams,
|
769 |
"string", NotImplemented) |
770 |
|
771 |
def testParamsEmpty(self): |
772 |
backend._CheckStorageParams([], 0)
|
773 |
|
774 |
def testParamsValidNumber(self): |
775 |
backend._CheckStorageParams(["a", True], 2) |
776 |
|
777 |
def testParamsInvalidNumber(self): |
778 |
self.assertRaises(errors.ProgrammerError, backend._CheckStorageParams,
|
779 |
["b", False], 3) |
780 |
|
781 |
|
782 |
class TestGetVgSpindlesInfo(unittest.TestCase): |
783 |
|
784 |
def setUp(self): |
785 |
self.vg_free = 13 |
786 |
self.vg_size = 31 |
787 |
self.mock_fn = mock.Mock(return_value=(self.vg_free, self.vg_size)) |
788 |
|
789 |
def testValidInput(self): |
790 |
name = "myvg"
|
791 |
excl_stor = True
|
792 |
result = backend._GetVgSpindlesInfo(name, excl_stor, info_fn=self.mock_fn)
|
793 |
self.mock_fn.assert_called_with(name)
|
794 |
self.assertEqual(name, result["name"]) |
795 |
self.assertEqual(constants.ST_LVM_PV, result["type"]) |
796 |
self.assertEqual(self.vg_free, result["storage_free"]) |
797 |
self.assertEqual(self.vg_size, result["storage_size"]) |
798 |
|
799 |
def testNoExclStor(self): |
800 |
name = "myvg"
|
801 |
excl_stor = False
|
802 |
result = backend._GetVgSpindlesInfo(name, excl_stor, info_fn=self.mock_fn)
|
803 |
self.mock_fn.assert_not_called()
|
804 |
self.assertEqual(name, result["name"]) |
805 |
self.assertEqual(constants.ST_LVM_PV, result["type"]) |
806 |
self.assertEqual(0, result["storage_free"]) |
807 |
self.assertEqual(0, result["storage_size"]) |
808 |
|
809 |
|
810 |
class TestGetVgSpindlesInfo(unittest.TestCase): |
811 |
|
812 |
def testValidInput(self): |
813 |
self.vg_free = 13 |
814 |
self.vg_size = 31 |
815 |
self.mock_fn = mock.Mock(return_value=[(self.vg_free, self.vg_size)]) |
816 |
name = "myvg"
|
817 |
excl_stor = True
|
818 |
result = backend._GetVgInfo(name, excl_stor, info_fn=self.mock_fn)
|
819 |
self.mock_fn.assert_called_with([name], excl_stor)
|
820 |
self.assertEqual(name, result["name"]) |
821 |
self.assertEqual(constants.ST_LVM_VG, result["type"]) |
822 |
self.assertEqual(self.vg_free, result["storage_free"]) |
823 |
self.assertEqual(self.vg_size, result["storage_size"]) |
824 |
|
825 |
def testNoExclStor(self): |
826 |
name = "myvg"
|
827 |
excl_stor = True
|
828 |
self.mock_fn = mock.Mock(return_value=None) |
829 |
result = backend._GetVgInfo(name, excl_stor, info_fn=self.mock_fn)
|
830 |
self.mock_fn.assert_called_with([name], excl_stor)
|
831 |
self.assertEqual(name, result["name"]) |
832 |
self.assertEqual(constants.ST_LVM_VG, result["type"]) |
833 |
self.assertEqual(None, result["storage_free"]) |
834 |
self.assertEqual(None, result["storage_size"]) |
835 |
|
836 |
|
837 |
class TestGetNodeInfo(unittest.TestCase): |
838 |
|
839 |
_SOME_RESULT = None
|
840 |
|
841 |
def testApplyStorageInfoFunction(self): |
842 |
orig_fn = backend._ApplyStorageInfoFunction |
843 |
backend._ApplyStorageInfoFunction = mock.Mock( |
844 |
return_value=self._SOME_RESULT)
|
845 |
storage_units = [(st, st + "_key", [st + "_params"]) for st in |
846 |
constants.STORAGE_TYPES] |
847 |
|
848 |
backend.GetNodeInfo(storage_units, None)
|
849 |
|
850 |
call_args_list = backend._ApplyStorageInfoFunction.call_args_list |
851 |
self.assertEqual(len(constants.STORAGE_TYPES), len(call_args_list)) |
852 |
for call in call_args_list: |
853 |
storage_type, storage_key, storage_params = call[0]
|
854 |
self.assertEqual(storage_type + "_key", storage_key) |
855 |
self.assertEqual([storage_type + "_params"], storage_params) |
856 |
self.assertTrue(storage_type in constants.STORAGE_TYPES) |
857 |
backend._ApplyStorageInfoFunction = orig_fn |
858 |
|
859 |
|
860 |
class TestSpaceReportingConstants(unittest.TestCase): |
861 |
"""Ensures consistency between STS_REPORT and backend.
|
862 |
|
863 |
These tests ensure, that the constant 'STS_REPORT' is consistent
|
864 |
with the implementation of invoking space reporting functions
|
865 |
in backend.py. Once space reporting is available for all types,
|
866 |
the constant can be removed and these tests as well.
|
867 |
|
868 |
"""
|
869 |
|
870 |
REPORTING = set(constants.STS_REPORT)
|
871 |
NOT_REPORTING = set(constants.STORAGE_TYPES) - REPORTING
|
872 |
|
873 |
def testAllReportingTypesHaveAReportingFunction(self): |
874 |
for storage_type in TestSpaceReportingConstants.REPORTING: |
875 |
self.assertTrue(backend._STORAGE_TYPE_INFO_FN[storage_type] is not None) |
876 |
|
877 |
def testAllNotReportingTypesDontHaveFunction(self): |
878 |
for storage_type in TestSpaceReportingConstants.NOT_REPORTING: |
879 |
self.assertEqual(None, backend._STORAGE_TYPE_INFO_FN[storage_type]) |
880 |
|
881 |
|
882 |
if __name__ == "__main__": |
883 |
testutils.GanetiTestProgram() |