Statistics
| Branch: | Tag: | Revision:

root / test / ganeti.rapi.rlib2_unittest.py @ 8d232068

History | View | Annotate | Download (46.6 kB)

1
#!/usr/bin/python
2
#
3

    
4
# Copyright (C) 2010 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 unittesting the RAPI rlib2 module
23

24
"""
25

    
26

    
27
import unittest
28
import itertools
29
import random
30

    
31
from ganeti import constants
32
from ganeti import opcodes
33
from ganeti import compat
34
from ganeti import http
35
from ganeti import query
36
from ganeti import luxi
37
from ganeti import errors
38

    
39
from ganeti.rapi import rlib2
40

    
41
import testutils
42

    
43

    
44
class _FakeRequestPrivateData:
45
  def __init__(self, body_data):
46
    self.body_data = body_data
47

    
48

    
49
class _FakeRequest:
50
  def __init__(self, body_data):
51
    self.private = _FakeRequestPrivateData(body_data)
52

    
53

    
54
def _CreateHandler(cls, items, queryargs, body_data, client_cls):
55
  return cls(items, queryargs, _FakeRequest(body_data),
56
             _client_cls=client_cls)
57

    
58

    
59
class _FakeClient:
60
  def __init__(self):
61
    self._jobs = []
62

    
63
  def GetNextSubmittedJob(self):
64
    return self._jobs.pop(0)
65

    
66
  def SubmitJob(self, ops):
67
    job_id = str(1 + int(random.random() * 1000000))
68
    self._jobs.append((job_id, ops))
69
    return job_id
70

    
71

    
72
class _FakeClientFactory:
73
  def __init__(self, cls):
74
    self._client_cls = cls
75
    self._clients = []
76

    
77
  def GetNextClient(self):
78
    return self._clients.pop(0)
79

    
80
  def __call__(self):
81
    cl = self._client_cls()
82
    self._clients.append(cl)
83
    return cl
84

    
85

    
86
class TestConstants(unittest.TestCase):
87
  def testConsole(self):
88
    # Exporting the console field without authentication might expose
89
    # information
90
    assert "console" in query.INSTANCE_FIELDS
91
    self.assertTrue("console" not in rlib2.I_FIELDS)
92

    
93
  def testFields(self):
94
    checks = {
95
      constants.QR_INSTANCE: rlib2.I_FIELDS,
96
      constants.QR_NODE: rlib2.N_FIELDS,
97
      constants.QR_GROUP: rlib2.G_FIELDS,
98
      }
99

    
100
    for (qr, fields) in checks.items():
101
      self.assertFalse(set(fields) - set(query.ALL_FIELDS[qr].keys()))
102

    
103

    
104
class TestClientConnectError(unittest.TestCase):
105
  @staticmethod
106
  def _FailingClient():
107
    raise luxi.NoMasterError("test")
108

    
109
  def test(self):
110
    resources = [
111
      rlib2.R_2_groups,
112
      rlib2.R_2_instances,
113
      rlib2.R_2_nodes,
114
      ]
115
    for cls in resources:
116
      handler = _CreateHandler(cls, ["name"], [], None, self._FailingClient)
117
      self.assertRaises(http.HttpBadGateway, handler.GET)
118

    
119

    
120
class TestJobSubmitError(unittest.TestCase):
121
  class _SubmitErrorClient:
122
    @staticmethod
123
    def SubmitJob(ops):
124
      raise errors.JobQueueFull("test")
125

    
126
  def test(self):
127
    handler = _CreateHandler(rlib2.R_2_redist_config, [], [], None,
128
                             self._SubmitErrorClient)
129
    self.assertRaises(http.HttpServiceUnavailable, handler.PUT)
130

    
131

    
132
class TestClusterModify(unittest.TestCase):
133
  def test(self):
134
    clfactory = _FakeClientFactory(_FakeClient)
135
    handler = _CreateHandler(rlib2.R_2_cluster_modify, [], [], {
136
      "vg_name": "testvg",
137
      "candidate_pool_size": 100,
138
      }, clfactory)
139
    job_id = handler.PUT()
140

    
141
    cl = clfactory.GetNextClient()
142
    self.assertRaises(IndexError, clfactory.GetNextClient)
143

    
144
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
145
    self.assertEqual(job_id, exp_job_id)
146
    self.assertTrue(isinstance(op, opcodes.OpClusterSetParams))
147
    self.assertEqual(op.vg_name, "testvg")
148
    self.assertEqual(op.candidate_pool_size, 100)
149

    
150
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
151

    
152
  def testInvalidValue(self):
153
    for attr in ["vg_name", "candidate_pool_size", "beparams", "_-Unknown#"]:
154
      clfactory = _FakeClientFactory(_FakeClient)
155
      handler = _CreateHandler(rlib2.R_2_cluster_modify, [], [], {
156
        attr: True,
157
        }, clfactory)
158
      self.assertRaises(http.HttpBadRequest, handler.PUT)
159
      self.assertRaises(IndexError, clfactory.GetNextClient)
160

    
161

    
162
class TestRedistConfig(unittest.TestCase):
163
  def test(self):
164
    clfactory = _FakeClientFactory(_FakeClient)
165
    handler = _CreateHandler(rlib2.R_2_redist_config, [], [], None, clfactory)
166
    job_id = handler.PUT()
167

    
168
    cl = clfactory.GetNextClient()
169
    self.assertRaises(IndexError, clfactory.GetNextClient)
170

    
171
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
172
    self.assertEqual(job_id, exp_job_id)
173
    self.assertTrue(isinstance(op, opcodes.OpClusterRedistConf))
174

    
175
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
176

    
177

    
178
class TestNodeMigrate(unittest.TestCase):
179
  def test(self):
180
    clfactory = _FakeClientFactory(_FakeClient)
181
    handler = _CreateHandler(rlib2.R_2_nodes_name_migrate, ["node1"], {}, {
182
      "iallocator": "fooalloc",
183
      }, clfactory)
184
    job_id = handler.POST()
185

    
186
    cl = clfactory.GetNextClient()
187
    self.assertRaises(IndexError, clfactory.GetNextClient)
188

    
189
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
190
    self.assertEqual(job_id, exp_job_id)
191
    self.assertTrue(isinstance(op, opcodes.OpNodeMigrate))
192
    self.assertEqual(op.node_name, "node1")
193
    self.assertEqual(op.iallocator, "fooalloc")
194

    
195
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
196

    
197
  def testQueryArgsConflict(self):
198
    clfactory = _FakeClientFactory(_FakeClient)
199
    handler = _CreateHandler(rlib2.R_2_nodes_name_migrate, ["node2"], {
200
      "live": True,
201
      "mode": constants.HT_MIGRATION_NONLIVE,
202
      }, None, clfactory)
203
    self.assertRaises(http.HttpBadRequest, handler.POST)
204
    self.assertRaises(IndexError, clfactory.GetNextClient)
205

    
206
  def testQueryArgsMode(self):
207
    clfactory = _FakeClientFactory(_FakeClient)
208
    queryargs = {
209
      "mode": [constants.HT_MIGRATION_LIVE],
210
      }
211
    handler = _CreateHandler(rlib2.R_2_nodes_name_migrate, ["node17292"],
212
                             queryargs, None, clfactory)
213
    job_id = handler.POST()
214

    
215
    cl = clfactory.GetNextClient()
216
    self.assertRaises(IndexError, clfactory.GetNextClient)
217

    
218
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
219
    self.assertEqual(job_id, exp_job_id)
220
    self.assertTrue(isinstance(op, opcodes.OpNodeMigrate))
221
    self.assertEqual(op.node_name, "node17292")
222
    self.assertEqual(op.mode, constants.HT_MIGRATION_LIVE)
223

    
224
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
225

    
226
  def testQueryArgsLive(self):
227
    clfactory = _FakeClientFactory(_FakeClient)
228

    
229
    for live in [False, True]:
230
      queryargs = {
231
        "live": [str(int(live))],
232
        }
233
      handler = _CreateHandler(rlib2.R_2_nodes_name_migrate, ["node6940"],
234
                               queryargs, None, clfactory)
235
      job_id = handler.POST()
236

    
237
      cl = clfactory.GetNextClient()
238
      self.assertRaises(IndexError, clfactory.GetNextClient)
239

    
240
      (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
241
      self.assertEqual(job_id, exp_job_id)
242
      self.assertTrue(isinstance(op, opcodes.OpNodeMigrate))
243
      self.assertEqual(op.node_name, "node6940")
244
      if live:
245
        self.assertEqual(op.mode, constants.HT_MIGRATION_LIVE)
246
      else:
247
        self.assertEqual(op.mode, constants.HT_MIGRATION_NONLIVE)
248

    
249
      self.assertRaises(IndexError, cl.GetNextSubmittedJob)
250

    
251

    
252
class TestNodeEvacuate(unittest.TestCase):
253
  def test(self):
254
    clfactory = _FakeClientFactory(_FakeClient)
255
    handler = _CreateHandler(rlib2.R_2_nodes_name_evacuate, ["node92"], {
256
      "dry-run": ["1"],
257
      }, {
258
      "mode": constants.IALLOCATOR_NEVAC_SEC,
259
      }, clfactory)
260
    job_id = handler.POST()
261

    
262
    cl = clfactory.GetNextClient()
263
    self.assertRaises(IndexError, clfactory.GetNextClient)
264

    
265
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
266
    self.assertEqual(job_id, exp_job_id)
267
    self.assertTrue(isinstance(op, opcodes.OpNodeEvacuate))
268
    self.assertEqual(op.node_name, "node92")
269
    self.assertEqual(op.mode, constants.IALLOCATOR_NEVAC_SEC)
270
    self.assertTrue(op.dry_run)
271

    
272
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
273

    
274

    
275
class TestGroupAssignNodes(unittest.TestCase):
276
  def test(self):
277
    clfactory = _FakeClientFactory(_FakeClient)
278
    handler = _CreateHandler(rlib2.R_2_groups_name_assign_nodes, ["grp-a"], {
279
      "dry-run": ["1"],
280
      "force": ["1"],
281
      }, {
282
      "nodes": ["n2", "n3"],
283
      }, clfactory)
284
    job_id = handler.PUT()
285

    
286
    cl = clfactory.GetNextClient()
287
    self.assertRaises(IndexError, clfactory.GetNextClient)
288

    
289
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
290
    self.assertEqual(job_id, exp_job_id)
291
    self.assertTrue(isinstance(op, opcodes.OpGroupAssignNodes))
292
    self.assertEqual(op.group_name, "grp-a")
293
    self.assertEqual(op.nodes, ["n2", "n3"])
294
    self.assertTrue(op.dry_run)
295
    self.assertTrue(op.force)
296

    
297
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
298

    
299

    
300
class TestInstanceDelete(unittest.TestCase):
301
  def test(self):
302
    clfactory = _FakeClientFactory(_FakeClient)
303
    handler = _CreateHandler(rlib2.R_2_instances_name, ["inst30965"], {
304
      "dry-run": ["1"],
305
      }, {}, clfactory)
306
    job_id = handler.DELETE()
307

    
308
    cl = clfactory.GetNextClient()
309
    self.assertRaises(IndexError, clfactory.GetNextClient)
310

    
311
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
312
    self.assertEqual(job_id, exp_job_id)
313
    self.assertTrue(isinstance(op, opcodes.OpInstanceRemove))
314
    self.assertEqual(op.instance_name, "inst30965")
315
    self.assertTrue(op.dry_run)
316
    self.assertFalse(op.ignore_failures)
317

    
318
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
319

    
320

    
321
class TestInstanceInfo(unittest.TestCase):
322
  def test(self):
323
    clfactory = _FakeClientFactory(_FakeClient)
324
    handler = _CreateHandler(rlib2.R_2_instances_name_info, ["inst31217"], {
325
      "static": ["1"],
326
      }, {}, clfactory)
327
    job_id = handler.GET()
328

    
329
    cl = clfactory.GetNextClient()
330
    self.assertRaises(IndexError, clfactory.GetNextClient)
331

    
332
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
333
    self.assertEqual(job_id, exp_job_id)
334
    self.assertTrue(isinstance(op, opcodes.OpInstanceQueryData))
335
    self.assertEqual(op.instances, ["inst31217"])
336
    self.assertTrue(op.static)
337

    
338
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
339

    
340

    
341
class TestInstanceReboot(unittest.TestCase):
342
  def test(self):
343
    clfactory = _FakeClientFactory(_FakeClient)
344
    handler = _CreateHandler(rlib2.R_2_instances_name_reboot, ["inst847"], {
345
      "dry-run": ["1"],
346
      "ignore_secondaries": ["1"],
347
      }, {}, clfactory)
348
    job_id = handler.POST()
349

    
350
    cl = clfactory.GetNextClient()
351
    self.assertRaises(IndexError, clfactory.GetNextClient)
352

    
353
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
354
    self.assertEqual(job_id, exp_job_id)
355
    self.assertTrue(isinstance(op, opcodes.OpInstanceReboot))
356
    self.assertEqual(op.instance_name, "inst847")
357
    self.assertEqual(op.reboot_type, constants.INSTANCE_REBOOT_HARD)
358
    self.assertTrue(op.ignore_secondaries)
359
    self.assertTrue(op.dry_run)
360

    
361
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
362

    
363

    
364
class TestInstanceStartup(unittest.TestCase):
365
  def test(self):
366
    clfactory = _FakeClientFactory(_FakeClient)
367
    handler = _CreateHandler(rlib2.R_2_instances_name_startup, ["inst31083"], {
368
      "force": ["1"],
369
      "no_remember": ["1"],
370
      }, {}, clfactory)
371
    job_id = handler.PUT()
372

    
373
    cl = clfactory.GetNextClient()
374
    self.assertRaises(IndexError, clfactory.GetNextClient)
375

    
376
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
377
    self.assertEqual(job_id, exp_job_id)
378
    self.assertTrue(isinstance(op, opcodes.OpInstanceStartup))
379
    self.assertEqual(op.instance_name, "inst31083")
380
    self.assertTrue(op.no_remember)
381
    self.assertTrue(op.force)
382
    self.assertFalse(op.dry_run)
383

    
384
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
385

    
386

    
387
class TestInstanceShutdown(unittest.TestCase):
388
  def test(self):
389
    clfactory = _FakeClientFactory(_FakeClient)
390
    handler = _CreateHandler(rlib2.R_2_instances_name_shutdown, ["inst26791"], {
391
      "no_remember": ["0"],
392
      }, {}, clfactory)
393
    job_id = handler.PUT()
394

    
395
    cl = clfactory.GetNextClient()
396
    self.assertRaises(IndexError, clfactory.GetNextClient)
397

    
398
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
399
    self.assertEqual(job_id, exp_job_id)
400
    self.assertTrue(isinstance(op, opcodes.OpInstanceShutdown))
401
    self.assertEqual(op.instance_name, "inst26791")
402
    self.assertFalse(op.no_remember)
403
    self.assertFalse(op.dry_run)
404

    
405
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
406

    
407

    
408
class TestInstanceActivateDisks(unittest.TestCase):
409
  def test(self):
410
    clfactory = _FakeClientFactory(_FakeClient)
411
    handler = _CreateHandler(rlib2.R_2_instances_name_activate_disks, ["xyz"], {
412
      "ignore_size": ["1"],
413
      }, {}, clfactory)
414
    job_id = handler.PUT()
415

    
416
    cl = clfactory.GetNextClient()
417
    self.assertRaises(IndexError, clfactory.GetNextClient)
418

    
419
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
420
    self.assertEqual(job_id, exp_job_id)
421
    self.assertTrue(isinstance(op, opcodes.OpInstanceActivateDisks))
422
    self.assertEqual(op.instance_name, "xyz")
423
    self.assertTrue(op.ignore_size)
424
    self.assertFalse(hasattr(op, "dry_run"))
425

    
426
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
427

    
428

    
429
class TestInstanceDeactivateDisks(unittest.TestCase):
430
  def test(self):
431
    clfactory = _FakeClientFactory(_FakeClient)
432
    handler = _CreateHandler(rlib2.R_2_instances_name_deactivate_disks,
433
                             ["inst22357"], {}, {}, clfactory)
434
    job_id = handler.PUT()
435

    
436
    cl = clfactory.GetNextClient()
437
    self.assertRaises(IndexError, clfactory.GetNextClient)
438

    
439
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
440
    self.assertEqual(job_id, exp_job_id)
441
    self.assertTrue(isinstance(op, opcodes.OpInstanceDeactivateDisks))
442
    self.assertEqual(op.instance_name, "inst22357")
443
    self.assertFalse(hasattr(op, "dry_run"))
444
    self.assertFalse(hasattr(op, "force"))
445

    
446
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
447

    
448

    
449
class TestInstanceFailover(unittest.TestCase):
450
  def test(self):
451
    clfactory = _FakeClientFactory(_FakeClient)
452
    handler = _CreateHandler(rlib2.R_2_instances_name_failover,
453
                             ["inst12794"], {}, {}, clfactory)
454
    job_id = handler.PUT()
455

    
456
    cl = clfactory.GetNextClient()
457
    self.assertRaises(IndexError, clfactory.GetNextClient)
458

    
459
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
460
    self.assertEqual(job_id, exp_job_id)
461
    self.assertTrue(isinstance(op, opcodes.OpInstanceFailover))
462
    self.assertEqual(op.instance_name, "inst12794")
463
    self.assertFalse(hasattr(op, "dry_run"))
464
    self.assertFalse(hasattr(op, "force"))
465

    
466
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
467

    
468

    
469
class TestInstanceDiskGrow(unittest.TestCase):
470
  def test(self):
471
    clfactory = _FakeClientFactory(_FakeClient)
472
    data = {
473
      "amount": 1024,
474
      }
475
    handler = _CreateHandler(rlib2.R_2_instances_name_disk_grow,
476
                             ["inst10742", "3"], {}, data, clfactory)
477
    job_id = handler.POST()
478

    
479
    cl = clfactory.GetNextClient()
480
    self.assertRaises(IndexError, clfactory.GetNextClient)
481

    
482
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
483
    self.assertEqual(job_id, exp_job_id)
484
    self.assertTrue(isinstance(op, opcodes.OpInstanceGrowDisk))
485
    self.assertEqual(op.instance_name, "inst10742")
486
    self.assertEqual(op.disk, 3)
487
    self.assertEqual(op.amount, 1024)
488
    self.assertFalse(hasattr(op, "dry_run"))
489
    self.assertFalse(hasattr(op, "force"))
490

    
491
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
492

    
493

    
494
class TestBackupPrepare(unittest.TestCase):
495
  def test(self):
496
    clfactory = _FakeClientFactory(_FakeClient)
497
    queryargs = {
498
      "mode": constants.EXPORT_MODE_REMOTE,
499
      }
500
    handler = _CreateHandler(rlib2.R_2_instances_name_prepare_export,
501
                             ["inst17925"], queryargs, {}, clfactory)
502
    job_id = handler.PUT()
503

    
504
    cl = clfactory.GetNextClient()
505
    self.assertRaises(IndexError, clfactory.GetNextClient)
506

    
507
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
508
    self.assertEqual(job_id, exp_job_id)
509
    self.assertTrue(isinstance(op, opcodes.OpBackupPrepare))
510
    self.assertEqual(op.instance_name, "inst17925")
511
    self.assertEqual(op.mode, constants.EXPORT_MODE_REMOTE)
512
    self.assertFalse(hasattr(op, "dry_run"))
513
    self.assertFalse(hasattr(op, "force"))
514

    
515
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
516

    
517

    
518
class TestGroupRemove(unittest.TestCase):
519
  def test(self):
520
    clfactory = _FakeClientFactory(_FakeClient)
521
    handler = _CreateHandler(rlib2.R_2_groups_name,
522
                             ["grp28575"], {}, {}, clfactory)
523
    job_id = handler.DELETE()
524

    
525
    cl = clfactory.GetNextClient()
526
    self.assertRaises(IndexError, clfactory.GetNextClient)
527

    
528
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
529
    self.assertEqual(job_id, exp_job_id)
530
    self.assertTrue(isinstance(op, opcodes.OpGroupRemove))
531
    self.assertEqual(op.group_name, "grp28575")
532
    self.assertFalse(op.dry_run)
533
    self.assertFalse(hasattr(op, "force"))
534

    
535
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
536

    
537

    
538
class TestStorageQuery(unittest.TestCase):
539
  def test(self):
540
    clfactory = _FakeClientFactory(_FakeClient)
541
    queryargs = {
542
      "storage_type": constants.ST_LVM_PV,
543
      "output_fields": "name,other",
544
      }
545
    handler = _CreateHandler(rlib2.R_2_nodes_name_storage,
546
                             ["node21075"], queryargs, {}, clfactory)
547
    job_id = handler.GET()
548

    
549
    cl = clfactory.GetNextClient()
550
    self.assertRaises(IndexError, clfactory.GetNextClient)
551

    
552
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
553
    self.assertEqual(job_id, exp_job_id)
554
    self.assertTrue(isinstance(op, opcodes.OpNodeQueryStorage))
555
    self.assertEqual(op.nodes, ["node21075"])
556
    self.assertEqual(op.storage_type, constants.ST_LVM_PV)
557
    self.assertEqual(op.output_fields, ["name", "other"])
558
    self.assertFalse(hasattr(op, "dry_run"))
559
    self.assertFalse(hasattr(op, "force"))
560

    
561
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
562

    
563
  def testErrors(self):
564
    clfactory = _FakeClientFactory(_FakeClient)
565

    
566
    queryargs = {
567
      "output_fields": "name,other",
568
      }
569
    handler = _CreateHandler(rlib2.R_2_nodes_name_storage,
570
                             ["node10538"], queryargs, {}, clfactory)
571
    self.assertRaises(http.HttpBadRequest, handler.GET)
572

    
573
    queryargs = {
574
      "storage_type": constants.ST_LVM_VG,
575
      }
576
    handler = _CreateHandler(rlib2.R_2_nodes_name_storage,
577
                             ["node21273"], queryargs, {}, clfactory)
578
    self.assertRaises(http.HttpBadRequest, handler.GET)
579

    
580
    queryargs = {
581
      "storage_type": "##unknown_storage##",
582
      "output_fields": "name,other",
583
      }
584
    handler = _CreateHandler(rlib2.R_2_nodes_name_storage,
585
                             ["node10315"], queryargs, {}, clfactory)
586
    self.assertRaises(http.HttpBadRequest, handler.GET)
587

    
588

    
589
class TestStorageModify(unittest.TestCase):
590
  def test(self):
591
    clfactory = _FakeClientFactory(_FakeClient)
592

    
593
    for allocatable in [None, "1", "0"]:
594
      queryargs = {
595
        "storage_type": constants.ST_LVM_VG,
596
        "name": "pv-a",
597
        }
598

    
599
      if allocatable is not None:
600
        queryargs["allocatable"] = allocatable
601

    
602
      handler = _CreateHandler(rlib2.R_2_nodes_name_storage_modify,
603
                               ["node9292"], queryargs, {}, clfactory)
604
      job_id = handler.PUT()
605

    
606
      cl = clfactory.GetNextClient()
607
      self.assertRaises(IndexError, clfactory.GetNextClient)
608

    
609
      (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
610
      self.assertEqual(job_id, exp_job_id)
611
      self.assertTrue(isinstance(op, opcodes.OpNodeModifyStorage))
612
      self.assertEqual(op.node_name, "node9292")
613
      self.assertEqual(op.storage_type, constants.ST_LVM_VG)
614
      self.assertEqual(op.name, "pv-a")
615
      if allocatable is None:
616
        self.assertFalse(op.changes)
617
      else:
618
        assert allocatable in ("0", "1")
619
        self.assertEqual(op.changes, {
620
          constants.SF_ALLOCATABLE: (allocatable == "1"),
621
          })
622
      self.assertFalse(hasattr(op, "dry_run"))
623
      self.assertFalse(hasattr(op, "force"))
624

    
625
      self.assertRaises(IndexError, cl.GetNextSubmittedJob)
626

    
627
  def testErrors(self):
628
    clfactory = _FakeClientFactory(_FakeClient)
629

    
630
    # No storage type
631
    queryargs = {
632
      "name": "xyz",
633
      }
634
    handler = _CreateHandler(rlib2.R_2_nodes_name_storage_modify,
635
                             ["node26016"], queryargs, {}, clfactory)
636
    self.assertRaises(http.HttpBadRequest, handler.PUT)
637

    
638
    # No name
639
    queryargs = {
640
      "storage_type": constants.ST_LVM_VG,
641
      }
642
    handler = _CreateHandler(rlib2.R_2_nodes_name_storage_modify,
643
                             ["node21218"], queryargs, {}, clfactory)
644
    self.assertRaises(http.HttpBadRequest, handler.PUT)
645

    
646
    # Invalid value
647
    queryargs = {
648
      "storage_type": constants.ST_LVM_VG,
649
      "name": "pv-b",
650
      "allocatable": "noint",
651
      }
652
    handler = _CreateHandler(rlib2.R_2_nodes_name_storage_modify,
653
                             ["node30685"], queryargs, {}, clfactory)
654
    self.assertRaises(http.HttpBadRequest, handler.PUT)
655

    
656

    
657
class TestParseInstanceCreateRequestVersion1(testutils.GanetiTestCase):
658
  def setUp(self):
659
    testutils.GanetiTestCase.setUp(self)
660

    
661
    self.Parse = rlib2._ParseInstanceCreateRequestVersion1
662

    
663
  def test(self):
664
    disk_variants = [
665
      # No disks
666
      [],
667

    
668
      # Two disks
669
      [{"size": 5, }, {"size": 100, }],
670

    
671
      # Disk with mode
672
      [{"size": 123, "mode": constants.DISK_RDWR, }],
673
      ]
674

    
675
    nic_variants = [
676
      # No NIC
677
      [],
678

    
679
      # Three NICs
680
      [{}, {}, {}],
681

    
682
      # Two NICs
683
      [
684
        { "ip": "192.0.2.6", "mode": constants.NIC_MODE_ROUTED,
685
          "mac": "01:23:45:67:68:9A",
686
        },
687
        { "mode": constants.NIC_MODE_BRIDGED, "link": "br1" },
688
      ],
689
      ]
690

    
691
    beparam_variants = [
692
      None,
693
      {},
694
      { constants.BE_VCPUS: 2, },
695
      { constants.BE_MEMORY: 123, },
696
      { constants.BE_VCPUS: 2,
697
        constants.BE_MEMORY: 1024,
698
        constants.BE_AUTO_BALANCE: True, }
699
      ]
700

    
701
    hvparam_variants = [
702
      None,
703
      { constants.HV_BOOT_ORDER: "anc", },
704
      { constants.HV_KERNEL_PATH: "/boot/fookernel",
705
        constants.HV_ROOT_PATH: "/dev/hda1", },
706
      ]
707

    
708
    for mode in [constants.INSTANCE_CREATE, constants.INSTANCE_IMPORT]:
709
      for nics in nic_variants:
710
        for disk_template in constants.DISK_TEMPLATES:
711
          for disks in disk_variants:
712
            for beparams in beparam_variants:
713
              for hvparams in hvparam_variants:
714
                data = {
715
                  "name": "inst1.example.com",
716
                  "hypervisor": constants.HT_FAKE,
717
                  "disks": disks,
718
                  "nics": nics,
719
                  "mode": mode,
720
                  "disk_template": disk_template,
721
                  "os": "debootstrap",
722
                  }
723

    
724
                if beparams is not None:
725
                  data["beparams"] = beparams
726

    
727
                if hvparams is not None:
728
                  data["hvparams"] = hvparams
729

    
730
                for dry_run in [False, True]:
731
                  op = self.Parse(data, dry_run)
732
                  self.assert_(isinstance(op, opcodes.OpInstanceCreate))
733
                  self.assertEqual(op.mode, mode)
734
                  self.assertEqual(op.disk_template, disk_template)
735
                  self.assertEqual(op.dry_run, dry_run)
736
                  self.assertEqual(len(op.disks), len(disks))
737
                  self.assertEqual(len(op.nics), len(nics))
738

    
739
                  for opdisk, disk in zip(op.disks, disks):
740
                    for key in constants.IDISK_PARAMS:
741
                      self.assertEqual(opdisk.get(key), disk.get(key))
742
                    self.assertFalse("unknown" in opdisk)
743

    
744
                  for opnic, nic in zip(op.nics, nics):
745
                    for key in constants.INIC_PARAMS:
746
                      self.assertEqual(opnic.get(key), nic.get(key))
747
                    self.assertFalse("unknown" in opnic)
748
                    self.assertFalse("foobar" in opnic)
749

    
750
                  if beparams is None:
751
                    self.assertFalse(hasattr(op, "beparams"))
752
                  else:
753
                    self.assertEqualValues(op.beparams, beparams)
754

    
755
                  if hvparams is None:
756
                    self.assertFalse(hasattr(op, "hvparams"))
757
                  else:
758
                    self.assertEqualValues(op.hvparams, hvparams)
759

    
760
  def testLegacyName(self):
761
    name = "inst29128.example.com"
762
    data = {
763
      "name": name,
764
      "disks": [],
765
      "nics": [],
766
      "mode": constants.INSTANCE_CREATE,
767
      "disk_template": constants.DT_PLAIN,
768
      }
769
    op = self.Parse(data, False)
770
    self.assert_(isinstance(op, opcodes.OpInstanceCreate))
771
    self.assertEqual(op.instance_name, name)
772
    self.assertFalse(hasattr(op, "name"))
773

    
774
    # Define both
775
    data = {
776
      "name": name,
777
      "instance_name": "other.example.com",
778
      "disks": [],
779
      "nics": [],
780
      "mode": constants.INSTANCE_CREATE,
781
      "disk_template": constants.DT_PLAIN,
782
      }
783
    self.assertRaises(http.HttpBadRequest, self.Parse, data, False)
784

    
785
  def testLegacyOs(self):
786
    name = "inst4673.example.com"
787
    os = "linux29206"
788
    data = {
789
      "name": name,
790
      "os_type": os,
791
      "disks": [],
792
      "nics": [],
793
      "mode": constants.INSTANCE_CREATE,
794
      "disk_template": constants.DT_PLAIN,
795
      }
796
    op = self.Parse(data, False)
797
    self.assert_(isinstance(op, opcodes.OpInstanceCreate))
798
    self.assertEqual(op.instance_name, name)
799
    self.assertEqual(op.os_type, os)
800
    self.assertFalse(hasattr(op, "os"))
801

    
802
    # Define both
803
    data = {
804
      "instance_name": name,
805
      "os": os,
806
      "os_type": "linux9584",
807
      "disks": [],
808
      "nics": [],
809
      "mode": constants.INSTANCE_CREATE,
810
      "disk_template": constants.DT_PLAIN,
811
      }
812
    self.assertRaises(http.HttpBadRequest, self.Parse, data, False)
813

    
814
  def testErrors(self):
815
    # Test all required fields
816
    reqfields = {
817
      "name": "inst1.example.com",
818
      "disks": [],
819
      "nics": [],
820
      "mode": constants.INSTANCE_CREATE,
821
      "disk_template": constants.DT_PLAIN,
822
      }
823

    
824
    for name in reqfields.keys():
825
      self.assertRaises(http.HttpBadRequest, self.Parse,
826
                        dict(i for i in reqfields.iteritems() if i[0] != name),
827
                        False)
828

    
829
    # Invalid disks and nics
830
    for field in ["disks", "nics"]:
831
      invalid_values = [None, 1, "", {}, [1, 2, 3], ["hda1", "hda2"],
832
                        [{"_unknown_": 999, }]]
833

    
834
      for invvalue in invalid_values:
835
        data = reqfields.copy()
836
        data[field] = invvalue
837
        self.assertRaises(http.HttpBadRequest, self.Parse, data, False)
838

    
839

    
840
class TestBackupExport(unittest.TestCase):
841
  def test(self):
842
    clfactory = _FakeClientFactory(_FakeClient)
843

    
844
    name = "instmoo"
845
    data = {
846
      "mode": constants.EXPORT_MODE_REMOTE,
847
      "destination": [(1, 2, 3), (99, 99, 99)],
848
      "shutdown": True,
849
      "remove_instance": True,
850
      "x509_key_name": ["name", "hash"],
851
      "destination_x509_ca": "---cert---"
852
      }
853

    
854
    handler = _CreateHandler(rlib2.R_2_instances_name_export, [name], {},
855
                             data, clfactory)
856
    job_id = handler.PUT()
857

    
858
    cl = clfactory.GetNextClient()
859
    self.assertRaises(IndexError, clfactory.GetNextClient)
860

    
861
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
862
    self.assertEqual(job_id, exp_job_id)
863
    self.assertTrue(isinstance(op, opcodes.OpBackupExport))
864
    self.assertEqual(op.instance_name, name)
865
    self.assertEqual(op.mode, constants.EXPORT_MODE_REMOTE)
866
    self.assertEqual(op.target_node, [(1, 2, 3), (99, 99, 99)])
867
    self.assertEqual(op.shutdown, True)
868
    self.assertEqual(op.remove_instance, True)
869
    self.assertEqual(op.x509_key_name, ["name", "hash"])
870
    self.assertEqual(op.destination_x509_ca, "---cert---")
871
    self.assertFalse(hasattr(op, "dry_run"))
872
    self.assertFalse(hasattr(op, "force"))
873

    
874
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
875

    
876
  def testDefaults(self):
877
    clfactory = _FakeClientFactory(_FakeClient)
878

    
879
    name = "inst1"
880
    data = {
881
      "destination": "node2",
882
      "shutdown": False,
883
      }
884

    
885
    handler = _CreateHandler(rlib2.R_2_instances_name_export, [name], {},
886
                             data, clfactory)
887
    job_id = handler.PUT()
888

    
889
    cl = clfactory.GetNextClient()
890
    self.assertRaises(IndexError, clfactory.GetNextClient)
891

    
892
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
893
    self.assertEqual(job_id, exp_job_id)
894
    self.assertTrue(isinstance(op, opcodes.OpBackupExport))
895
    self.assertEqual(op.instance_name, name)
896
    self.assertEqual(op.target_node, "node2")
897
    self.assertFalse(hasattr(op, "mode"))
898
    self.assertFalse(hasattr(op, "remove_instance"))
899
    self.assertFalse(hasattr(op, "destination"))
900
    self.assertFalse(hasattr(op, "dry_run"))
901
    self.assertFalse(hasattr(op, "force"))
902

    
903
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
904

    
905
  def testErrors(self):
906
    clfactory = _FakeClientFactory(_FakeClient)
907

    
908
    for value in ["True", "False"]:
909
      handler = _CreateHandler(rlib2.R_2_instances_name_export, ["err1"], {}, {
910
        "remove_instance": value,
911
        }, clfactory)
912
      self.assertRaises(http.HttpBadRequest, handler.PUT)
913

    
914

    
915
class TestInstanceMigrate(testutils.GanetiTestCase):
916
  def test(self):
917
    clfactory = _FakeClientFactory(_FakeClient)
918

    
919
    name = "instYooho6ek"
920

    
921
    for cleanup in [False, True]:
922
      for mode in constants.HT_MIGRATION_MODES:
923
        data = {
924
          "cleanup": cleanup,
925
          "mode": mode,
926
          }
927

    
928
        handler = _CreateHandler(rlib2.R_2_instances_name_migrate, [name], {},
929
                                 data, clfactory)
930
        job_id = handler.PUT()
931

    
932
        cl = clfactory.GetNextClient()
933
        self.assertRaises(IndexError, clfactory.GetNextClient)
934

    
935
        (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
936
        self.assertEqual(job_id, exp_job_id)
937
        self.assertTrue(isinstance(op, opcodes.OpInstanceMigrate))
938
        self.assertEqual(op.instance_name, name)
939
        self.assertEqual(op.mode, mode)
940
        self.assertEqual(op.cleanup, cleanup)
941
        self.assertFalse(hasattr(op, "dry_run"))
942
        self.assertFalse(hasattr(op, "force"))
943

    
944
        self.assertRaises(IndexError, cl.GetNextSubmittedJob)
945

    
946
  def testDefaults(self):
947
    clfactory = _FakeClientFactory(_FakeClient)
948

    
949
    name = "instnohZeex0"
950

    
951
    handler = _CreateHandler(rlib2.R_2_instances_name_migrate, [name], {}, {},
952
                             clfactory)
953
    job_id = handler.PUT()
954

    
955
    cl = clfactory.GetNextClient()
956
    self.assertRaises(IndexError, clfactory.GetNextClient)
957

    
958
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
959
    self.assertEqual(job_id, exp_job_id)
960
    self.assertTrue(isinstance(op, opcodes.OpInstanceMigrate))
961
    self.assertEqual(op.instance_name, name)
962
    self.assertFalse(hasattr(op, "mode"))
963
    self.assertFalse(hasattr(op, "cleanup"))
964
    self.assertFalse(hasattr(op, "dry_run"))
965
    self.assertFalse(hasattr(op, "force"))
966

    
967
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
968

    
969

    
970
class TestParseRenameInstanceRequest(testutils.GanetiTestCase):
971
  def test(self):
972
    clfactory = _FakeClientFactory(_FakeClient)
973

    
974
    name = "instij0eeph7"
975

    
976
    for new_name in ["ua0aiyoo", "fai3ongi"]:
977
      for ip_check in [False, True]:
978
        for name_check in [False, True]:
979
          data = {
980
            "new_name": new_name,
981
            "ip_check": ip_check,
982
            "name_check": name_check,
983
            }
984

    
985
          handler = _CreateHandler(rlib2.R_2_instances_name_rename, [name],
986
                                   {}, data, clfactory)
987
          job_id = handler.PUT()
988

    
989
          cl = clfactory.GetNextClient()
990
          self.assertRaises(IndexError, clfactory.GetNextClient)
991

    
992
          (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
993
          self.assertEqual(job_id, exp_job_id)
994
          self.assertTrue(isinstance(op, opcodes.OpInstanceRename))
995
          self.assertEqual(op.instance_name, name)
996
          self.assertEqual(op.new_name, new_name)
997
          self.assertEqual(op.ip_check, ip_check)
998
          self.assertEqual(op.name_check, name_check)
999
          self.assertFalse(hasattr(op, "dry_run"))
1000
          self.assertFalse(hasattr(op, "force"))
1001

    
1002
          self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1003

    
1004
  def testDefaults(self):
1005
    clfactory = _FakeClientFactory(_FakeClient)
1006

    
1007
    name = "instahchie3t"
1008

    
1009
    for new_name in ["thag9mek", "quees7oh"]:
1010
      data = {
1011
        "new_name": new_name,
1012
        }
1013

    
1014
      handler = _CreateHandler(rlib2.R_2_instances_name_rename, [name],
1015
                               {}, data, clfactory)
1016
      job_id = handler.PUT()
1017

    
1018
      cl = clfactory.GetNextClient()
1019
      self.assertRaises(IndexError, clfactory.GetNextClient)
1020

    
1021
      (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1022
      self.assertEqual(job_id, exp_job_id)
1023
      self.assertTrue(isinstance(op, opcodes.OpInstanceRename))
1024
      self.assertEqual(op.instance_name, name)
1025
      self.assertEqual(op.new_name, new_name)
1026
      self.assertFalse(hasattr(op, "ip_check"))
1027
      self.assertFalse(hasattr(op, "name_check"))
1028
      self.assertFalse(hasattr(op, "dry_run"))
1029
      self.assertFalse(hasattr(op, "force"))
1030

    
1031
      self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1032

    
1033

    
1034
class TestParseModifyInstanceRequest(unittest.TestCase):
1035
  def test(self):
1036
    clfactory = _FakeClientFactory(_FakeClient)
1037

    
1038
    name = "instush8gah"
1039

    
1040
    test_disks = [
1041
      [],
1042
      [(1, { constants.IDISK_MODE: constants.DISK_RDWR, })],
1043
      ]
1044

    
1045
    for osparams in [{}, { "some": "value", "other": "Hello World", }]:
1046
      for hvparams in [{}, { constants.HV_KERNEL_PATH: "/some/kernel", }]:
1047
        for beparams in [{}, { constants.BE_MEMORY: 128, }]:
1048
          for force in [False, True]:
1049
            for nics in [[], [(0, { constants.INIC_IP: "192.0.2.1", })]]:
1050
              for disks in test_disks:
1051
                for disk_template in constants.DISK_TEMPLATES:
1052
                  data = {
1053
                    "osparams": osparams,
1054
                    "hvparams": hvparams,
1055
                    "beparams": beparams,
1056
                    "nics": nics,
1057
                    "disks": disks,
1058
                    "force": force,
1059
                    "disk_template": disk_template,
1060
                    }
1061

    
1062
                  handler = _CreateHandler(rlib2.R_2_instances_name_modify,
1063
                                           [name], {}, data, clfactory)
1064
                  job_id = handler.PUT()
1065

    
1066
                  cl = clfactory.GetNextClient()
1067
                  self.assertRaises(IndexError, clfactory.GetNextClient)
1068

    
1069
                  (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1070
                  self.assertEqual(job_id, exp_job_id)
1071
                  self.assertTrue(isinstance(op, opcodes.OpInstanceSetParams))
1072
                  self.assertEqual(op.instance_name, name)
1073
                  self.assertEqual(op.hvparams, hvparams)
1074
                  self.assertEqual(op.beparams, beparams)
1075
                  self.assertEqual(op.osparams, osparams)
1076
                  self.assertEqual(op.force, force)
1077
                  self.assertEqual(op.nics, nics)
1078
                  self.assertEqual(op.disks, disks)
1079
                  self.assertEqual(op.disk_template, disk_template)
1080
                  self.assertFalse(hasattr(op, "remote_node"))
1081
                  self.assertFalse(hasattr(op, "os_name"))
1082
                  self.assertFalse(hasattr(op, "force_variant"))
1083
                  self.assertFalse(hasattr(op, "dry_run"))
1084

    
1085
                  self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1086

    
1087
  def testDefaults(self):
1088
    clfactory = _FakeClientFactory(_FakeClient)
1089

    
1090
    name = "instir8aish31"
1091

    
1092
    handler = _CreateHandler(rlib2.R_2_instances_name_modify,
1093
                             [name], {}, {}, clfactory)
1094
    job_id = handler.PUT()
1095

    
1096
    cl = clfactory.GetNextClient()
1097
    self.assertRaises(IndexError, clfactory.GetNextClient)
1098

    
1099
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1100
    self.assertEqual(job_id, exp_job_id)
1101
    self.assertTrue(isinstance(op, opcodes.OpInstanceSetParams))
1102
    self.assertEqual(op.instance_name, name)
1103

    
1104
    for i in ["hvparams", "beparams", "osparams", "force", "nics", "disks",
1105
              "disk_template", "remote_node", "os_name", "force_variant"]:
1106
      self.assertFalse(hasattr(op, i))
1107

    
1108

    
1109
class TestParseInstanceReinstallRequest(testutils.GanetiTestCase):
1110
  def setUp(self):
1111
    testutils.GanetiTestCase.setUp(self)
1112

    
1113
    self.Parse = rlib2._ParseInstanceReinstallRequest
1114

    
1115
  def _Check(self, ops, name):
1116
    expcls = [
1117
      opcodes.OpInstanceShutdown,
1118
      opcodes.OpInstanceReinstall,
1119
      opcodes.OpInstanceStartup,
1120
      ]
1121

    
1122
    self.assert_(compat.all(isinstance(op, exp)
1123
                            for op, exp in zip(ops, expcls)))
1124
    self.assert_(compat.all(op.instance_name == name for op in ops))
1125

    
1126
  def test(self):
1127
    name = "shoo0tihohma"
1128

    
1129
    ops = self.Parse(name, {"os": "sys1", "start": True,})
1130
    self.assertEqual(len(ops), 3)
1131
    self._Check(ops, name)
1132
    self.assertEqual(ops[1].os_type, "sys1")
1133
    self.assertFalse(ops[1].osparams)
1134

    
1135
    ops = self.Parse(name, {"os": "sys2", "start": False,})
1136
    self.assertEqual(len(ops), 2)
1137
    self._Check(ops, name)
1138
    self.assertEqual(ops[1].os_type, "sys2")
1139

    
1140
    osparams = {
1141
      "reformat": "1",
1142
      }
1143
    ops = self.Parse(name, {"os": "sys4035", "start": True,
1144
                            "osparams": osparams,})
1145
    self.assertEqual(len(ops), 3)
1146
    self._Check(ops, name)
1147
    self.assertEqual(ops[1].os_type, "sys4035")
1148
    self.assertEqual(ops[1].osparams, osparams)
1149

    
1150
  def testDefaults(self):
1151
    name = "noolee0g"
1152

    
1153
    ops = self.Parse(name, {"os": "linux1"})
1154
    self.assertEqual(len(ops), 3)
1155
    self._Check(ops, name)
1156
    self.assertEqual(ops[1].os_type, "linux1")
1157
    self.assertFalse(ops[1].osparams)
1158

    
1159

    
1160
class TestGroupRename(unittest.TestCase):
1161
  def test(self):
1162
    clfactory = _FakeClientFactory(_FakeClient)
1163

    
1164
    name = "group608242564"
1165
    data = {
1166
      "new_name": "ua0aiyoo15112",
1167
      }
1168

    
1169
    handler = _CreateHandler(rlib2.R_2_groups_name_rename, [name], {}, data,
1170
                             clfactory)
1171
    job_id = handler.PUT()
1172

    
1173
    cl = clfactory.GetNextClient()
1174
    self.assertRaises(IndexError, clfactory.GetNextClient)
1175

    
1176
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1177
    self.assertEqual(job_id, exp_job_id)
1178

    
1179
    self.assertTrue(isinstance(op, opcodes.OpGroupRename))
1180
    self.assertEqual(op.group_name, name)
1181
    self.assertEqual(op.new_name, "ua0aiyoo15112")
1182
    self.assertFalse(op.dry_run)
1183
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1184

    
1185
  def testDryRun(self):
1186
    clfactory = _FakeClientFactory(_FakeClient)
1187

    
1188
    name = "group28548"
1189
    data = {
1190
      "new_name": "ua0aiyoo",
1191
      }
1192

    
1193
    handler = _CreateHandler(rlib2.R_2_groups_name_rename, [name], {
1194
      "dry-run": ["1"],
1195
      }, data, clfactory)
1196
    job_id = handler.PUT()
1197

    
1198
    cl = clfactory.GetNextClient()
1199
    self.assertRaises(IndexError, clfactory.GetNextClient)
1200

    
1201
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1202
    self.assertEqual(job_id, exp_job_id)
1203

    
1204
    self.assertTrue(isinstance(op, opcodes.OpGroupRename))
1205
    self.assertEqual(op.group_name, name)
1206
    self.assertEqual(op.new_name, "ua0aiyoo")
1207
    self.assertTrue(op.dry_run)
1208
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1209

    
1210

    
1211
class TestInstanceReplaceDisks(unittest.TestCase):
1212
  def test(self):
1213
    clfactory = _FakeClientFactory(_FakeClient)
1214

    
1215
    name = "inst22568"
1216

    
1217
    for disks in [range(1, 4), "1,2,3", "1, 2, 3"]:
1218
      data = {
1219
        "mode": constants.REPLACE_DISK_SEC,
1220
        "disks": disks,
1221
        "iallocator": "myalloc",
1222
        }
1223

    
1224
      handler = _CreateHandler(rlib2.R_2_instances_name_replace_disks,
1225
                               [name], {}, data, clfactory)
1226
      job_id = handler.POST()
1227

    
1228
      cl = clfactory.GetNextClient()
1229
      self.assertRaises(IndexError, clfactory.GetNextClient)
1230

    
1231
      (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1232
      self.assertEqual(job_id, exp_job_id)
1233

    
1234
      self.assertTrue(isinstance(op, opcodes.OpInstanceReplaceDisks))
1235
      self.assertEqual(op.instance_name, name)
1236
      self.assertEqual(op.mode, constants.REPLACE_DISK_SEC)
1237
      self.assertEqual(op.disks, [1, 2, 3])
1238
      self.assertEqual(op.iallocator, "myalloc")
1239
      self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1240

    
1241
  def testDefaults(self):
1242
    clfactory = _FakeClientFactory(_FakeClient)
1243

    
1244
    name = "inst11413"
1245
    data = {
1246
      "mode": constants.REPLACE_DISK_AUTO,
1247
      }
1248

    
1249
    handler = _CreateHandler(rlib2.R_2_instances_name_replace_disks,
1250
                             [name], {}, data, clfactory)
1251
    job_id = handler.POST()
1252

    
1253
    cl = clfactory.GetNextClient()
1254
    self.assertRaises(IndexError, clfactory.GetNextClient)
1255

    
1256
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1257
    self.assertEqual(job_id, exp_job_id)
1258

    
1259
    self.assertTrue(isinstance(op, opcodes.OpInstanceReplaceDisks))
1260
    self.assertEqual(op.instance_name, name)
1261
    self.assertEqual(op.mode, constants.REPLACE_DISK_AUTO)
1262
    self.assertFalse(hasattr(op, "iallocator"))
1263
    self.assertFalse(hasattr(op, "disks"))
1264
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1265

    
1266
  def testWrong(self):
1267
    clfactory = _FakeClientFactory(_FakeClient)
1268

    
1269
    data = {
1270
      "mode": constants.REPLACE_DISK_AUTO,
1271
      "disks": "hello world",
1272
      }
1273

    
1274
    handler = _CreateHandler(rlib2.R_2_instances_name_replace_disks,
1275
                             ["foo"], {}, data, clfactory)
1276
    self.assertRaises(http.HttpBadRequest, handler.POST)
1277

    
1278

    
1279
class TestGroupModify(unittest.TestCase):
1280
  def test(self):
1281
    clfactory = _FakeClientFactory(_FakeClient)
1282

    
1283
    name = "group6002"
1284

    
1285
    for policy in constants.VALID_ALLOC_POLICIES:
1286
      data = {
1287
        "alloc_policy": policy,
1288
        }
1289

    
1290
      handler = _CreateHandler(rlib2.R_2_groups_name_modify, [name], {}, data,
1291
                               clfactory)
1292
      job_id = handler.PUT()
1293

    
1294
      cl = clfactory.GetNextClient()
1295
      self.assertRaises(IndexError, clfactory.GetNextClient)
1296

    
1297
      (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1298
      self.assertEqual(job_id, exp_job_id)
1299

    
1300
      self.assertTrue(isinstance(op, opcodes.OpGroupSetParams))
1301
      self.assertEqual(op.group_name, name)
1302
      self.assertEqual(op.alloc_policy, policy)
1303
      self.assertFalse(hasattr(op, "dry_run"))
1304
      self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1305

    
1306
  def testUnknownPolicy(self):
1307
    clfactory = _FakeClientFactory(_FakeClient)
1308

    
1309
    data = {
1310
      "alloc_policy": "_unknown_policy_",
1311
      }
1312

    
1313
    handler = _CreateHandler(rlib2.R_2_groups_name_modify, ["xyz"], {}, data,
1314
                             clfactory)
1315
    self.assertRaises(http.HttpBadRequest, handler.PUT)
1316
    self.assertRaises(IndexError, clfactory.GetNextClient)
1317

    
1318
  def testDefaults(self):
1319
    clfactory = _FakeClientFactory(_FakeClient)
1320

    
1321
    name = "group6679"
1322

    
1323
    handler = _CreateHandler(rlib2.R_2_groups_name_modify, [name], {}, {},
1324
                             clfactory)
1325
    job_id = handler.PUT()
1326

    
1327
    cl = clfactory.GetNextClient()
1328
    self.assertRaises(IndexError, clfactory.GetNextClient)
1329

    
1330
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1331
    self.assertEqual(job_id, exp_job_id)
1332

    
1333
    self.assertTrue(isinstance(op, opcodes.OpGroupSetParams))
1334
    self.assertEqual(op.group_name, name)
1335
    self.assertFalse(hasattr(op, "alloc_policy"))
1336
    self.assertFalse(hasattr(op, "dry_run"))
1337
    self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1338

    
1339

    
1340
class TestGroupAdd(unittest.TestCase):
1341
  def test(self):
1342
    name = "group3618"
1343
    clfactory = _FakeClientFactory(_FakeClient)
1344

    
1345
    for policy in constants.VALID_ALLOC_POLICIES:
1346
      data = {
1347
        "group_name": name,
1348
        "alloc_policy": policy,
1349
        }
1350

    
1351
      handler = _CreateHandler(rlib2.R_2_groups, [], {}, data,
1352
                               clfactory)
1353
      job_id = handler.POST()
1354

    
1355
      cl = clfactory.GetNextClient()
1356
      self.assertRaises(IndexError, clfactory.GetNextClient)
1357

    
1358
      (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1359
      self.assertEqual(job_id, exp_job_id)
1360

    
1361
      self.assertTrue(isinstance(op, opcodes.OpGroupAdd))
1362
      self.assertEqual(op.group_name, name)
1363
      self.assertEqual(op.alloc_policy, policy)
1364
      self.assertFalse(op.dry_run)
1365
      self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1366

    
1367
  def testUnknownPolicy(self):
1368
    clfactory = _FakeClientFactory(_FakeClient)
1369

    
1370
    data = {
1371
      "alloc_policy": "_unknown_policy_",
1372
      }
1373

    
1374
    handler = _CreateHandler(rlib2.R_2_groups, [], {}, data, clfactory)
1375
    self.assertRaises(http.HttpBadRequest, handler.POST)
1376
    self.assertRaises(IndexError, clfactory.GetNextClient)
1377

    
1378
  def testDefaults(self):
1379
    clfactory = _FakeClientFactory(_FakeClient)
1380

    
1381
    name = "group15395"
1382
    data = {
1383
      "group_name": name,
1384
      }
1385

    
1386
    handler = _CreateHandler(rlib2.R_2_groups, [], {}, data, clfactory)
1387
    job_id = handler.POST()
1388

    
1389
    cl = clfactory.GetNextClient()
1390
    self.assertRaises(IndexError, clfactory.GetNextClient)
1391

    
1392
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1393
    self.assertEqual(job_id, exp_job_id)
1394

    
1395
    self.assertTrue(isinstance(op, opcodes.OpGroupAdd))
1396
    self.assertEqual(op.group_name, name)
1397
    self.assertFalse(hasattr(op, "alloc_policy"))
1398
    self.assertFalse(op.dry_run)
1399

    
1400
  def testLegacyName(self):
1401
    clfactory = _FakeClientFactory(_FakeClient)
1402

    
1403
    name = "group29852"
1404
    data = {
1405
      "name": name,
1406
      }
1407

    
1408
    handler = _CreateHandler(rlib2.R_2_groups, [], {
1409
      "dry-run": ["1"],
1410
      }, data, clfactory)
1411
    job_id = handler.POST()
1412

    
1413
    cl = clfactory.GetNextClient()
1414
    self.assertRaises(IndexError, clfactory.GetNextClient)
1415

    
1416
    (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1417
    self.assertEqual(job_id, exp_job_id)
1418

    
1419
    self.assertTrue(isinstance(op, opcodes.OpGroupAdd))
1420
    self.assertEqual(op.group_name, name)
1421
    self.assertFalse(hasattr(op, "alloc_policy"))
1422
    self.assertTrue(op.dry_run)
1423

    
1424

    
1425
class TestNodeRole(unittest.TestCase):
1426
  def test(self):
1427
    clfactory = _FakeClientFactory(_FakeClient)
1428

    
1429
    for role in rlib2._NR_MAP.values():
1430
      handler = _CreateHandler(rlib2.R_2_nodes_name_role,
1431
                               ["node-z"], {}, role, clfactory)
1432
      if role == rlib2._NR_MASTER:
1433
        self.assertRaises(http.HttpBadRequest, handler.PUT)
1434
      else:
1435
        job_id = handler.PUT()
1436

    
1437
        cl = clfactory.GetNextClient()
1438
        self.assertRaises(IndexError, clfactory.GetNextClient)
1439

    
1440
        (exp_job_id, (op, )) = cl.GetNextSubmittedJob()
1441
        self.assertEqual(job_id, exp_job_id)
1442
        self.assertTrue(isinstance(op, opcodes.OpNodeSetParams))
1443
        self.assertEqual(op.node_name, "node-z")
1444
        self.assertFalse(op.force)
1445
        self.assertFalse(hasattr(op, "dry_run"))
1446

    
1447
        if role == rlib2._NR_REGULAR:
1448
          self.assertFalse(op.drained)
1449
          self.assertFalse(op.offline)
1450
          self.assertFalse(op.master_candidate)
1451
        elif role == rlib2._NR_MASTER_CANDIDATE:
1452
          self.assertFalse(op.drained)
1453
          self.assertFalse(op.offline)
1454
          self.assertTrue(op.master_candidate)
1455
        elif role == rlib2._NR_DRAINED:
1456
          self.assertTrue(op.drained)
1457
          self.assertFalse(op.offline)
1458
          self.assertFalse(op.master_candidate)
1459
        elif role == rlib2._NR_OFFLINE:
1460
          self.assertFalse(op.drained)
1461
          self.assertTrue(op.offline)
1462
          self.assertFalse(op.master_candidate)
1463
        else:
1464
          self.fail("Unknown role '%s'" % role)
1465

    
1466
      self.assertRaises(IndexError, cl.GetNextSubmittedJob)
1467

    
1468

    
1469
if __name__ == '__main__':
1470
  testutils.GanetiTestProgram()