This function will also be used in tools/move-instance.
Signed-off-by: Michael Hanselmann <[email protected]>
---
lib/cli.py | 36 +++++++++++++++++++++++++-----------
test/ganeti.cli_unittest.py | 21 +++++++++++++++++++++
2 files changed, 46 insertions(+), 11 deletions(-)
diff --git a/lib/cli.py b/lib/cli.py
index e339c4f..2708a45 100644
--- a/lib/cli.py
+++ b/lib/cli.py
@@ -1829,6 +1829,30 @@ def GenericMain(commands, override=None, aliases=None):
return result
+def ParseNicOption(optvalue):
+ """Parses the value of the --net option(s).
+
+ """
+ try:
+ nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
+ except (TypeError, ValueError), err:
+ raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
+
+ nics = [{}] * nic_max
+ for nidx, ndict in optvalue:
+ nidx = int(nidx)
+
+ if not isinstance(ndict, dict):
+ raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
+ " got %s" % (nidx, ndict))
+
+ utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
+
+ nics[nidx] = ndict
+
+ return nics
+
+
def GenericInstanceCreate(mode, opts, args):
"""Add an instance to the cluster via either creation or import.
@@ -1850,17 +1874,7 @@ def GenericInstanceCreate(mode, opts, args):
hypervisor, hvparams = opts.hypervisor
if opts.nics:
- try:
- nic_max = max(int(nidx[0]) + 1 for nidx in opts.nics)
- except ValueError, err:
- raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
- nics = [{}] * nic_max
- for nidx, ndict in opts.nics:
- nidx = int(nidx)
- if not isinstance(ndict, dict):
- msg = "Invalid nic/%d value: expected dict, got %s" % (nidx, ndict)
- raise errors.OpPrereqError(msg)
- nics[nidx] = ndict
+ nics = ParseNicOption(opts.nics)
elif opts.no_nics:
# no nics
nics = []
diff --git a/test/ganeti.cli_unittest.py b/test/ganeti.cli_unittest.py
index e2f1032..64e3ddb 100755
--- a/test/ganeti.cli_unittest.py
+++ b/test/ganeti.cli_unittest.py
@@ -450,5 +450,26 @@ class TestConstants(unittest.TestCase):
sorted(constants.OP_PRIO_SUBMIT_VALID, reverse=True))
+class TestParseNicOption(unittest.TestCase):
+ def test(self):
+ self.assertEqual(cli.ParseNicOption([("0", { "link": "eth0", })]),
+ [{ "link": "eth0", }])
+ self.assertEqual(cli.ParseNicOption([("5", { "ip": "192.0.2.7", })]),
+ [{}, {}, {}, {}, {}, { "ip": "192.0.2.7", }])
+
+ def testErrors(self):
+ for i in [None, "", "abc", "zero", "Hello World", "\0", []]:
+ self.assertRaises(errors.OpPrereqError, cli.ParseNicOption,
+ [(i, { "link": "eth0", })])
+ self.assertRaises(errors.OpPrereqError, cli.ParseNicOption,
+ [("0", i)])
+
+ self.assertRaises(errors.TypeEnforcementError, cli.ParseNicOption,
+ [(0, { True: False, })])
+
+ self.assertRaises(errors.TypeEnforcementError, cli.ParseNicOption,
+ [(3, { "mode": [], })])
+
+
if __name__ == '__main__':
testutils.GanetiTestProgram()
--
1.7.0.4