ganeti.cmdlib_unittest.py 42.6 KB
Newer Older
1
2
3
#!/usr/bin/python
#

4
# Copyright (C) 2008, 2011, 2012 Google Inc.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20
21
22
23
24
25
26
27


"""Script for unittesting the cmdlib module"""


import os
import unittest
import time
28
29
import tempfile
import shutil
30
import operator
31
import itertools
32
import copy
33

Michael Hanselmann's avatar
Michael Hanselmann committed
34
from ganeti import constants
Iustin Pop's avatar
Iustin Pop committed
35
from ganeti import mcpu
36
from ganeti import cmdlib
Iustin Pop's avatar
Iustin Pop committed
37
from ganeti import opcodes
38
from ganeti import errors
Iustin Pop's avatar
Iustin Pop committed
39
from ganeti import utils
40
from ganeti import luxi
41
from ganeti import ht
42
from ganeti import objects
43
44
from ganeti import compat
from ganeti import rpc
45
from ganeti import pathutils
René Nussbaumer's avatar
René Nussbaumer committed
46
from ganeti.masterd import iallocator
47
from ganeti.hypervisor import hv_xen
48

49
import testutils
50
import mocks
51

52

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class TestCertVerification(testutils.GanetiTestCase):
  def setUp(self):
    testutils.GanetiTestCase.setUp(self)

    self.tmpdir = tempfile.mkdtemp()

  def tearDown(self):
    shutil.rmtree(self.tmpdir)

  def testVerifyCertificate(self):
    cmdlib._VerifyCertificate(self._TestDataFilename("cert1.pem"))

    nonexist_filename = os.path.join(self.tmpdir, "does-not-exist")

    (errcode, msg) = cmdlib._VerifyCertificate(nonexist_filename)
68
    self.assertEqual(errcode, cmdlib.LUClusterVerifyConfig.ETYPE_ERROR)
69
70

    # Try to load non-certificate file
71
    invalid_cert = self._TestDataFilename("bdev-net.txt")
72
    (errcode, msg) = cmdlib._VerifyCertificate(invalid_cert)
73
    self.assertEqual(errcode, cmdlib.LUClusterVerifyConfig.ETYPE_ERROR)
74
75


Iustin Pop's avatar
Iustin Pop committed
76
77
78
79
80
class TestOpcodeParams(testutils.GanetiTestCase):
  def testParamsStructures(self):
    for op in sorted(mcpu.Processor.DISPATCH_TABLE):
      lu = mcpu.Processor.DISPATCH_TABLE[op]
      lu_name = lu.__name__
81
82
83
84
85
86
      self.failIf(hasattr(lu, "_OP_REQP"),
                  msg=("LU '%s' has old-style _OP_REQP" % lu_name))
      self.failIf(hasattr(lu, "_OP_DEFS"),
                  msg=("LU '%s' has old-style _OP_DEFS" % lu_name))
      self.failIf(hasattr(lu, "_OP_PARAMS"),
                  msg=("LU '%s' has old-style _OP_PARAMS" % lu_name))
Iustin Pop's avatar
Iustin Pop committed
87
88


89
90
91
92
93
94
95
class TestIAllocatorChecks(testutils.GanetiTestCase):
  def testFunction(self):
    class TestLU(object):
      def __init__(self, opcode):
        self.cfg = mocks.FakeConfig()
        self.op = opcode

96
97
    class OpTest(opcodes.OpCode):
       OP_PARAMS = [
98
99
        ("iallocator", None, ht.NoType, None),
        ("node", None, ht.NoType, None),
100
        ]
101
102
103
104

    default_iallocator = mocks.FakeConfig().GetDefaultIAllocator()
    other_iallocator = default_iallocator + "_not"

105
    op = OpTest()
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
    lu = TestLU(op)

    c_i = lambda: cmdlib._CheckIAllocatorOrNode(lu, "iallocator", "node")

    # Neither node nor iallocator given
    op.iallocator = None
    op.node = None
    c_i()
    self.assertEqual(lu.op.iallocator, default_iallocator)
    self.assertEqual(lu.op.node, None)

    # Both, iallocator and node given
    op.iallocator = "test"
    op.node = "test"
    self.assertRaises(errors.OpPrereqError, c_i)

    # Only iallocator given
    op.iallocator = other_iallocator
    op.node = None
    c_i()
    self.assertEqual(lu.op.iallocator, other_iallocator)
    self.assertEqual(lu.op.node, None)

    # Only node given
    op.iallocator = None
    op.node = "node"
    c_i()
    self.assertEqual(lu.op.iallocator, None)
    self.assertEqual(lu.op.node, "node")

    # No node, iallocator or default iallocator
    op.iallocator = None
    op.node = None
    lu.cfg.GetDefaultIAllocator = lambda: None
    self.assertRaises(errors.OpPrereqError, c_i)


143
class TestLUTestJqueue(unittest.TestCase):
144
  def test(self):
145
    self.assert_(cmdlib.LUTestJqueue._CLIENT_CONNECT_TIMEOUT <
146
147
148
149
150
                 (luxi.WFJC_TIMEOUT * 0.75),
                 msg=("Client timeout too high, might not notice bugs"
                      " in WaitForJobChange"))


Michael Hanselmann's avatar
Michael Hanselmann committed
151
152
153
class TestLUQuery(unittest.TestCase):
  def test(self):
    self.assertEqual(sorted(cmdlib._QUERY_IMPL.keys()),
154
                     sorted(constants.QR_VIA_OP))
Michael Hanselmann's avatar
Michael Hanselmann committed
155

156
157
    assert constants.QR_NODE in constants.QR_VIA_OP
    assert constants.QR_INSTANCE in constants.QR_VIA_OP
Michael Hanselmann's avatar
Michael Hanselmann committed
158

159
    for i in constants.QR_VIA_OP:
Michael Hanselmann's avatar
Michael Hanselmann committed
160
161
162
163
164
165
166
      self.assert_(cmdlib._GetQueryImplementation(i))

    self.assertRaises(errors.OpPrereqError, cmdlib._GetQueryImplementation, "")
    self.assertRaises(errors.OpPrereqError, cmdlib._GetQueryImplementation,
                      "xyz")


167
class TestLUGroupAssignNodes(unittest.TestCase):
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

  def testCheckAssignmentForSplitInstances(self):
    node_data = dict((name, objects.Node(name=name, group=group))
                     for (name, group) in [("n1a", "g1"), ("n1b", "g1"),
                                           ("n2a", "g2"), ("n2b", "g2"),
                                           ("n3a", "g3"), ("n3b", "g3"),
                                           ("n3c", "g3"),
                                           ])

    def Instance(name, pnode, snode):
      if snode is None:
        disks = []
        disk_template = constants.DT_DISKLESS
      else:
        disks = [objects.Disk(dev_type=constants.LD_DRBD8,
                              logical_id=[pnode, snode, 1, 17, 17])]
        disk_template = constants.DT_DRBD8

      return objects.Instance(name=name, primary_node=pnode, disks=disks,
                              disk_template=disk_template)

    instance_data = dict((name, Instance(name, pnode, snode))
                         for name, pnode, snode in [("inst1a", "n1a", "n1b"),
                                                    ("inst1b", "n1b", "n1a"),
                                                    ("inst2a", "n2a", "n2b"),
                                                    ("inst3a", "n3a", None),
                                                    ("inst3b", "n3b", "n1b"),
                                                    ("inst3c", "n3b", "n2b"),
                                                    ])

    # Test first with the existing state.
    (new, prev) = \
200
      cmdlib.LUGroupAssignNodes.CheckAssignmentForSplitInstances([],
201
202
203
204
205
206
207
208
                                                                 node_data,
                                                                 instance_data)

    self.assertEqual([], new)
    self.assertEqual(set(["inst3b", "inst3c"]), set(prev))

    # And now some changes.
    (new, prev) = \
209
      cmdlib.LUGroupAssignNodes.CheckAssignmentForSplitInstances([("n1b",
210
211
212
213
214
215
216
217
                                                                   "g3")],
                                                                 node_data,
                                                                 instance_data)

    self.assertEqual(set(["inst1a", "inst1b"]), set(new))
    self.assertEqual(set(["inst3c"]), set(prev))


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
class TestClusterVerifySsh(unittest.TestCase):
  def testMultipleGroups(self):
    fn = cmdlib.LUClusterVerifyGroup._SelectSshCheckNodes
    mygroupnodes = [
      objects.Node(name="node20", group="my", offline=False),
      objects.Node(name="node21", group="my", offline=False),
      objects.Node(name="node22", group="my", offline=False),
      objects.Node(name="node23", group="my", offline=False),
      objects.Node(name="node24", group="my", offline=False),
      objects.Node(name="node25", group="my", offline=False),
      objects.Node(name="node26", group="my", offline=True),
      ]
    nodes = [
      objects.Node(name="node1", group="g1", offline=True),
      objects.Node(name="node2", group="g1", offline=False),
      objects.Node(name="node3", group="g1", offline=False),
      objects.Node(name="node4", group="g1", offline=True),
      objects.Node(name="node5", group="g1", offline=False),
      objects.Node(name="node10", group="xyz", offline=False),
      objects.Node(name="node11", group="xyz", offline=False),
      objects.Node(name="node40", group="alloff", offline=True),
      objects.Node(name="node41", group="alloff", offline=True),
      objects.Node(name="node50", group="aaa", offline=False),
      ] + mygroupnodes
    assert not utils.FindDuplicates(map(operator.attrgetter("name"), nodes))

    (online, perhost) = fn(mygroupnodes, "my", nodes)
    self.assertEqual(online, ["node%s" % i for i in range(20, 26)])
    self.assertEqual(set(perhost.keys()), set(online))

    self.assertEqual(perhost, {
      "node20": ["node10", "node2", "node50"],
      "node21": ["node11", "node3", "node50"],
      "node22": ["node10", "node5", "node50"],
      "node23": ["node11", "node2", "node50"],
      "node24": ["node10", "node3", "node50"],
      "node25": ["node11", "node5", "node50"],
      })

  def testSingleGroup(self):
    fn = cmdlib.LUClusterVerifyGroup._SelectSshCheckNodes
    nodes = [
      objects.Node(name="node1", group="default", offline=True),
      objects.Node(name="node2", group="default", offline=False),
      objects.Node(name="node3", group="default", offline=False),
      objects.Node(name="node4", group="default", offline=True),
      ]
    assert not utils.FindDuplicates(map(operator.attrgetter("name"), nodes))

    (online, perhost) = fn(nodes, "default", nodes)
    self.assertEqual(online, ["node2", "node3"])
    self.assertEqual(set(perhost.keys()), set(online))

    self.assertEqual(perhost, {
      "node2": [],
      "node3": [],
      })


277
278
279
class TestClusterVerifyFiles(unittest.TestCase):
  @staticmethod
  def _FakeErrorIf(errors, cond, ecode, item, msg, *args, **kwargs):
280
    assert ((ecode == constants.CV_ENODEFILECHECK and
281
             ht.TNonEmptyString(item)) or
282
            (ecode == constants.CV_ECLUSTERFILECHECK and
283
284
285
286
287
288
289
290
291
292
293
294
295
296
             item is None))

    if args:
      msg = msg % args

    if cond:
      errors.append((item, msg))

  _VerifyFiles = cmdlib.LUClusterVerifyGroup._VerifyFiles

  def test(self):
    errors = []
    master_name = "master.example.com"
    nodeinfo = [
297
298
299
300
301
302
      objects.Node(name=master_name, offline=False, vm_capable=True),
      objects.Node(name="node2.example.com", offline=False, vm_capable=True),
      objects.Node(name="node3.example.com", master_candidate=True,
                   vm_capable=False),
      objects.Node(name="node4.example.com", offline=False, vm_capable=True),
      objects.Node(name="nodata.example.com", offline=False, vm_capable=True),
303
304
305
306
307
      objects.Node(name="offline.example.com", offline=True),
      ]
    cluster = objects.Cluster(modify_etc_hosts=True,
                              enabled_hypervisors=[constants.HT_XEN_HVM])
    files_all = set([
308
309
310
      pathutils.CLUSTER_DOMAIN_SECRET_FILE,
      pathutils.RAPI_CERT_FILE,
      pathutils.RAPI_USERS_FILE,
311
      ])
312
    files_opt = set([
313
      pathutils.RAPI_USERS_FILE,
314
      hv_xen.XL_CONFIG_FILE,
315
      pathutils.VNC_PASSWORD_FILE,
316
317
      ])
    files_mc = set([
318
      pathutils.CLUSTER_CONF_FILE,
319
      ])
320
321
322
    files_vm = set([
      hv_xen.XEND_CONFIG_FILE,
      hv_xen.XL_CONFIG_FILE,
323
      pathutils.VNC_PASSWORD_FILE,
324
      ])
325
326
327
    nvinfo = {
      master_name: rpc.RpcResult(data=(True, {
        constants.NV_FILELIST: {
328
329
330
          pathutils.CLUSTER_CONF_FILE: "82314f897f38b35f9dab2f7c6b1593e0",
          pathutils.RAPI_CERT_FILE: "babbce8f387bc082228e544a2146fee4",
          pathutils.CLUSTER_DOMAIN_SECRET_FILE: "cds-47b5b3f19202936bb4",
331
332
          hv_xen.XEND_CONFIG_FILE: "b4a8a824ab3cac3d88839a9adeadf310",
          hv_xen.XL_CONFIG_FILE: "77935cee92afd26d162f9e525e3d49b9"
333
334
335
        }})),
      "node2.example.com": rpc.RpcResult(data=(True, {
        constants.NV_FILELIST: {
336
          pathutils.RAPI_CERT_FILE: "97f0356500e866387f4b84233848cc4a",
337
          hv_xen.XEND_CONFIG_FILE: "b4a8a824ab3cac3d88839a9adeadf310",
338
339
340
341
          }
        })),
      "node3.example.com": rpc.RpcResult(data=(True, {
        constants.NV_FILELIST: {
342
343
          pathutils.RAPI_CERT_FILE: "97f0356500e866387f4b84233848cc4a",
          pathutils.CLUSTER_DOMAIN_SECRET_FILE: "cds-47b5b3f19202936bb4",
344
345
346
347
          }
        })),
      "node4.example.com": rpc.RpcResult(data=(True, {
        constants.NV_FILELIST: {
348
349
350
351
          pathutils.RAPI_CERT_FILE: "97f0356500e866387f4b84233848cc4a",
          pathutils.CLUSTER_CONF_FILE: "conf-a6d4b13e407867f7a7b4f0f232a8f527",
          pathutils.CLUSTER_DOMAIN_SECRET_FILE: "cds-47b5b3f19202936bb4",
          pathutils.RAPI_USERS_FILE: "rapiusers-ea3271e8d810ef3",
352
          hv_xen.XL_CONFIG_FILE: "77935cee92afd26d162f9e525e3d49b9"
353
354
355
356
357
358
359
360
361
          }
        })),
      "nodata.example.com": rpc.RpcResult(data=(True, {})),
      "offline.example.com": rpc.RpcResult(offline=True),
      }
    assert set(nvinfo.keys()) == set(map(operator.attrgetter("name"), nodeinfo))

    self._VerifyFiles(compat.partial(self._FakeErrorIf, errors), nodeinfo,
                      master_name, nvinfo,
362
                      (files_all, files_opt, files_mc, files_vm))
363
364
365
    self.assertEqual(sorted(errors), sorted([
      (None, ("File %s found with 2 different checksums (variant 1 on"
              " node2.example.com, node3.example.com, node4.example.com;"
366
              " variant 2 on master.example.com)" % pathutils.RAPI_CERT_FILE)),
367
      (None, ("File %s is missing from node(s) node2.example.com" %
368
              pathutils.CLUSTER_DOMAIN_SECRET_FILE)),
369
      (None, ("File %s should not exist on node(s) node4.example.com" %
370
              pathutils.CLUSTER_CONF_FILE)),
371
372
      (None, ("File %s is missing from node(s) node4.example.com" %
              hv_xen.XEND_CONFIG_FILE)),
373
      (None, ("File %s is missing from node(s) node3.example.com" %
374
              pathutils.CLUSTER_CONF_FILE)),
375
376
      (None, ("File %s found with 2 different checksums (variant 1 on"
              " master.example.com; variant 2 on node4.example.com)" %
377
              pathutils.CLUSTER_CONF_FILE)),
378
379
      (None, ("File %s is optional, but it must exist on all or no nodes (not"
              " found on master.example.com, node2.example.com,"
380
              " node3.example.com)" % pathutils.RAPI_USERS_FILE)),
381
382
      (None, ("File %s is optional, but it must exist on all or no nodes (not"
              " found on node2.example.com)" % hv_xen.XL_CONFIG_FILE)),
383
384
385
386
      ("nodata.example.com", "Node did not return file checksum data"),
      ]))


387
class _FakeLU:
388
  def __init__(self, cfg=NotImplemented, proc=NotImplemented):
389
390
    self.warning_log = []
    self.info_log = []
391
    self.cfg = cfg
392
    self.proc = proc
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413

  def LogWarning(self, text, *args):
    self.warning_log.append((text, args))

  def LogInfo(self, text, *args):
    self.info_log.append((text, args))


class TestLoadNodeEvacResult(unittest.TestCase):
  def testSuccess(self):
    for moved in [[], [
      ("inst20153.example.com", "grp2", ["nodeA4509", "nodeB2912"]),
      ]]:
      for early_release in [False, True]:
        for use_nodes in [False, True]:
          jobs = [
            [opcodes.OpInstanceReplaceDisks().__getstate__()],
            [opcodes.OpInstanceMigrate().__getstate__()],
            ]

          alloc_result = (moved, [], jobs)
René Nussbaumer's avatar
René Nussbaumer committed
414
          assert iallocator._NEVAC_RESULT(alloc_result)
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442

          lu = _FakeLU()
          result = cmdlib._LoadNodeEvacResult(lu, alloc_result,
                                              early_release, use_nodes)

          if moved:
            (_, (info_args, )) = lu.info_log.pop(0)
            for (instname, instgroup, instnodes) in moved:
              self.assertTrue(instname in info_args)
              if use_nodes:
                for i in instnodes:
                  self.assertTrue(i in info_args)
              else:
                self.assertTrue(instgroup in info_args)

          self.assertFalse(lu.info_log)
          self.assertFalse(lu.warning_log)

          for op in itertools.chain(*result):
            if hasattr(op.__class__, "early_release"):
              self.assertEqual(op.early_release, early_release)
            else:
              self.assertFalse(hasattr(op, "early_release"))

  def testFailed(self):
    alloc_result = ([], [
      ("inst5191.example.com", "errormsg21178"),
      ], [])
René Nussbaumer's avatar
René Nussbaumer committed
443
    assert iallocator._NEVAC_RESULT(alloc_result)
444
445
446
447
448
449
450
451
452
453
454

    lu = _FakeLU()
    self.assertRaises(errors.OpExecError, cmdlib._LoadNodeEvacResult,
                      lu, alloc_result, False, False)
    self.assertFalse(lu.info_log)
    (_, (args, )) = lu.warning_log.pop(0)
    self.assertTrue("inst5191.example.com" in args)
    self.assertTrue("errormsg21178" in args)
    self.assertFalse(lu.warning_log)


455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
class TestUpdateAndVerifySubDict(unittest.TestCase):
  def setUp(self):
    self.type_check = {
        "a": constants.VTYPE_INT,
        "b": constants.VTYPE_STRING,
        "c": constants.VTYPE_BOOL,
        "d": constants.VTYPE_STRING,
        }

  def test(self):
    old_test = {
      "foo": {
        "d": "blubb",
        "a": 321,
        },
      "baz": {
        "a": 678,
        "b": "678",
        "c": True,
        },
      }
    test = {
      "foo": {
        "a": 123,
        "b": "123",
        "c": True,
        },
      "bar": {
        "a": 321,
        "b": "321",
        "c": False,
        },
      }

    mv = {
      "foo": {
        "a": 123,
        "b": "123",
        "c": True,
        "d": "blubb"
        },
      "bar": {
        "a": 321,
        "b": "321",
        "c": False,
        },
      "baz": {
        "a": 678,
        "b": "678",
        "c": True,
        },
      }

    verified = cmdlib._UpdateAndVerifySubDict(old_test, test, self.type_check)
    self.assertEqual(verified, mv)

  def testWrong(self):
    test = {
      "foo": {
        "a": "blubb",
        "b": "123",
        "c": True,
        },
      "bar": {
        "a": 321,
        "b": "321",
        "c": False,
        },
      }

    self.assertRaises(errors.TypeEnforcementError,
                      cmdlib._UpdateAndVerifySubDict, {}, test, self.type_check)


529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
class TestHvStateHelper(unittest.TestCase):
  def testWithoutOpData(self):
    self.assertEqual(cmdlib._MergeAndVerifyHvState(None, NotImplemented), None)

  def testWithoutOldData(self):
    new = {
      constants.HT_XEN_PVM: {
        constants.HVST_MEMORY_TOTAL: 4096,
        },
      }
    self.assertEqual(cmdlib._MergeAndVerifyHvState(new, None), new)

  def testWithWrongHv(self):
    new = {
      "i-dont-exist": {
        constants.HVST_MEMORY_TOTAL: 4096,
        },
      }
    self.assertRaises(errors.OpPrereqError, cmdlib._MergeAndVerifyHvState, new,
                      None)

class TestDiskStateHelper(unittest.TestCase):
  def testWithoutOpData(self):
    self.assertEqual(cmdlib._MergeAndVerifyDiskState(None, NotImplemented),
                     None)

  def testWithoutOldData(self):
    new = {
      constants.LD_LV: {
        "xenvg": {
          constants.DS_DISK_RESERVED: 1024,
          },
        },
      }
    self.assertEqual(cmdlib._MergeAndVerifyDiskState(new, None), new)

  def testWithWrongStorageType(self):
    new = {
      "i-dont-exist": {
        "xenvg": {
          constants.DS_DISK_RESERVED: 1024,
          },
        },
      }
    self.assertRaises(errors.OpPrereqError, cmdlib._MergeAndVerifyDiskState,
                      new, None)


577
578
579
580
581
582
583
584
585
586
587
588
589
590
class TestComputeMinMaxSpec(unittest.TestCase):
  def setUp(self):
    self.ipolicy = {
      constants.ISPECS_MAX: {
        constants.ISPEC_MEM_SIZE: 512,
        constants.ISPEC_DISK_SIZE: 1024,
        },
      constants.ISPECS_MIN: {
        constants.ISPEC_MEM_SIZE: 128,
        constants.ISPEC_DISK_COUNT: 1,
        },
      }

  def testNoneValue(self):
591
    self.assertTrue(cmdlib._ComputeMinMaxSpec(constants.ISPEC_MEM_SIZE, None,
592
593
594
                                              self.ipolicy, None) is None)

  def testAutoValue(self):
595
    self.assertTrue(cmdlib._ComputeMinMaxSpec(constants.ISPEC_MEM_SIZE, None,
596
597
598
599
                                              self.ipolicy,
                                              constants.VALUE_AUTO) is None)

  def testNotDefined(self):
600
    self.assertTrue(cmdlib._ComputeMinMaxSpec(constants.ISPEC_NIC_COUNT, None,
601
602
603
                                              self.ipolicy, 3) is None)

  def testNoMinDefined(self):
604
    self.assertTrue(cmdlib._ComputeMinMaxSpec(constants.ISPEC_DISK_SIZE, None,
605
606
607
                                              self.ipolicy, 128) is None)

  def testNoMaxDefined(self):
608
    self.assertTrue(cmdlib._ComputeMinMaxSpec(constants.ISPEC_DISK_COUNT, None,
609
610
611
612
613
614
615
616
617
                                                self.ipolicy, 16) is None)

  def testOutOfRange(self):
    for (name, val) in ((constants.ISPEC_MEM_SIZE, 64),
                        (constants.ISPEC_MEM_SIZE, 768),
                        (constants.ISPEC_DISK_SIZE, 4096),
                        (constants.ISPEC_DISK_COUNT, 0)):
      min_v = self.ipolicy[constants.ISPECS_MIN].get(name, val)
      max_v = self.ipolicy[constants.ISPECS_MAX].get(name, val)
618
619
      self.assertEqual(cmdlib._ComputeMinMaxSpec(name, None,
                                                 self.ipolicy, val),
620
621
                       "%s value %s is not in range [%s, %s]" %
                       (name, val,min_v, max_v))
622
623
624
625
      self.assertEqual(cmdlib._ComputeMinMaxSpec(name, "1",
                                                 self.ipolicy, val),
                       "%s/1 value %s is not in range [%s, %s]" %
                       (name, val,min_v, max_v))
626
627
628
629
630
631
632
633
634

  def test(self):
    for (name, val) in ((constants.ISPEC_MEM_SIZE, 256),
                        (constants.ISPEC_MEM_SIZE, 128),
                        (constants.ISPEC_MEM_SIZE, 512),
                        (constants.ISPEC_DISK_SIZE, 1024),
                        (constants.ISPEC_DISK_SIZE, 0),
                        (constants.ISPEC_DISK_COUNT, 1),
                        (constants.ISPEC_DISK_COUNT, 5)):
635
      self.assertTrue(cmdlib._ComputeMinMaxSpec(name, None, self.ipolicy, val)
636
637
638
                      is None)


639
def _ValidateComputeMinMaxSpec(name, *_):
640
641
642
643
644
645
646
647
  assert name in constants.ISPECS_PARAMETERS
  return None


class _SpecWrapper:
  def __init__(self, spec):
    self.spec = spec

648
  def ComputeMinMaxSpec(self, *args):
649
650
651
652
653
    return self.spec.pop(0)


class TestComputeIPolicySpecViolation(unittest.TestCase):
  def test(self):
654
    compute_fn = _ValidateComputeMinMaxSpec
655
    ret = cmdlib._ComputeIPolicySpecViolation(NotImplemented, 1024, 1, 1, 1,
656
                                              [1024], 1, _compute_fn=compute_fn)
657
658
659
660
    self.assertEqual(ret, [])

  def testInvalidArguments(self):
    self.assertRaises(AssertionError, cmdlib._ComputeIPolicySpecViolation,
661
                      NotImplemented, 1024, 1, 1, 1, [], 1)
662
663

  def testInvalidSpec(self):
664
    spec = _SpecWrapper([None, False, "foo", None, "bar", None])
665
    compute_fn = spec.ComputeMinMaxSpec
666
    ret = cmdlib._ComputeIPolicySpecViolation(NotImplemented, 1024, 1, 1, 1,
667
                                              [1024], 1, _compute_fn=compute_fn)
668
669
670
671
672
    self.assertEqual(ret, ["foo", "bar"])
    self.assertFalse(spec.spec)


class _StubComputeIPolicySpecViolation:
673
674
  def __init__(self, mem_size, cpu_count, disk_count, nic_count, disk_sizes,
               spindle_use):
675
676
677
678
679
    self.mem_size = mem_size
    self.cpu_count = cpu_count
    self.disk_count = disk_count
    self.nic_count = nic_count
    self.disk_sizes = disk_sizes
680
    self.spindle_use = spindle_use
681

682
683
  def __call__(self, _, mem_size, cpu_count, disk_count, nic_count, disk_sizes,
               spindle_use):
684
685
686
687
688
    assert self.mem_size == mem_size
    assert self.cpu_count == cpu_count
    assert self.disk_count == disk_count
    assert self.nic_count == nic_count
    assert self.disk_sizes == disk_sizes
689
    assert self.spindle_use == spindle_use
690
691
692
693
694
695
696
697
698

    return []


class TestComputeIPolicyInstanceViolation(unittest.TestCase):
  def test(self):
    beparams = {
      constants.BE_MAXMEM: 2048,
      constants.BE_VCPUS: 2,
699
      constants.BE_SPINDLE_USE: 4,
700
701
702
      }
    disks = [objects.Disk(size=512)]
    instance = objects.Instance(beparams=beparams, disks=disks, nics=[])
703
    stub = _StubComputeIPolicySpecViolation(2048, 2, 1, 0, [512], 4)
704
705
706
707
708
709
710
711
712
713
714
715
716
    ret = cmdlib._ComputeIPolicyInstanceViolation(NotImplemented, instance,
                                                  _compute_fn=stub)
    self.assertEqual(ret, [])


class TestComputeIPolicyInstanceSpecViolation(unittest.TestCase):
  def test(self):
    ispec = {
      constants.ISPEC_MEM_SIZE: 2048,
      constants.ISPEC_CPU_COUNT: 2,
      constants.ISPEC_DISK_COUNT: 1,
      constants.ISPEC_DISK_SIZE: [512],
      constants.ISPEC_NIC_COUNT: 0,
717
      constants.ISPEC_SPINDLE_USE: 1,
718
      }
719
    stub = _StubComputeIPolicySpecViolation(2048, 2, 1, 0, [512], 1)
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
    ret = cmdlib._ComputeIPolicyInstanceSpecViolation(NotImplemented, ispec,
                                                      _compute_fn=stub)
    self.assertEqual(ret, [])


class _CallRecorder:
  def __init__(self, return_value=None):
    self.called = False
    self.return_value = return_value

  def __call__(self, *args):
    self.called = True
    return self.return_value


class TestComputeIPolicyNodeViolation(unittest.TestCase):
  def setUp(self):
    self.recorder = _CallRecorder(return_value=[])

  def testSameGroup(self):
    ret = cmdlib._ComputeIPolicyNodeViolation(NotImplemented, NotImplemented,
                                              "foo", "foo",
                                              _compute_fn=self.recorder)
    self.assertFalse(self.recorder.called)
    self.assertEqual(ret, [])

  def testDifferentGroup(self):
    ret = cmdlib._ComputeIPolicyNodeViolation(NotImplemented, NotImplemented,
                                              "foo", "bar",
                                              _compute_fn=self.recorder)
    self.assertTrue(self.recorder.called)
    self.assertEqual(ret, [])


754
755
756
757
758
759
760
761
class _FakeConfigForTargetNodeIPolicy:
  def __init__(self, node_info=NotImplemented):
    self._node_info = node_info

  def GetNodeInfo(self, _):
    return self._node_info


762
763
class TestCheckTargetNodeIPolicy(unittest.TestCase):
  def setUp(self):
764
    self.instance = objects.Instance(primary_node="blubb")
765
    self.target_node = objects.Node(group="bar")
766
767
768
    node_info = objects.Node(group="foo")
    fake_cfg = _FakeConfigForTargetNodeIPolicy(node_info=node_info)
    self.lu = _FakeLU(cfg=fake_cfg)
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796

  def testNoViolation(self):
    compute_recoder = _CallRecorder(return_value=[])
    cmdlib._CheckTargetNodeIPolicy(self.lu, NotImplemented, self.instance,
                                   self.target_node,
                                   _compute_fn=compute_recoder)
    self.assertTrue(compute_recoder.called)
    self.assertEqual(self.lu.warning_log, [])

  def testNoIgnore(self):
    compute_recoder = _CallRecorder(return_value=["mem_size not in range"])
    self.assertRaises(errors.OpPrereqError, cmdlib._CheckTargetNodeIPolicy,
                      self.lu, NotImplemented, self.instance, self.target_node,
                      _compute_fn=compute_recoder)
    self.assertTrue(compute_recoder.called)
    self.assertEqual(self.lu.warning_log, [])

  def testIgnoreViolation(self):
    compute_recoder = _CallRecorder(return_value=["mem_size not in range"])
    cmdlib._CheckTargetNodeIPolicy(self.lu, NotImplemented, self.instance,
                                   self.target_node, ignore=True,
                                   _compute_fn=compute_recoder)
    self.assertTrue(compute_recoder.called)
    msg = ("Instance does not meet target node group's (bar) instance policy:"
           " mem_size not in range")
    self.assertEqual(self.lu.warning_log, [(msg, ())])


797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
class TestApplyContainerMods(unittest.TestCase):
  def testEmptyContainer(self):
    container = []
    chgdesc = []
    cmdlib.ApplyContainerMods("test", container, chgdesc, [], None, None, None)
    self.assertEqual(container, [])
    self.assertEqual(chgdesc, [])

  def testAdd(self):
    container = []
    chgdesc = []
    mods = cmdlib.PrepareContainerMods([
      (constants.DDM_ADD, -1, "Hello"),
      (constants.DDM_ADD, -1, "World"),
      (constants.DDM_ADD, 0, "Start"),
      (constants.DDM_ADD, -1, "End"),
      ], None)
    cmdlib.ApplyContainerMods("test", container, chgdesc, mods,
                              None, None, None)
    self.assertEqual(container, ["Start", "Hello", "World", "End"])
    self.assertEqual(chgdesc, [])

819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
    mods = cmdlib.PrepareContainerMods([
      (constants.DDM_ADD, 0, "zero"),
      (constants.DDM_ADD, 3, "Added"),
      (constants.DDM_ADD, 5, "four"),
      (constants.DDM_ADD, 7, "xyz"),
      ], None)
    cmdlib.ApplyContainerMods("test", container, chgdesc, mods,
                              None, None, None)
    self.assertEqual(container,
                     ["zero", "Start", "Hello", "Added", "World", "four",
                      "End", "xyz"])
    self.assertEqual(chgdesc, [])

    for idx in [-2, len(container) + 1]:
      mods = cmdlib.PrepareContainerMods([
        (constants.DDM_ADD, idx, "error"),
        ], None)
      self.assertRaises(IndexError, cmdlib.ApplyContainerMods,
                        "test", container, None, mods, None, None, None)

839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
  def testRemoveError(self):
    for idx in [0, 1, 2, 100, -1, -4]:
      mods = cmdlib.PrepareContainerMods([
        (constants.DDM_REMOVE, idx, None),
        ], None)
      self.assertRaises(IndexError, cmdlib.ApplyContainerMods,
                        "test", [], None, mods, None, None, None)

    mods = cmdlib.PrepareContainerMods([
      (constants.DDM_REMOVE, 0, object()),
      ], None)
    self.assertRaises(AssertionError, cmdlib.ApplyContainerMods,
                      "test", [""], None, mods, None, None, None)

  def testAddError(self):
854
    for idx in range(-100, -1) + [100]:
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
      mods = cmdlib.PrepareContainerMods([
        (constants.DDM_ADD, idx, None),
        ], None)
      self.assertRaises(IndexError, cmdlib.ApplyContainerMods,
                        "test", [], None, mods, None, None, None)

  def testRemove(self):
    container = ["item 1", "item 2"]
    mods = cmdlib.PrepareContainerMods([
      (constants.DDM_ADD, -1, "aaa"),
      (constants.DDM_REMOVE, -1, None),
      (constants.DDM_ADD, -1, "bbb"),
      ], None)
    chgdesc = []
    cmdlib.ApplyContainerMods("test", container, chgdesc, mods,
                              None, None, None)
    self.assertEqual(container, ["item 1", "item 2", "bbb"])
    self.assertEqual(chgdesc, [
      ("test/2", "remove"),
      ])

876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
  def testModify(self):
    container = ["item 1", "item 2"]
    mods = cmdlib.PrepareContainerMods([
      (constants.DDM_MODIFY, -1, "a"),
      (constants.DDM_MODIFY, 0, "b"),
      (constants.DDM_MODIFY, 1, "c"),
      ], None)
    chgdesc = []
    cmdlib.ApplyContainerMods("test", container, chgdesc, mods,
                              None, None, None)
    self.assertEqual(container, ["item 1", "item 2"])
    self.assertEqual(chgdesc, [])

    for idx in [-2, len(container) + 1]:
      mods = cmdlib.PrepareContainerMods([
        (constants.DDM_MODIFY, idx, "error"),
        ], None)
      self.assertRaises(IndexError, cmdlib.ApplyContainerMods,
                        "test", container, None, mods, None, None, None)

896
897
898
899
900
  class _PrivateData:
    def __init__(self):
      self.data = None

  @staticmethod
901
  def _CreateTestFn(idx, params, private):
902
    private.data = ("add", idx, params)
903
904
905
    return ((100 * idx, params), [
      ("test/%s" % idx, hex(idx)),
      ])
906
907

  @staticmethod
908
  def _ModifyTestFn(idx, item, params, private):
909
    private.data = ("modify", idx, params)
910
911
912
    return [
      ("test/%s" % idx, "modify %s" % params),
      ]
913
914

  @staticmethod
915
  def _RemoveTestFn(idx, item, private):
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
    private.data = ("remove", idx, item)

  def testAddWithCreateFunction(self):
    container = []
    chgdesc = []
    mods = cmdlib.PrepareContainerMods([
      (constants.DDM_ADD, -1, "Hello"),
      (constants.DDM_ADD, -1, "World"),
      (constants.DDM_ADD, 0, "Start"),
      (constants.DDM_ADD, -1, "End"),
      (constants.DDM_REMOVE, 2, None),
      (constants.DDM_MODIFY, -1, "foobar"),
      (constants.DDM_REMOVE, 2, None),
      (constants.DDM_ADD, 1, "More"),
      ], self._PrivateData)
    cmdlib.ApplyContainerMods("test", container, chgdesc, mods,
      self._CreateTestFn, self._ModifyTestFn, self._RemoveTestFn)
    self.assertEqual(container, [
934
935
936
      (000, "Start"),
      (100, "More"),
      (000, "Hello"),
937
938
939
940
      ])
    self.assertEqual(chgdesc, [
      ("test/0", "0x0"),
      ("test/1", "0x1"),
941
      ("test/0", "0x0"),
942
943
944
945
      ("test/3", "0x3"),
      ("test/2", "remove"),
      ("test/2", "modify foobar"),
      ("test/2", "remove"),
946
      ("test/1", "0x1")
947
948
949
950
951
952
      ])
    self.assertTrue(compat.all(op == private.data[0]
                               for (op, _, _, private) in mods))
    self.assertEqual([private.data for (op, _, _, private) in mods], [
      ("add", 0, "Hello"),
      ("add", 1, "World"),
953
      ("add", 0, "Start"),
954
955
956
957
      ("add", 3, "End"),
      ("remove", 2, (100, "World")),
      ("modify", 2, "foobar"),
      ("remove", 2, (300, "End")),
958
      ("add", 1, "More"),
959
960
961
      ])


962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
class _FakeConfigForGenDiskTemplate:
  def __init__(self):
    self._unique_id = itertools.count()
    self._drbd_minor = itertools.count(20)
    self._port = itertools.count(constants.FIRST_DRBD_PORT)
    self._secret = itertools.count()

  def GetVGName(self):
    return "testvg"

  def GenerateUniqueID(self, ec_id):
    return "ec%s-uq%s" % (ec_id, self._unique_id.next())

  def AllocateDRBDMinor(self, nodes, instance):
    return [self._drbd_minor.next()
            for _ in nodes]

  def AllocatePort(self):
    return self._port.next()

  def GenerateDRBDSecret(self, ec_id):
    return "ec%s-secret%s" % (ec_id, self._secret.next())

985
986
987
  def GetInstanceInfo(self, _):
    return "foobar"

988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004

class _FakeProcForGenDiskTemplate:
  def GetECId(self):
    return 0


class TestGenerateDiskTemplate(unittest.TestCase):
  def setUp(self):
    nodegroup = objects.NodeGroup(name="ng")
    nodegroup.UpgradeConfig()

    cfg = _FakeConfigForGenDiskTemplate()
    proc = _FakeProcForGenDiskTemplate()

    self.lu = _FakeLU(cfg=cfg, proc=proc)
    self.nodegroup = nodegroup

1005
1006
1007
1008
  @staticmethod
  def GetDiskParams():
    return copy.deepcopy(constants.DISK_DT_DEFAULTS)

1009
1010
1011
1012
1013
1014
1015
1016
1017
  def testWrongDiskTemplate(self):
    gdt = cmdlib._GenerateDiskTemplate
    disk_template = "##unknown##"

    assert disk_template not in constants.DISK_TEMPLATES

    self.assertRaises(errors.ProgrammerError, gdt, self.lu, disk_template,
                      "inst26831.example.com", "node30113.example.com", [], [],
                      NotImplemented, NotImplemented, 0, self.lu.LogInfo,
1018
                      self.GetDiskParams())
1019
1020
1021
1022
1023
1024
1025

  def testDiskless(self):
    gdt = cmdlib._GenerateDiskTemplate

    result = gdt(self.lu, constants.DT_DISKLESS, "inst27734.example.com",
                 "node30113.example.com", [], [],
                 NotImplemented, NotImplemented, 0, self.lu.LogInfo,
1026
                 self.GetDiskParams())
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
    self.assertEqual(result, [])

  def _TestTrivialDisk(self, template, disk_info, base_index, exp_dev_type,
                       file_storage_dir=NotImplemented,
                       file_driver=NotImplemented,
                       req_file_storage=NotImplemented,
                       req_shr_file_storage=NotImplemented):
    gdt = cmdlib._GenerateDiskTemplate

    map(lambda params: utils.ForceDictType(params,
                                           constants.IDISK_PARAMS_TYPES),
        disk_info)

    # Check if non-empty list of secondaries is rejected
    self.assertRaises(errors.ProgrammerError, gdt, self.lu,
                      template, "inst25088.example.com",
                      "node185.example.com", ["node323.example.com"], [],
                      NotImplemented, NotImplemented, base_index,
1045
                      self.lu.LogInfo, self.GetDiskParams(),
1046
1047
1048
1049
1050
1051
                      _req_file_storage=req_file_storage,
                      _req_shr_file_storage=req_shr_file_storage)

    result = gdt(self.lu, template, "inst21662.example.com",
                 "node21741.example.com", [],
                 disk_info, file_storage_dir, file_driver, base_index,
1052
                 self.lu.LogInfo, self.GetDiskParams(),
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
                 _req_file_storage=req_file_storage,
                 _req_shr_file_storage=req_shr_file_storage)

    for (idx, disk) in enumerate(result):
      self.assertTrue(isinstance(disk, objects.Disk))
      self.assertEqual(disk.dev_type, exp_dev_type)
      self.assertEqual(disk.size, disk_info[idx][constants.IDISK_SIZE])
      self.assertEqual(disk.mode, disk_info[idx][constants.IDISK_MODE])
      self.assertTrue(disk.children is None)

1063
1064
1065
    self._CheckIvNames(result, base_index, base_index + len(disk_info))
    cmdlib._UpdateIvNames(base_index, result)
    self._CheckIvNames(result, base_index, base_index + len(disk_info))
1066
1067
1068

    return result

1069
1070
1071
1072
  def _CheckIvNames(self, disks, base_index, end_index):
    self.assertEqual(map(operator.attrgetter("iv_name"), disks),
                     ["disk/%s" % i for i in range(base_index, end_index)])

1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
  def testPlain(self):
    disk_info = [{
      constants.IDISK_SIZE: 1024,
      constants.IDISK_MODE: constants.DISK_RDWR,
      }, {
      constants.IDISK_SIZE: 4096,
      constants.IDISK_VG: "othervg",
      constants.IDISK_MODE: constants.DISK_RDWR,
      }]

    result = self._TestTrivialDisk(constants.DT_PLAIN, disk_info, 3,
                                   constants.LD_LV)

    self.assertEqual(map(operator.attrgetter("logical_id"), result), [
      ("testvg", "ec0-uq0.disk3"),
      ("othervg", "ec0-uq1.disk4"),
      ])

  @staticmethod
  def _AllowFileStorage():
    pass

  @staticmethod
  def _ForbidFileStorage():
    raise errors.OpPrereqError("Disallowed in test")

  def testFile(self):
    self.assertRaises(errors.OpPrereqError, self._TestTrivialDisk,
                      constants.DT_FILE, [], 0, NotImplemented,
                      req_file_storage=self._ForbidFileStorage)
    self.assertRaises(errors.OpPrereqError, self._TestTrivialDisk,
                      constants.DT_SHARED_FILE, [], 0, NotImplemented,
                      req_shr_file_storage=self._ForbidFileStorage)

    for disk_template in [constants.DT_FILE, constants.DT_SHARED_FILE]:
      disk_info = [{
        constants.IDISK_SIZE: 80 * 1024,
        constants.IDISK_MODE: constants.DISK_RDONLY,
        }, {
        constants.IDISK_SIZE: 4096,
        constants.IDISK_MODE: constants.DISK_RDWR,
        }, {
        constants.IDISK_SIZE: 6 * 1024,
        constants.IDISK_MODE: constants.DISK_RDWR,
        }]

      result = self._TestTrivialDisk(disk_template, disk_info, 2,
        constants.LD_FILE, file_storage_dir="/tmp",
        file_driver=constants.FD_BLKTAP,
        req_file_storage=self._AllowFileStorage,
        req_shr_file_storage=self._AllowFileStorage)

      self.assertEqual(map(operator.attrgetter("logical_id"), result), [
        (constants.FD_BLKTAP, "/tmp/disk2"),
        (constants.FD_BLKTAP, "/tmp/disk3"),
        (constants.FD_BLKTAP, "/tmp/disk4"),
        ])

  def testBlock(self):
    disk_info = [{
      constants.IDISK_SIZE: 8 * 1024,
      constants.IDISK_MODE: constants.DISK_RDWR,
      constants.IDISK_ADOPT: "/tmp/some/block/dev",
      }]

    result = self._TestTrivialDisk(constants.DT_BLOCK, disk_info, 10,
                                   constants.LD_BLOCKDEV)

    self.assertEqual(map(operator.attrgetter("logical_id"), result), [
      (constants.BLOCKDEV_DRIVER_MANUAL, "/tmp/some/block/dev"),
      ])

  def testRbd(self):
    disk_info = [{
      constants.IDISK_SIZE: 8 * 1024,
      constants.IDISK_MODE: constants.DISK_RDONLY,
      }, {
      constants.IDISK_SIZE: 100 * 1024,
      constants.IDISK_MODE: constants.DISK_RDWR,
      }]

    result = self._TestTrivialDisk(constants.DT_RBD, disk_info, 0,
                                   constants.LD_RBD)

    self.assertEqual(map(operator.attrgetter("logical_id"), result), [
      ("rbd", "ec0-uq0.rbd.disk0"),
      ("rbd", "ec0-uq1.rbd.disk1"),
      ])

  def testDrbd8(self):
    gdt = cmdlib._GenerateDiskTemplate
    drbd8_defaults = constants.DISK_LD_DEFAULTS[constants.LD_DRBD8]
    drbd8_default_metavg = drbd8_defaults[constants.LDP_DEFAULT_METAVG]

    disk_info = [{
      constants.IDISK_SIZE: 1024,
      constants.IDISK_MODE: constants.DISK_RDWR,
      }, {
      constants.IDISK_SIZE: 100 * 1024,
      constants.IDISK_MODE: constants.DISK_RDONLY,
      constants.IDISK_METAVG: "metavg",
      }, {
      constants.IDISK_SIZE: 4096,
      constants.IDISK_MODE: constants.DISK_RDWR,
      constants.IDISK_VG: "vgxyz",
      },
      ]

    exp_logical_ids = [[
      (self.lu.cfg.GetVGName(), "ec0-uq0.disk0_data"),
      (drbd8_default_metavg, "ec0-uq0.disk0_meta"),
      ], [
      (self.lu.cfg.GetVGName(), "ec0-uq1.disk1_data"),
      ("metavg", "ec0-uq1.disk1_meta"),
      ], [
      ("vgxyz", "ec0-uq2.disk2_data"),
      (drbd8_default_metavg, "ec0-uq2.disk2_meta"),
      ]]

    assert len(exp_logical_ids) == len(disk_info)

    map(lambda params: utils.ForceDictType(params,
                                           constants.IDISK_PARAMS_TYPES),
        disk_info)

    # Check if empty list of secondaries is rejected
    self.assertRaises(errors.ProgrammerError, gdt, self.lu, constants.DT_DRBD8,
                      "inst827.example.com", "node1334.example.com", [],
                      disk_info, NotImplemented, NotImplemented, 0,
1202
                      self.lu.LogInfo, self.GetDiskParams())
1203
1204
1205
1206

    result = gdt(self.lu, constants.DT_DRBD8, "inst827.example.com",
                 "node1334.example.com", ["node12272.example.com"],
                 disk_info, NotImplemented, NotImplemented, 0, self.lu.LogInfo,
1207
                 self.GetDiskParams())
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224

    for (idx, disk) in enumerate(result):
      self.assertTrue(isinstance(disk, objects.Disk))
      self.assertEqual(disk.dev_type, constants.LD_DRBD8)
      self.assertEqual(disk.size, disk_info[idx][constants.IDISK_SIZE])
      self.assertEqual(disk.mode, disk_info[idx][constants.IDISK_MODE])

      for child in disk.children:
        self.assertTrue(isinstance(disk, objects.Disk))
        self.assertEqual(child.dev_type, constants.LD_LV)
        self.assertTrue(child.children is None)

      self.assertEqual(map(operator.attrgetter("logical_id"), disk.children),
                       exp_logical_ids[idx])

      self.assertEqual(len(disk.children), 2)
      self.assertEqual(disk.children[0].size, disk.size)
1225
      self.assertEqual(disk.children[1].size, constants.DRBD_META_SIZE)
1226

1227
1228
1229
    self._CheckIvNames(result, 0, len(disk_info))
    cmdlib._UpdateIvNames(0, result)
    self._CheckIvNames(result, 0, len(disk_info))
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240

    self.assertEqual(map(operator.attrgetter("logical_id"), result), [
      ("node1334.example.com", "node12272.example.com",
       constants.FIRST_DRBD_PORT, 20, 21, "ec0-secret0"),
      ("node1334.example.com", "node12272.example.com",
       constants.FIRST_DRBD_PORT + 1, 22, 23, "ec0-secret1"),
      ("node1334.example.com", "node12272.example.com",
       constants.FIRST_DRBD_PORT + 2, 24, 25, "ec0-secret2"),
      ])


1241
if __name__ == "__main__":
1242
  testutils.GanetiTestProgram()