ganeti.rapi.client_unittest.py 15.8 KB
Newer Older
David Knowles's avatar
David Knowles committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/python
#

# Copyright (C) 2010 Google Inc.
#
# 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
# 02110-1301, USA.


"""Script for unittesting the RAPI client module"""


import re
import unittest
import warnings

from ganeti import http
30
from ganeti import serializer
David Knowles's avatar
David Knowles committed
31
32
33

from ganeti.rapi import connector
from ganeti.rapi import rlib2
34
from ganeti.rapi import client
David Knowles's avatar
David Knowles committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

import testutils


_URI_RE = re.compile(r"https://(?P<host>.*):(?P<port>\d+)(?P<path>/.*)")


def _GetPathFromUri(uri):
  """Gets the path and query from a URI.

  """
  match = _URI_RE.match(uri)
  if match:
    return match.groupdict()["path"]
  else:
    return None


53
54
class HttpResponseMock:
  """Dumb mock of httplib.HTTPResponse.
David Knowles's avatar
David Knowles committed
55
56
57

  """

58
59
60
61
62
63
  def __init__(self, code, data):
    self.code = code
    self._data = data

  def read(self):
    return self._data
David Knowles's avatar
David Knowles committed
64
65


66
67
class OpenerDirectorMock:
  """Mock for urllib.OpenerDirector.
David Knowles's avatar
David Knowles committed
68
69
70
71
72

  """

  def __init__(self, rapi):
    self._rapi = rapi
73
    self.last_request = None
David Knowles's avatar
David Knowles committed
74

75
76
  def open(self, req):
    self.last_request = req
David Knowles's avatar
David Knowles committed
77

78
79
80
    path = _GetPathFromUri(req.get_full_url())
    code, resp_body = self._rapi.FetchResponse(path, req.get_method())
    return HttpResponseMock(code, resp_body)
David Knowles's avatar
David Knowles committed
81
82
83
84
85
86
87
88


class RapiMock(object):
  def __init__(self):
    self._mapper = connector.Mapper()
    self._responses = []
    self._last_handler = None

89
90
  def AddResponse(self, response, code=200):
    self._responses.insert(0, (code, response))
David Knowles's avatar
David Knowles committed
91
92
93
94
95
96
97
98
99

  def GetLastHandler(self):
    return self._last_handler

  def FetchResponse(self, path, method):
    try:
      HandlerClass, items, args = self._mapper.getController(path)
      self._last_handler = HandlerClass(items, args, None)
      if not hasattr(self._last_handler, method.upper()):
100
101
        raise http.HttpNotImplemented(message="Method not implemented")

David Knowles's avatar
David Knowles committed
102
103
104
    except http.HttpException, ex:
      code = ex.code
      response = ex.message
105
106
107
    else:
      if not self._responses:
        raise Exception("No responses")
David Knowles's avatar
David Knowles committed
108

109
      (code, response) = self._responses.pop()
David Knowles's avatar
David Knowles committed
110
111
112
113
114
115
116
117
118

    return code, response


class RapiMockTest(unittest.TestCase):
  def test(self):
    rapi = RapiMock()
    path = "/version"
    self.assertEqual((404, None), rapi.FetchResponse("/foo", "GET"))
119
    self.assertEqual((501, "Method not implemented"),
David Knowles's avatar
David Knowles committed
120
121
122
123
124
125
126
127
                     rapi.FetchResponse("/version", "POST"))
    rapi.AddResponse("2")
    code, response = rapi.FetchResponse("/version", "GET")
    self.assertEqual(200, code)
    self.assertEqual("2", response)
    self.failUnless(isinstance(rapi.GetLastHandler(), rlib2.R_version))


128
class GanetiRapiClientTests(testutils.GanetiTestCase):
David Knowles's avatar
David Knowles committed
129
  def setUp(self):
130
131
    testutils.GanetiTestCase.setUp(self)

David Knowles's avatar
David Knowles committed
132
    self.rapi = RapiMock()
133
    self.http = OpenerDirectorMock(self.rapi)
David Knowles's avatar
David Knowles committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
    self.client = client.GanetiRapiClient('master.foo.com')
    self.client._http = self.http
    # Hard-code the version for easier testing.
    self.client._version = 2

  def assertHandler(self, handler_cls):
    self.failUnless(isinstance(self.rapi.GetLastHandler(), handler_cls))

  def assertQuery(self, key, value):
    self.assertEqual(value, self.rapi.GetLastHandler().queryargs.get(key, None))

  def assertItems(self, items):
    self.assertEqual(items, self.rapi.GetLastHandler().items)

  def assertBulk(self):
    self.assertTrue(self.rapi.GetLastHandler().useBulk())

  def assertDryRun(self):
    self.assertTrue(self.rapi.GetLastHandler().dryRun())

  def testGetVersion(self):
    self.client._version = None
    self.rapi.AddResponse("2")
    self.assertEqual(2, self.client.GetVersion())
    self.assertHandler(rlib2.R_version)

  def testGetOperatingSystems(self):
    self.rapi.AddResponse("[\"beos\"]")
    self.assertEqual(["beos"], self.client.GetOperatingSystems())
    self.assertHandler(rlib2.R_2_os)

  def testGetClusterTags(self):
    self.rapi.AddResponse("[\"tag\"]")
    self.assertEqual(["tag"], self.client.GetClusterTags())
    self.assertHandler(rlib2.R_2_tags)

  def testAddClusterTags(self):
171
172
173
    self.rapi.AddResponse("1234")
    self.assertEqual(1234,
        self.client.AddClusterTags(["awesome"], dry_run=True))
David Knowles's avatar
David Knowles committed
174
175
176
177
178
    self.assertHandler(rlib2.R_2_tags)
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])

  def testDeleteClusterTags(self):
179
180
181
    self.rapi.AddResponse("5107")
    self.assertEqual(5107, self.client.DeleteClusterTags(["awesome"],
                                                         dry_run=True))
David Knowles's avatar
David Knowles committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    self.assertHandler(rlib2.R_2_tags)
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])

  def testGetInfo(self):
    self.rapi.AddResponse("{}")
    self.assertEqual({}, self.client.GetInfo())
    self.assertHandler(rlib2.R_2_info)

  def testGetInstances(self):
    self.rapi.AddResponse("[]")
    self.assertEqual([], self.client.GetInstances(bulk=True))
    self.assertHandler(rlib2.R_2_instances)
    self.assertBulk()

  def testGetInstanceInfo(self):
    self.rapi.AddResponse("[]")
    self.assertEqual([], self.client.GetInstanceInfo("instance"))
    self.assertHandler(rlib2.R_2_instances_name)
    self.assertItems(["instance"])

  def testCreateInstance(self):
    self.rapi.AddResponse("1234")
    self.assertEqual(1234, self.client.CreateInstance(dry_run=True))
    self.assertHandler(rlib2.R_2_instances)
    self.assertDryRun()

  def testDeleteInstance(self):
210
211
    self.rapi.AddResponse("1234")
    self.assertEqual(1234, self.client.DeleteInstance("instance", dry_run=True))
David Knowles's avatar
David Knowles committed
212
213
214
215
216
217
218
219
220
221
222
    self.assertHandler(rlib2.R_2_instances_name)
    self.assertItems(["instance"])
    self.assertDryRun()

  def testGetInstanceTags(self):
    self.rapi.AddResponse("[]")
    self.assertEqual([], self.client.GetInstanceTags("fooinstance"))
    self.assertHandler(rlib2.R_2_instances_name_tags)
    self.assertItems(["fooinstance"])

  def testAddInstanceTags(self):
223
224
225
    self.rapi.AddResponse("1234")
    self.assertEqual(1234,
        self.client.AddInstanceTags("fooinstance", ["awesome"], dry_run=True))
David Knowles's avatar
David Knowles committed
226
227
228
229
230
231
    self.assertHandler(rlib2.R_2_instances_name_tags)
    self.assertItems(["fooinstance"])
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])

  def testDeleteInstanceTags(self):
232
233
234
    self.rapi.AddResponse("25826")
    self.assertEqual(25826, self.client.DeleteInstanceTags("foo", ["awesome"],
                                                           dry_run=True))
David Knowles's avatar
David Knowles committed
235
236
237
238
239
240
    self.assertHandler(rlib2.R_2_instances_name_tags)
    self.assertItems(["foo"])
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])

  def testRebootInstance(self):
241
242
243
244
    self.rapi.AddResponse("6146")
    job_id = self.client.RebootInstance("i-bar", reboot_type="hard",
                                        ignore_secondaries=True, dry_run=True)
    self.assertEqual(6146, job_id)
David Knowles's avatar
David Knowles committed
245
246
247
248
249
250
251
    self.assertHandler(rlib2.R_2_instances_name_reboot)
    self.assertItems(["i-bar"])
    self.assertDryRun()
    self.assertQuery("type", ["hard"])
    self.assertQuery("ignore_secondaries", ["True"])

  def testShutdownInstance(self):
252
253
254
    self.rapi.AddResponse("1487")
    self.assertEqual(1487, self.client.ShutdownInstance("foo-instance",
                                                        dry_run=True))
David Knowles's avatar
David Knowles committed
255
256
257
258
259
    self.assertHandler(rlib2.R_2_instances_name_shutdown)
    self.assertItems(["foo-instance"])
    self.assertDryRun()

  def testStartupInstance(self):
260
261
262
    self.rapi.AddResponse("27149")
    self.assertEqual(27149, self.client.StartupInstance("bar-instance",
                                                        dry_run=True))
David Knowles's avatar
David Knowles committed
263
264
265
266
267
    self.assertHandler(rlib2.R_2_instances_name_startup)
    self.assertItems(["bar-instance"])
    self.assertDryRun()

  def testReinstallInstance(self):
268
269
270
    self.rapi.AddResponse("19119")
    self.assertEqual(19119, self.client.ReinstallInstance("baz-instance", "DOS",
                                                          no_startup=True))
David Knowles's avatar
David Knowles committed
271
272
273
274
275
276
277
278
    self.assertHandler(rlib2.R_2_instances_name_reinstall)
    self.assertItems(["baz-instance"])
    self.assertQuery("os", ["DOS"])
    self.assertQuery("nostartup", ["1"])

  def testReplaceInstanceDisks(self):
    self.rapi.AddResponse("999")
    job_id = self.client.ReplaceInstanceDisks("instance-name",
279
        ["hda", "hdc"], dry_run=True, iallocator="hail")
David Knowles's avatar
David Knowles committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
    self.assertEqual(999, job_id)
    self.assertHandler(rlib2.R_2_instances_name_replace_disks)
    self.assertItems(["instance-name"])
    self.assertQuery("disks", ["hda,hdc"])
    self.assertQuery("mode", ["replace_auto"])
    self.assertQuery("iallocator", ["hail"])
    self.assertDryRun()

    self.assertRaises(client.InvalidReplacementMode,
                      self.client.ReplaceInstanceDisks,
                      "instance_a", ["hda"], mode="invalid_mode")
    self.assertRaises(client.GanetiApiError,
                      self.client.ReplaceInstanceDisks,
                      "instance-foo", ["hda"], mode="replace_on_secondary")

    self.rapi.AddResponse("1000")
    job_id = self.client.ReplaceInstanceDisks("instance-bar",
        ["hda"], mode="replace_on_secondary", remote_node="foo-node",
        dry_run=True)
    self.assertEqual(1000, job_id)
    self.assertItems(["instance-bar"])
    self.assertQuery("disks", ["hda"])
    self.assertQuery("remote_node", ["foo-node"])
    self.assertDryRun()

  def testGetJobs(self):
306
307
    self.rapi.AddResponse('[ { "id": "123", "uri": "\\/2\\/jobs\\/123" },'
                          '  { "id": "124", "uri": "\\/2\\/jobs\\/124" } ]')
David Knowles's avatar
David Knowles committed
308
309
310
311
312
313
314
315
316
    self.assertEqual([123, 124], self.client.GetJobs())
    self.assertHandler(rlib2.R_2_jobs)

  def testGetJobStatus(self):
    self.rapi.AddResponse("{\"foo\": \"bar\"}")
    self.assertEqual({"foo": "bar"}, self.client.GetJobStatus(1234))
    self.assertHandler(rlib2.R_2_jobs_id)
    self.assertItems(["1234"])

317
318
319
320
321
322
323
324
325
326
327
328
329
  def testWaitForJobChange(self):
    fields = ["id", "summary"]
    expected = {
      "job_info": [123, "something"],
      "log_entries": [],
      }

    self.rapi.AddResponse(serializer.DumpJson(expected))
    result = self.client.WaitForJobChange(123, fields, [], -1)
    self.assertEqualValues(expected, result)
    self.assertHandler(rlib2.R_2_jobs_id_wait)
    self.assertItems(["123"])

330
  def testCancelJob(self):
331
332
    self.rapi.AddResponse("[true, \"Job 123 will be canceled\"]")
    self.assertEqual([True, "Job 123 will be canceled"],
333
                     self.client.CancelJob(999, dry_run=True))
David Knowles's avatar
David Knowles committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
    self.assertHandler(rlib2.R_2_jobs_id)
    self.assertItems(["999"])
    self.assertDryRun()

  def testGetNodes(self):
    self.rapi.AddResponse("[ { \"id\": \"node1\", \"uri\": \"uri1\" },"
                          " { \"id\": \"node2\", \"uri\": \"uri2\" } ]")
    self.assertEqual(["node1", "node2"], self.client.GetNodes())
    self.assertHandler(rlib2.R_2_nodes)

    self.rapi.AddResponse("[ { \"id\": \"node1\", \"uri\": \"uri1\" },"
                          " { \"id\": \"node2\", \"uri\": \"uri2\" } ]")
    self.assertEqual([{"id": "node1", "uri": "uri1"},
                      {"id": "node2", "uri": "uri2"}],
                     self.client.GetNodes(bulk=True))
    self.assertHandler(rlib2.R_2_nodes)
    self.assertBulk()

  def testGetNodeInfo(self):
    self.rapi.AddResponse("{}")
    self.assertEqual({}, self.client.GetNodeInfo("node-foo"))
    self.assertHandler(rlib2.R_2_nodes_name)
    self.assertItems(["node-foo"])

  def testEvacuateNode(self):
    self.rapi.AddResponse("9876")
    job_id = self.client.EvacuateNode("node-1", remote_node="node-2")
    self.assertEqual(9876, job_id)
    self.assertHandler(rlib2.R_2_nodes_name_evacuate)
    self.assertItems(["node-1"])
    self.assertQuery("remote_node", ["node-2"])

    self.rapi.AddResponse("8888")
    job_id = self.client.EvacuateNode("node-3", iallocator="hail", dry_run=True)
    self.assertEqual(8888, job_id)
    self.assertItems(["node-3"])
    self.assertQuery("iallocator", ["hail"])
    self.assertDryRun()

    self.assertRaises(client.GanetiApiError,
                      self.client.EvacuateNode,
                      "node-4", iallocator="hail", remote_node="node-5")

  def testMigrateNode(self):
    self.rapi.AddResponse("1111")
    self.assertEqual(1111, self.client.MigrateNode("node-a", dry_run=True))
    self.assertHandler(rlib2.R_2_nodes_name_migrate)
    self.assertItems(["node-a"])
    self.assertQuery("live", ["1"])
    self.assertDryRun()

  def testGetNodeRole(self):
    self.rapi.AddResponse("\"master\"")
    self.assertEqual("master", self.client.GetNodeRole("node-a"))
    self.assertHandler(rlib2.R_2_nodes_name_role)
    self.assertItems(["node-a"])

  def testSetNodeRole(self):
    self.rapi.AddResponse("789")
    self.assertEqual(789,
        self.client.SetNodeRole("node-foo", "master-candidate", force=True))
    self.assertHandler(rlib2.R_2_nodes_name_role)
    self.assertItems(["node-foo"])
    self.assertQuery("force", ["True"])
398
    self.assertEqual("\"master-candidate\"", self.http.last_request.data)
David Knowles's avatar
David Knowles committed
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427

    self.assertRaises(client.InvalidNodeRole,
                      self.client.SetNodeRole, "node-bar", "fake-role")

  def testGetNodeStorageUnits(self):
    self.rapi.AddResponse("42")
    self.assertEqual(42,
        self.client.GetNodeStorageUnits("node-x", "lvm-pv", "fields"))
    self.assertHandler(rlib2.R_2_nodes_name_storage)
    self.assertItems(["node-x"])
    self.assertQuery("storage_type", ["lvm-pv"])
    self.assertQuery("output_fields", ["fields"])

    self.assertRaises(client.InvalidStorageType,
                      self.client.GetNodeStorageUnits,
                      "node-y", "floppy-disk", "fields")

  def testModifyNodeStorageUnits(self):
    self.rapi.AddResponse("14")
    self.assertEqual(14,
        self.client.ModifyNodeStorageUnits("node-z", "lvm-pv", "hda"))
    self.assertHandler(rlib2.R_2_nodes_name_storage_modify)
    self.assertItems(["node-z"])
    self.assertQuery("storage_type", ["lvm-pv"])
    self.assertQuery("name", ["hda"])

    self.assertRaises(client.InvalidStorageType,
                      self.client.ModifyNodeStorageUnits,
                      "node-n", "floppy-disk", "hdc")
428
429
430
431
432
433
434
435
436
437
438
439
440

  def testRepairNodeStorageUnits(self):
    self.rapi.AddResponse("99")
    self.assertEqual(99, self.client.RepairNodeStorageUnits("node-z", "lvm-pv",
                                                            "hda"))
    self.assertHandler(rlib2.R_2_nodes_name_storage_repair)
    self.assertItems(["node-z"])
    self.assertQuery("storage_type", ["lvm-pv"])
    self.assertQuery("name", ["hda"])

    self.assertRaises(client.InvalidStorageType,
                      self.client.RepairNodeStorageUnits,
                      "node-n", "floppy-disk", "hdc")
David Knowles's avatar
David Knowles committed
441
442
443
444
445
446
447
448

  def testGetNodeTags(self):
    self.rapi.AddResponse("[\"fry\", \"bender\"]")
    self.assertEqual(["fry", "bender"], self.client.GetNodeTags("node-k"))
    self.assertHandler(rlib2.R_2_nodes_name_tags)
    self.assertItems(["node-k"])

  def testAddNodeTags(self):
449
450
451
    self.rapi.AddResponse("1234")
    self.assertEqual(1234,
        self.client.AddNodeTags("node-v", ["awesome"], dry_run=True))
David Knowles's avatar
David Knowles committed
452
453
454
455
456
457
    self.assertHandler(rlib2.R_2_nodes_name_tags)
    self.assertItems(["node-v"])
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])

  def testDeleteNodeTags(self):
458
459
460
    self.rapi.AddResponse("16861")
    self.assertEqual(16861, self.client.DeleteNodeTags("node-w", ["awesome"],
                                                       dry_run=True))
David Knowles's avatar
David Knowles committed
461
462
463
464
465
466
467
    self.assertHandler(rlib2.R_2_nodes_name_tags)
    self.assertItems(["node-w"])
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])


if __name__ == '__main__':
468
  testutils.GanetiTestProgram()