ganeti.rapi.client_unittest.py 44.7 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
#!/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
28
import pycurl
David Knowles's avatar
David Knowles committed
29

30
from ganeti import constants
David Knowles's avatar
David Knowles committed
31
from ganeti import http
32
from ganeti import serializer
33
from ganeti import utils
34 35
from ganeti import query
from ganeti import objects
David Knowles's avatar
David Knowles committed
36 37 38

from ganeti.rapi import connector
from ganeti.rapi import rlib2
39
from ganeti.rapi import client
David Knowles's avatar
David Knowles committed
40 41 42 43 44 45

import testutils


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

46 47 48 49 50 51 52 53 54
# List of resource handlers which aren't used by the RAPI client
_KNOWN_UNUSED = set([
  connector.R_root,
  connector.R_2,
  ])

# Global variable for collecting used handlers
_used_handlers = None

David Knowles's avatar
David Knowles committed
55 56 57 58 59 60 61 62 63 64 65 66

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


67 68 69 70 71
class FakeCurl:
  def __init__(self, rapi):
    self._rapi = rapi
    self._opts = {}
    self._info = {}
72

73 74
  def setopt(self, opt, value):
    self._opts[opt] = value
David Knowles's avatar
David Knowles committed
75

76 77
  def getopt(self, opt):
    return self._opts.get(opt)
David Knowles's avatar
David Knowles committed
78

79 80
  def unsetopt(self, opt):
    self._opts.pop(opt, None)
David Knowles's avatar
David Knowles committed
81

82 83
  def getinfo(self, info):
    return self._info[info]
David Knowles's avatar
David Knowles committed
84

85 86 87 88 89
  def perform(self):
    method = self._opts[pycurl.CUSTOMREQUEST]
    url = self._opts[pycurl.URL]
    request_body = self._opts[pycurl.POSTFIELDS]
    writefn = self._opts[pycurl.WRITEFUNCTION]
David Knowles's avatar
David Knowles committed
90

91 92
    path = _GetPathFromUri(url)
    (code, resp_body) = self._rapi.FetchResponse(path, method, request_body)
David Knowles's avatar
David Knowles committed
93

94 95 96
    self._info[pycurl.RESPONSE_CODE] = code
    if resp_body is not None:
      writefn(resp_body)
David Knowles's avatar
David Knowles committed
97 98 99 100 101 102 103


class RapiMock(object):
  def __init__(self):
    self._mapper = connector.Mapper()
    self._responses = []
    self._last_handler = None
104
    self._last_req_data = None
David Knowles's avatar
David Knowles committed
105

106 107
  def AddResponse(self, response, code=200):
    self._responses.insert(0, (code, response))
David Knowles's avatar
David Knowles committed
108

109 110 111
  def CountPending(self):
    return len(self._responses)

David Knowles's avatar
David Knowles committed
112 113 114
  def GetLastHandler(self):
    return self._last_handler

115 116 117 118 119 120
  def GetLastRequestData(self):
    return self._last_req_data

  def FetchResponse(self, path, method, request_body):
    self._last_req_data = request_body

David Knowles's avatar
David Knowles committed
121
    try:
122 123 124 125 126 127
      (handler_cls, items, args) = self._mapper.getController(path)

      # Record handler as used
      _used_handlers.add(handler_cls)

      self._last_handler = handler_cls(items, args, None)
David Knowles's avatar
David Knowles committed
128
      if not hasattr(self._last_handler, method.upper()):
129 130
        raise http.HttpNotImplemented(message="Method not implemented")

David Knowles's avatar
David Knowles committed
131 132 133
    except http.HttpException, ex:
      code = ex.code
      response = ex.message
134 135 136
    else:
      if not self._responses:
        raise Exception("No responses")
David Knowles's avatar
David Knowles committed
137

138
      (code, response) = self._responses.pop()
David Knowles's avatar
David Knowles committed
139 140 141 142

    return code, response


143 144 145 146 147 148 149
class TestConstants(unittest.TestCase):
  def test(self):
    self.assertEqual(client.GANETI_RAPI_PORT, constants.DEFAULT_RAPI_PORT)
    self.assertEqual(client.GANETI_RAPI_VERSION, constants.RAPI_VERSION)
    self.assertEqual(client.HTTP_APP_JSON, http.HTTP_APP_JSON)
    self.assertEqual(client._REQ_DATA_VERSION_FIELD, rlib2._REQ_DATA_VERSION)
    self.assertEqual(client._INST_CREATE_REQV1, rlib2._INST_CREATE_REQV1)
150
    self.assertEqual(client._INST_REINSTALL_REQV1, rlib2._INST_REINSTALL_REQV1)
151
    self.assertEqual(client._INST_NIC_PARAMS, constants.INIC_PARAMS)
152 153


David Knowles's avatar
David Knowles committed
154 155 156 157
class RapiMockTest(unittest.TestCase):
  def test(self):
    rapi = RapiMock()
    path = "/version"
158
    self.assertEqual((404, None), rapi.FetchResponse("/foo", "GET", None))
159
    self.assertEqual((501, "Method not implemented"),
160
                     rapi.FetchResponse("/version", "POST", None))
David Knowles's avatar
David Knowles committed
161
    rapi.AddResponse("2")
162
    code, response = rapi.FetchResponse("/version", "GET", None)
David Knowles's avatar
David Knowles committed
163 164 165 166 167
    self.assertEqual(200, code)
    self.assertEqual("2", response)
    self.failUnless(isinstance(rapi.GetLastHandler(), rlib2.R_version))


168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
def _FakeNoSslPycurlVersion():
  # Note: incomplete version tuple
  return (3, "7.16.0", 462848, "mysystem", 1581, None, 0)


def _FakeFancySslPycurlVersion():
  # Note: incomplete version tuple
  return (3, "7.16.0", 462848, "mysystem", 1581, "FancySSL/1.2.3", 0)


def _FakeOpenSslPycurlVersion():
  # Note: incomplete version tuple
  return (2, "7.15.5", 462597, "othersystem", 668, "OpenSSL/0.9.8c", 0)


def _FakeGnuTlsPycurlVersion():
  # Note: incomplete version tuple
  return (3, "7.18.0", 463360, "somesystem", 1581, "GnuTLS/2.0.4", 0)


class TestExtendedConfig(unittest.TestCase):
  def testAuth(self):
    cl = client.GanetiRapiClient("master.example.com",
                                 username="user", password="pw",
192
                                 curl_factory=lambda: FakeCurl(RapiMock()))
193

194
    curl = cl._CreateCurl()
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    self.assertEqual(curl.getopt(pycurl.HTTPAUTH), pycurl.HTTPAUTH_BASIC)
    self.assertEqual(curl.getopt(pycurl.USERPWD), "user:pw")

  def testInvalidAuth(self):
    # No username
    self.assertRaises(client.Error, client.GanetiRapiClient,
                      "master-a.example.com", password="pw")
    # No password
    self.assertRaises(client.Error, client.GanetiRapiClient,
                      "master-b.example.com", username="user")

  def testCertVerifyInvalidCombinations(self):
    self.assertRaises(client.Error, client.GenericCurlConfig,
                      use_curl_cabundle=True, cafile="cert1.pem")
    self.assertRaises(client.Error, client.GenericCurlConfig,
                      use_curl_cabundle=True, capath="certs/")
    self.assertRaises(client.Error, client.GenericCurlConfig,
                      use_curl_cabundle=True,
                      cafile="cert1.pem", capath="certs/")

  def testProxySignalVerifyHostname(self):
    for use_gnutls in [False, True]:
      if use_gnutls:
        pcverfn = _FakeGnuTlsPycurlVersion
      else:
        pcverfn = _FakeOpenSslPycurlVersion

      for proxy in ["", "http://127.0.0.1:1234"]:
        for use_signal in [False, True]:
          for verify_hostname in [False, True]:
            cfgfn = client.GenericCurlConfig(proxy=proxy, use_signal=use_signal,
                                             verify_hostname=verify_hostname,
                                             _pycurl_version_fn=pcverfn)

229
            curl_factory = lambda: FakeCurl(RapiMock())
230
            cl = client.GanetiRapiClient("master.example.com",
231 232
                                         curl_config_fn=cfgfn,
                                         curl_factory=curl_factory)
233

234
            curl = cl._CreateCurl()
235 236 237 238 239 240 241 242 243 244 245
            self.assertEqual(curl.getopt(pycurl.PROXY), proxy)
            self.assertEqual(curl.getopt(pycurl.NOSIGNAL), not use_signal)

            if verify_hostname:
              self.assertEqual(curl.getopt(pycurl.SSL_VERIFYHOST), 2)
            else:
              self.assertEqual(curl.getopt(pycurl.SSL_VERIFYHOST), 0)

  def testNoCertVerify(self):
    cfgfn = client.GenericCurlConfig()

246
    curl_factory = lambda: FakeCurl(RapiMock())
247
    cl = client.GanetiRapiClient("master.example.com", curl_config_fn=cfgfn,
248
                                 curl_factory=curl_factory)
249

250
    curl = cl._CreateCurl()
251 252 253 254 255 256 257
    self.assertFalse(curl.getopt(pycurl.SSL_VERIFYPEER))
    self.assertFalse(curl.getopt(pycurl.CAINFO))
    self.assertFalse(curl.getopt(pycurl.CAPATH))

  def testCertVerifyCurlBundle(self):
    cfgfn = client.GenericCurlConfig(use_curl_cabundle=True)

258
    curl_factory = lambda: FakeCurl(RapiMock())
259
    cl = client.GanetiRapiClient("master.example.com", curl_config_fn=cfgfn,
260
                                 curl_factory=curl_factory)
261

262
    curl = cl._CreateCurl()
263 264 265 266 267 268 269 270
    self.assert_(curl.getopt(pycurl.SSL_VERIFYPEER))
    self.assertFalse(curl.getopt(pycurl.CAINFO))
    self.assertFalse(curl.getopt(pycurl.CAPATH))

  def testCertVerifyCafile(self):
    mycert = "/tmp/some/UNUSED/cert/file.pem"
    cfgfn = client.GenericCurlConfig(cafile=mycert)

271
    curl_factory = lambda: FakeCurl(RapiMock())
272
    cl = client.GanetiRapiClient("master.example.com", curl_config_fn=cfgfn,
273
                                 curl_factory=curl_factory)
274

275
    curl = cl._CreateCurl()
276 277 278 279 280 281 282 283 284 285
    self.assert_(curl.getopt(pycurl.SSL_VERIFYPEER))
    self.assertEqual(curl.getopt(pycurl.CAINFO), mycert)
    self.assertFalse(curl.getopt(pycurl.CAPATH))

  def testCertVerifyCapath(self):
    certdir = "/tmp/some/UNUSED/cert/directory"
    pcverfn = _FakeOpenSslPycurlVersion
    cfgfn = client.GenericCurlConfig(capath=certdir,
                                     _pycurl_version_fn=pcverfn)

286
    curl_factory = lambda: FakeCurl(RapiMock())
287
    cl = client.GanetiRapiClient("master.example.com", curl_config_fn=cfgfn,
288
                                 curl_factory=curl_factory)
289

290
    curl = cl._CreateCurl()
291 292 293 294 295 296 297 298 299 300
    self.assert_(curl.getopt(pycurl.SSL_VERIFYPEER))
    self.assertEqual(curl.getopt(pycurl.CAPATH), certdir)
    self.assertFalse(curl.getopt(pycurl.CAINFO))

  def testCertVerifyCapathGnuTls(self):
    certdir = "/tmp/some/UNUSED/cert/directory"
    pcverfn = _FakeGnuTlsPycurlVersion
    cfgfn = client.GenericCurlConfig(capath=certdir,
                                     _pycurl_version_fn=pcverfn)

301 302 303 304 305
    curl_factory = lambda: FakeCurl(RapiMock())
    cl = client.GanetiRapiClient("master.example.com", curl_config_fn=cfgfn,
                                 curl_factory=curl_factory)

    self.assertRaises(client.Error, cl._CreateCurl)
306 307 308 309 310 311 312

  def testCertVerifyNoSsl(self):
    certdir = "/tmp/some/UNUSED/cert/directory"
    pcverfn = _FakeNoSslPycurlVersion
    cfgfn = client.GenericCurlConfig(capath=certdir,
                                     _pycurl_version_fn=pcverfn)

313 314 315 316 317
    curl_factory = lambda: FakeCurl(RapiMock())
    cl = client.GanetiRapiClient("master.example.com", curl_config_fn=cfgfn,
                                 curl_factory=curl_factory)

    self.assertRaises(client.Error, cl._CreateCurl)
318 319 320 321 322 323 324

  def testCertVerifyFancySsl(self):
    certdir = "/tmp/some/UNUSED/cert/directory"
    pcverfn = _FakeFancySslPycurlVersion
    cfgfn = client.GenericCurlConfig(capath=certdir,
                                     _pycurl_version_fn=pcverfn)

325 326 327 328 329
    curl_factory = lambda: FakeCurl(RapiMock())
    cl = client.GanetiRapiClient("master.example.com", curl_config_fn=cfgfn,
                                 curl_factory=curl_factory)

    self.assertRaises(NotImplementedError, cl._CreateCurl)
330 331 332 333 334 335 336

  def testCertVerifyCapath(self):
    for connect_timeout in [None, 1, 5, 10, 30, 60, 300]:
      for timeout in [None, 1, 30, 60, 3600, 24 * 3600]:
        cfgfn = client.GenericCurlConfig(connect_timeout=connect_timeout,
                                         timeout=timeout)

337
        curl_factory = lambda: FakeCurl(RapiMock())
338
        cl = client.GanetiRapiClient("master.example.com", curl_config_fn=cfgfn,
339
                                     curl_factory=curl_factory)
340

341
        curl = cl._CreateCurl()
342 343 344 345
        self.assertEqual(curl.getopt(pycurl.CONNECTTIMEOUT), connect_timeout)
        self.assertEqual(curl.getopt(pycurl.TIMEOUT), timeout)


346
class GanetiRapiClientTests(testutils.GanetiTestCase):
David Knowles's avatar
David Knowles committed
347
  def setUp(self):
348 349
    testutils.GanetiTestCase.setUp(self)

David Knowles's avatar
David Knowles committed
350
    self.rapi = RapiMock()
351 352
    self.curl = FakeCurl(self.rapi)
    self.client = client.GanetiRapiClient("master.example.com",
353
                                          curl_factory=lambda: self.curl)
David Knowles's avatar
David Knowles committed
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369

  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())

370 371 372
  def assertUseForce(self):
    self.assertTrue(self.rapi.GetLastHandler().useForce())

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
  def testEncodeQuery(self):
    query = [
      ("a", None),
      ("b", 1),
      ("c", 2),
      ("d", "Foo"),
      ("e", True),
      ]

    expected = [
      ("a", ""),
      ("b", 1),
      ("c", 2),
      ("d", "Foo"),
      ("e", 1),
      ]

    self.assertEqualValues(self.client._EncodeQuery(query),
                           expected)

    # invalid types
    for i in [[1, 2, 3], {"moo": "boo"}, (1, 2, 3)]:
      self.assertRaises(ValueError, self.client._EncodeQuery, [("x", i)])

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  def testCurlSettings(self):
    self.rapi.AddResponse("2")
    self.assertEqual(2, self.client.GetVersion())
    self.assertHandler(rlib2.R_version)

    # Signals should be disabled by default
    self.assert_(self.curl.getopt(pycurl.NOSIGNAL))

    # No auth and no proxy
    self.assertFalse(self.curl.getopt(pycurl.USERPWD))
    self.assert_(self.curl.getopt(pycurl.PROXY) is None)

    # Content-type is required for requests
    headers = self.curl.getopt(pycurl.HTTPHEADER)
    self.assert_("Content-type: application/json" in headers)

413 414 415 416 417 418 419 420 421
  def testHttpError(self):
    self.rapi.AddResponse(None, code=404)
    try:
      self.client.GetJobStatus(15140)
    except client.GanetiApiError, err:
      self.assertEqual(err.code, 404)
    else:
      self.fail("Didn't raise exception")

David Knowles's avatar
David Knowles committed
422 423 424 425 426
  def testGetVersion(self):
    self.rapi.AddResponse("2")
    self.assertEqual(2, self.client.GetVersion())
    self.assertHandler(rlib2.R_version)

427 428 429 430 431 432
  def testGetFeatures(self):
    for features in [[], ["foo", "bar", "baz"]]:
      self.rapi.AddResponse(serializer.DumpJson(features))
      self.assertEqual(features, self.client.GetFeatures())
      self.assertHandler(rlib2.R_2_features)

433 434 435 436
  def testGetFeaturesNotFound(self):
    self.rapi.AddResponse(None, code=404)
    self.assertEqual([], self.client.GetFeatures())

David Knowles's avatar
David Knowles committed
437 438 439 440 441 442 443 444 445 446 447
  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):
448 449 450
    self.rapi.AddResponse("1234")
    self.assertEqual(1234,
        self.client.AddClusterTags(["awesome"], dry_run=True))
David Knowles's avatar
David Knowles committed
451 452 453 454 455
    self.assertHandler(rlib2.R_2_tags)
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])

  def testDeleteClusterTags(self):
456 457 458
    self.rapi.AddResponse("5107")
    self.assertEqual(5107, self.client.DeleteClusterTags(["awesome"],
                                                         dry_run=True))
David Knowles's avatar
David Knowles committed
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
    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()

474
  def testGetInstance(self):
David Knowles's avatar
David Knowles committed
475
    self.rapi.AddResponse("[]")
476
    self.assertEqual([], self.client.GetInstance("instance"))
David Knowles's avatar
David Knowles committed
477 478 479
    self.assertHandler(rlib2.R_2_instances_name)
    self.assertItems(["instance"])

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
  def testGetInstanceInfo(self):
    self.rapi.AddResponse("21291")
    self.assertEqual(21291, self.client.GetInstanceInfo("inst3"))
    self.assertHandler(rlib2.R_2_instances_name_info)
    self.assertItems(["inst3"])
    self.assertQuery("static", None)

    self.rapi.AddResponse("3428")
    self.assertEqual(3428, self.client.GetInstanceInfo("inst31", static=False))
    self.assertHandler(rlib2.R_2_instances_name_info)
    self.assertItems(["inst31"])
    self.assertQuery("static", ["0"])

    self.rapi.AddResponse("15665")
    self.assertEqual(15665, self.client.GetInstanceInfo("inst32", static=True))
    self.assertHandler(rlib2.R_2_instances_name_info)
    self.assertItems(["inst32"])
    self.assertQuery("static", ["1"])

499
  def testCreateInstanceOldVersion(self):
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 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
    # No NICs
    self.rapi.AddResponse(None, code=404)
    self.assertRaises(client.GanetiApiError, self.client.CreateInstance,
                      "create", "inst1.example.com", "plain", [], [])
    self.assertEqual(self.rapi.CountPending(), 0)

    # More than one NIC
    self.rapi.AddResponse(None, code=404)
    self.assertRaises(client.GanetiApiError, self.client.CreateInstance,
                      "create", "inst1.example.com", "plain", [],
                      [{}, {}, {}])
    self.assertEqual(self.rapi.CountPending(), 0)

    # Unsupported NIC fields
    self.rapi.AddResponse(None, code=404)
    self.assertRaises(client.GanetiApiError, self.client.CreateInstance,
                      "create", "inst1.example.com", "plain", [],
                      [{"x": True, "y": False}])
    self.assertEqual(self.rapi.CountPending(), 0)

    # Unsupported disk fields
    self.rapi.AddResponse(None, code=404)
    self.assertRaises(client.GanetiApiError, self.client.CreateInstance,
                      "create", "inst1.example.com", "plain",
                      [{}, {"moo": "foo",}], [{}])
    self.assertEqual(self.rapi.CountPending(), 0)

    # Unsupported fields
    self.rapi.AddResponse(None, code=404)
    self.assertRaises(client.GanetiApiError, self.client.CreateInstance,
                      "create", "inst1.example.com", "plain", [], [{}],
                      hello_world=123)
    self.assertEqual(self.rapi.CountPending(), 0)

    self.rapi.AddResponse(None, code=404)
    self.assertRaises(client.GanetiApiError, self.client.CreateInstance,
                      "create", "inst1.example.com", "plain", [], [{}],
                      memory=128)
    self.assertEqual(self.rapi.CountPending(), 0)

    # Normal creation
    testnics = [
      [{}],
      [{ "mac": constants.VALUE_AUTO, }],
      [{ "ip": "192.0.2.99", "mode": constants.NIC_MODE_ROUTED, }],
      ]

    testdisks = [
      [],
      [{ "size": 128, }],
      [{ "size": 321, }, { "size": 4096, }],
      ]

    for idx, nics in enumerate(testnics):
      for disks in testdisks:
        beparams = {
          constants.BE_MEMORY: 512,
          constants.BE_AUTO_BALANCE: False,
          }
        hvparams = {
          constants.HV_MIGRATION_PORT: 9876,
          constants.HV_VNC_TLS: True,
          }

        self.rapi.AddResponse(None, code=404)
        self.rapi.AddResponse(serializer.DumpJson(3122617 + idx))
        job_id = self.client.CreateInstance("create", "inst1.example.com",
                                            "plain", disks, nics,
                                            pnode="node99", dry_run=True,
                                            hvparams=hvparams,
                                            beparams=beparams)
        self.assertEqual(job_id, 3122617 + idx)
        self.assertHandler(rlib2.R_2_instances)
        self.assertDryRun()
        self.assertEqual(self.rapi.CountPending(), 0)

576
        data = serializer.LoadJson(self.rapi.GetLastRequestData())
577 578 579 580 581 582 583 584
        self.assertEqual(data["name"], "inst1.example.com")
        self.assertEqual(data["disk_template"], "plain")
        self.assertEqual(data["pnode"], "node99")
        self.assertEqual(data[constants.BE_MEMORY], 512)
        self.assertEqual(data[constants.BE_AUTO_BALANCE], False)
        self.assertEqual(data[constants.HV_MIGRATION_PORT], 9876)
        self.assertEqual(data[constants.HV_VNC_TLS], True)
        self.assertEqual(data["disks"], [disk["size"] for disk in disks])
585

David Knowles's avatar
David Knowles committed
586
  def testCreateInstance(self):
587 588 589 590 591
    self.rapi.AddResponse(serializer.DumpJson([rlib2._INST_CREATE_REQV1]))
    self.rapi.AddResponse("23030")
    job_id = self.client.CreateInstance("create", "inst1.example.com",
                                        "plain", [], [], dry_run=True)
    self.assertEqual(job_id, 23030)
David Knowles's avatar
David Knowles committed
592 593 594
    self.assertHandler(rlib2.R_2_instances)
    self.assertDryRun()

595
    data = serializer.LoadJson(self.rapi.GetLastRequestData())
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614

    for field in ["dry_run", "beparams", "hvparams", "start"]:
      self.assertFalse(field in data)

    self.assertEqual(data["name"], "inst1.example.com")
    self.assertEqual(data["disk_template"], "plain")

  def testCreateInstance2(self):
    self.rapi.AddResponse(serializer.DumpJson([rlib2._INST_CREATE_REQV1]))
    self.rapi.AddResponse("24740")
    job_id = self.client.CreateInstance("import", "inst2.example.com",
                                        "drbd8", [{"size": 100,}],
                                        [{}, {"bridge": "br1", }],
                                        dry_run=False, start=True,
                                        pnode="node1", snode="node9",
                                        ip_check=False)
    self.assertEqual(job_id, 24740)
    self.assertHandler(rlib2.R_2_instances)

615
    data = serializer.LoadJson(self.rapi.GetLastRequestData())
616 617 618 619 620 621 622 623
    self.assertEqual(data[rlib2._REQ_DATA_VERSION], 1)
    self.assertEqual(data["name"], "inst2.example.com")
    self.assertEqual(data["disk_template"], "drbd8")
    self.assertEqual(data["start"], True)
    self.assertEqual(data["ip_check"], False)
    self.assertEqualValues(data["disks"], [{"size": 100,}])
    self.assertEqualValues(data["nics"], [{}, {"bridge": "br1", }])

David Knowles's avatar
David Knowles committed
624
  def testDeleteInstance(self):
625 626
    self.rapi.AddResponse("1234")
    self.assertEqual(1234, self.client.DeleteInstance("instance", dry_run=True))
David Knowles's avatar
David Knowles committed
627 628 629 630 631 632 633 634 635 636 637
    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):
638 639 640
    self.rapi.AddResponse("1234")
    self.assertEqual(1234,
        self.client.AddInstanceTags("fooinstance", ["awesome"], dry_run=True))
David Knowles's avatar
David Knowles committed
641 642 643 644 645 646
    self.assertHandler(rlib2.R_2_instances_name_tags)
    self.assertItems(["fooinstance"])
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])

  def testDeleteInstanceTags(self):
647 648 649
    self.rapi.AddResponse("25826")
    self.assertEqual(25826, self.client.DeleteInstanceTags("foo", ["awesome"],
                                                           dry_run=True))
David Knowles's avatar
David Knowles committed
650 651 652 653 654 655
    self.assertHandler(rlib2.R_2_instances_name_tags)
    self.assertItems(["foo"])
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])

  def testRebootInstance(self):
656 657 658 659
    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
660 661 662 663
    self.assertHandler(rlib2.R_2_instances_name_reboot)
    self.assertItems(["i-bar"])
    self.assertDryRun()
    self.assertQuery("type", ["hard"])
664
    self.assertQuery("ignore_secondaries", ["1"])
David Knowles's avatar
David Knowles committed
665 666

  def testShutdownInstance(self):
667 668 669
    self.rapi.AddResponse("1487")
    self.assertEqual(1487, self.client.ShutdownInstance("foo-instance",
                                                        dry_run=True))
David Knowles's avatar
David Knowles committed
670 671 672 673 674
    self.assertHandler(rlib2.R_2_instances_name_shutdown)
    self.assertItems(["foo-instance"])
    self.assertDryRun()

  def testStartupInstance(self):
675 676 677
    self.rapi.AddResponse("27149")
    self.assertEqual(27149, self.client.StartupInstance("bar-instance",
                                                        dry_run=True))
David Knowles's avatar
David Knowles committed
678 679 680 681 682
    self.assertHandler(rlib2.R_2_instances_name_startup)
    self.assertItems(["bar-instance"])
    self.assertDryRun()

  def testReinstallInstance(self):
683
    self.rapi.AddResponse(serializer.DumpJson([]))
684
    self.rapi.AddResponse("19119")
685 686
    self.assertEqual(19119, self.client.ReinstallInstance("baz-instance",
                                                          os="DOS",
687
                                                          no_startup=True))
David Knowles's avatar
David Knowles committed
688 689 690 691
    self.assertHandler(rlib2.R_2_instances_name_reinstall)
    self.assertItems(["baz-instance"])
    self.assertQuery("os", ["DOS"])
    self.assertQuery("nostartup", ["1"])
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
    self.assertEqual(self.rapi.CountPending(), 0)

  def testReinstallInstanceNew(self):
    self.rapi.AddResponse(serializer.DumpJson([rlib2._INST_REINSTALL_REQV1]))
    self.rapi.AddResponse("25689")
    self.assertEqual(25689, self.client.ReinstallInstance("moo-instance",
                                                          os="Debian",
                                                          no_startup=True))
    self.assertHandler(rlib2.R_2_instances_name_reinstall)
    self.assertItems(["moo-instance"])
    data = serializer.LoadJson(self.rapi.GetLastRequestData())
    self.assertEqual(len(data), 2)
    self.assertEqual(data["os"], "Debian")
    self.assertEqual(data["start"], False)
    self.assertEqual(self.rapi.CountPending(), 0)

  def testReinstallInstanceWithOsparams1(self):
    self.rapi.AddResponse(serializer.DumpJson([]))
    self.assertRaises(client.GanetiApiError, self.client.ReinstallInstance,
                      "doo-instance", osparams={"x": "y"})
    self.assertEqual(self.rapi.CountPending(), 0)

  def testReinstallInstanceWithOsparams2(self):
    osparams = {
      "Hello": "World",
      "foo": "bar",
      }
    self.rapi.AddResponse(serializer.DumpJson([rlib2._INST_REINSTALL_REQV1]))
    self.rapi.AddResponse("1717")
    self.assertEqual(1717, self.client.ReinstallInstance("zoo-instance",
                                                         osparams=osparams))
    self.assertHandler(rlib2.R_2_instances_name_reinstall)
    self.assertItems(["zoo-instance"])
    data = serializer.LoadJson(self.rapi.GetLastRequestData())
    self.assertEqual(len(data), 2)
    self.assertEqual(data["osparams"], osparams)
    self.assertEqual(data["start"], True)
    self.assertEqual(self.rapi.CountPending(), 0)
David Knowles's avatar
David Knowles committed
730 731 732 733

  def testReplaceInstanceDisks(self):
    self.rapi.AddResponse("999")
    job_id = self.client.ReplaceInstanceDisks("instance-name",
734
        disks=[0, 1], dry_run=True, iallocator="hail")
David Knowles's avatar
David Knowles committed
735 736 737
    self.assertEqual(999, job_id)
    self.assertHandler(rlib2.R_2_instances_name_replace_disks)
    self.assertItems(["instance-name"])
738
    self.assertQuery("disks", ["0,1"])
David Knowles's avatar
David Knowles committed
739 740 741 742 743 744
    self.assertQuery("mode", ["replace_auto"])
    self.assertQuery("iallocator", ["hail"])
    self.assertDryRun()

    self.rapi.AddResponse("1000")
    job_id = self.client.ReplaceInstanceDisks("instance-bar",
745
        disks=[1], mode="replace_on_secondary", remote_node="foo-node",
David Knowles's avatar
David Knowles committed
746 747 748
        dry_run=True)
    self.assertEqual(1000, job_id)
    self.assertItems(["instance-bar"])
749
    self.assertQuery("disks", ["1"])
David Knowles's avatar
David Knowles committed
750 751 752
    self.assertQuery("remote_node", ["foo-node"])
    self.assertDryRun()

753 754 755 756 757
    self.rapi.AddResponse("5175")
    self.assertEqual(5175, self.client.ReplaceInstanceDisks("instance-moo"))
    self.assertItems(["instance-moo"])
    self.assertQuery("disks", None)

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
  def testPrepareExport(self):
    self.rapi.AddResponse("8326")
    self.assertEqual(8326, self.client.PrepareExport("inst1", "local"))
    self.assertHandler(rlib2.R_2_instances_name_prepare_export)
    self.assertItems(["inst1"])
    self.assertQuery("mode", ["local"])

  def testExportInstance(self):
    self.rapi.AddResponse("19695")
    job_id = self.client.ExportInstance("inst2", "local", "nodeX",
                                        shutdown=True)
    self.assertEqual(job_id, 19695)
    self.assertHandler(rlib2.R_2_instances_name_export)
    self.assertItems(["inst2"])

773
    data = serializer.LoadJson(self.rapi.GetLastRequestData())
774 775 776 777
    self.assertEqual(data["mode"], "local")
    self.assertEqual(data["destination"], "nodeX")
    self.assertEqual(data["shutdown"], True)

778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
  def testMigrateInstanceDefaults(self):
    self.rapi.AddResponse("24873")
    job_id = self.client.MigrateInstance("inst91")
    self.assertEqual(job_id, 24873)
    self.assertHandler(rlib2.R_2_instances_name_migrate)
    self.assertItems(["inst91"])

    data = serializer.LoadJson(self.rapi.GetLastRequestData())
    self.assertFalse(data)

  def testMigrateInstance(self):
    for mode in constants.HT_MIGRATION_MODES:
      for cleanup in [False, True]:
        self.rapi.AddResponse("31910")
        job_id = self.client.MigrateInstance("inst289", mode=mode,
                                             cleanup=cleanup)
        self.assertEqual(job_id, 31910)
        self.assertHandler(rlib2.R_2_instances_name_migrate)
        self.assertItems(["inst289"])

        data = serializer.LoadJson(self.rapi.GetLastRequestData())
        self.assertEqual(len(data), 2)
        self.assertEqual(data["mode"], mode)
        self.assertEqual(data["cleanup"], cleanup)

803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
  def testRenameInstanceDefaults(self):
    new_name = "newnametha7euqu"
    self.rapi.AddResponse("8791")
    job_id = self.client.RenameInstance("inst18821", new_name)
    self.assertEqual(job_id, 8791)
    self.assertHandler(rlib2.R_2_instances_name_rename)
    self.assertItems(["inst18821"])

    data = serializer.LoadJson(self.rapi.GetLastRequestData())
    self.assertEqualValues(data, {"new_name": new_name, })

  def testRenameInstance(self):
    new_name = "new-name-yiux1iin"
    for ip_check in [False, True]:
      for name_check in [False, True]:
        self.rapi.AddResponse("24776")
        job_id = self.client.RenameInstance("inst20967", new_name,
                                             ip_check=ip_check,
                                             name_check=name_check)
        self.assertEqual(job_id, 24776)
        self.assertHandler(rlib2.R_2_instances_name_rename)
        self.assertItems(["inst20967"])

        data = serializer.LoadJson(self.rapi.GetLastRequestData())
        self.assertEqual(len(data), 3)
        self.assertEqual(data["new_name"], new_name)
        self.assertEqual(data["ip_check"], ip_check)
        self.assertEqual(data["name_check"], name_check)

David Knowles's avatar
David Knowles committed
832
  def testGetJobs(self):
833 834
    self.rapi.AddResponse('[ { "id": "123", "uri": "\\/2\\/jobs\\/123" },'
                          '  { "id": "124", "uri": "\\/2\\/jobs\\/124" } ]')
David Knowles's avatar
David Knowles committed
835 836 837 838 839 840 841 842 843
    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"])

844 845 846 847 848 849 850 851 852 853 854 855 856
  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"])

857
  def testCancelJob(self):
858 859
    self.rapi.AddResponse("[true, \"Job 123 will be canceled\"]")
    self.assertEqual([True, "Job 123 will be canceled"],
860
                     self.client.CancelJob(999, dry_run=True))
David Knowles's avatar
David Knowles committed
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
    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()

879
  def testGetNode(self):
David Knowles's avatar
David Knowles committed
880
    self.rapi.AddResponse("{}")
881
    self.assertEqual({}, self.client.GetNode("node-foo"))
David Knowles's avatar
David Knowles committed
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
    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"])
909 910 911 912 913 914 915 916 917
    self.assert_("mode" not in self.rapi.GetLastHandler().queryargs)
    self.assertDryRun()

    self.rapi.AddResponse("1112")
    self.assertEqual(1112, self.client.MigrateNode("node-a", dry_run=True,
                                                   mode="live"))
    self.assertHandler(rlib2.R_2_nodes_name_migrate)
    self.assertItems(["node-a"])
    self.assertQuery("mode", ["live"])
David Knowles's avatar
David Knowles committed
918 919 920 921 922 923 924 925 926 927 928 929 930 931
    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"])
932
    self.assertQuery("force", ["1"])
933
    self.assertEqual("\"master-candidate\"", self.rapi.GetLastRequestData())
David Knowles's avatar
David Knowles committed
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951

  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"])

  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"])
952 953 954 955 956 957 958 959 960 961 962 963
    self.assertQuery("allocatable", None)

    for allocatable, query_allocatable in [(True, "1"), (False, "0")]:
      self.rapi.AddResponse("7205")
      job_id = self.client.ModifyNodeStorageUnits("node-z", "lvm-pv", "hda",
                                                  allocatable=allocatable)
      self.assertEqual(7205, job_id)
      self.assertHandler(rlib2.R_2_nodes_name_storage_modify)
      self.assertItems(["node-z"])
      self.assertQuery("storage_type", ["lvm-pv"])
      self.assertQuery("name", ["hda"])
      self.assertQuery("allocatable", [query_allocatable])
David Knowles's avatar
David Knowles committed
964

965 966 967 968 969 970 971 972 973
  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"])

David Knowles's avatar
David Knowles committed
974 975 976 977 978 979 980
  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):
981 982 983
    self.rapi.AddResponse("1234")
    self.assertEqual(1234,
        self.client.AddNodeTags("node-v", ["awesome"], dry_run=True))
David Knowles's avatar
David Knowles committed
984 985 986 987 988 989
    self.assertHandler(rlib2.R_2_nodes_name_tags)
    self.assertItems(["node-v"])
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])

  def testDeleteNodeTags(self):
990 991 992
    self.rapi.AddResponse("16861")
    self.assertEqual(16861, self.client.DeleteNodeTags("node-w", ["awesome"],
                                                       dry_run=True))
David Knowles's avatar
David Knowles committed
993 994 995 996 997
    self.assertHandler(rlib2.R_2_nodes_name_tags)
    self.assertItems(["node-w"])
    self.assertDryRun()
    self.assertQuery("tag", ["awesome"])

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
  def testGetGroups(self):
    groups = [{"name": "group1",
               "uri": "/2/groups/group1",
               },
              {"name": "group2",
               "uri": "/2/groups/group2",
               },
              ]
    self.rapi.AddResponse(serializer.DumpJson(groups))
    self.assertEqual(["group1", "group2"], self.client.GetGroups())
    self.assertHandler(rlib2.R_2_groups)

  def testGetGroupsBulk(self):
    groups = [{"name": "group1",
               "uri": "/2/groups/group1",
               "node_cnt": 2,
               "node_list": ["gnt1.test",
                             "gnt2.test",
                             ],
               },
              {"name": "group2",
               "uri": "/2/groups/group2",
               "node_cnt": 1,
               "node_list": ["gnt3.test",
                             ],
               },
              ]
    self.rapi.AddResponse(serializer.DumpJson(groups))

    self.assertEqual(groups, self.client.GetGroups(bulk=True))
    self.assertHandler(rlib2.R_2_groups)
    self.assertBulk()

  def testGetGroup(self):
    group = {"ctime": None,
             "name": "default",
             }
    self.rapi.AddResponse(serializer.DumpJson(group))
    self.assertEqual({"ctime": None, "name": "default"},
                     self.client.GetGroup("default"))
    self.assertHandler(rlib2.R_2_groups_name)
    self.assertItems(["default"])

  def testCreateGroup(self):
    self.rapi.AddResponse("12345")
    job_id = self.client.CreateGroup("newgroup", dry_run=True)
    self.assertEqual(job_id, 12345)
    self.assertHandler(rlib2.R_2_groups)
    self.assertDryRun()

  def testDeleteGroup(self):
    self.rapi.AddResponse("12346")
    job_id = self.client.DeleteGroup("newgroup", dry_run=True)
    self.assertEqual(job_id, 12346)
    self.assertHandler(rlib2.R_2_groups_name)
    self.assertDryRun()

  def testRenameGroup(self):
    self.rapi.AddResponse("12347")
    job_id = self.client.RenameGroup("oldname", "newname")
    self.assertEqual(job_id, 12347)
    self.assertHandler(rlib2.R_2_groups_name_rename)

1061 1062 1063 1064 1065 1066
  def testModifyGroup(self):
    self.rapi.AddResponse("12348")
    job_id = self.client.ModifyGroup("mygroup", alloc_policy="foo")
    self.assertEqual(job_id, 12348)
    self.assertHandler(rlib2.R_2_groups_name_modify)

1067 1068 1069 1070 1071 1072 1073 1074 1075
  def testAssignGroupNodes(self):
    self.rapi.AddResponse("12349")
    job_id = self.client.AssignGroupNodes("mygroup", ["node1", "node2"],
                                          force=True, dry_run=True)
    self.assertEqual(job_id, 12349)
    self.assertHandler(rlib2.R_2_groups_name_assign_nodes)
    self.assertDryRun()
    self.assertUseForce()

1076 1077 1078 1079 1080 1081 1082 1083 1084
  def testModifyInstance(self):
    self.rapi.AddResponse("23681")
    job_id = self.client.ModifyInstance("inst7210", os_name="linux")
    self.assertEqual(job_id, 23681)
    self.assertItems(["inst7210"])
    self.assertHandler(rlib2.R_2_instances_name_modify)
    self.assertEqual(serializer.LoadJson(self.rapi.GetLastRequestData()),
                     { "os_name": "linux", })

1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
  def testModifyCluster(self):
    for mnh in [None, False, True]:
      self.rapi.AddResponse("14470")
      self.assertEqual(14470,
        self.client.ModifyCluster(maintain_node_health=mnh))
      self.assertHandler(rlib2.R_2_cluster_modify)
      self.assertItems([])
      data = serializer.LoadJson(self.rapi.GetLastRequestData())
      self.assertEqual(len(data), 1)
      self.assertEqual(data["maintain_node_health"], mnh)
      self.assertEqual(self.rapi.CountPending(), 0)

1097 1098 1099 1100 1101 1102 1103
  def testRedistributeConfig(self):
    self.rapi.AddResponse("3364")
    job_id = self.client.RedistributeConfig()
    self.assertEqual(job_id, 3364)
    self.assertItems([])
    self.assertHandler(rlib2.R_2_redist_config)

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
  def testActivateInstanceDisks(self):
    self.rapi.AddResponse("23547")
    job_id = self.client.ActivateInstanceDisks("inst28204")
    self.assertEqual(job_id, 23547)
    self.assertItems(["inst28204"])
    self.assertHandler(rlib2.R_2_instances_name_activate_disks)
    self.assertFalse(self.rapi.GetLastHandler().queryargs)

  def testActivateInstanceDisksIgnoreSize(self):
    self.rapi.AddResponse("11044")
    job_id = self.client.ActivateInstanceDisks("inst28204", ignore_size=True)
    self.assertEqual(job_id, 11044)
    self.assertItems(["inst28204"])
    self.assertHandler(rlib2.R_2_instances_name_activate_disks)
    self.assertQuery("ignore_size", ["1"])

  def testDeactivateInstanceDisks(self):
    self.rapi.AddResponse("14591")
    job_id = self.client.DeactivateInstanceDisks("inst28234")
    self.assertEqual(job_id, 14591)
    self.assertItems(["inst28234"])
    self.assertHandler(rlib2.R_2_instances_name_deactivate_disks)
    self.assertFalse(self.rapi.GetLastHandler().queryargs)

1128 1129 1130 1131 1132 1133 1134 1135 1136
  def testGetInstanceConsole(self):
    self.rapi.AddResponse("26876")
    job_id = self.client.GetInstanceConsole("inst21491")
    self.assertEqual(job_id, 26876)
    self.assertItems(["inst21491"])
    self.assertHandler(rlib2.R_2_instances_name_console)
    self.assertFalse(self.rapi.GetLastHandler().queryargs)
    self.assertFalse(self.rapi.GetLastRequestData())

1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
  def testGrowInstanceDisk(self):
    for idx, wait_for_sync in enumerate([None, False, True]):
      amount = 128 + (512 * idx)
      self.assertEqual(self.rapi.CountPending(), 0)
      self.rapi.AddResponse("30783")
      self.assertEqual(30783,
        self.client.GrowInstanceDisk("eze8ch", idx, amount,
                                     wait_for_sync=wait_for_sync))
      self.assertHandler(rlib2.R_2_instances_name_disk_grow)
      self.assertItems(["eze8ch", str(idx)])
      data = serializer.LoadJson(self.rapi.GetLastRequestData())
      if wait_for_sync is None:
        self.assertEqual(len(data), 1)
        self.assert_("wait_for_sync" not in data)
      else:
        self.assertEqual(len(data), 2)
        self.assertEqual(data["wait_for_sync"], wait_for_sync)
      self.assertEqual(data["amount"], amount)
      self.assertEqual(self.rapi.CountPending(), 0)

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 1202 1203 1204 1205
  def testQuery(self):
    for idx, what in enumerate(constants.QR_VIA_RAPI):
      for idx2, filter_ in enumerate([None, ["?", "name"]]):
        job_id = 11010 + (idx << 4) + (idx2 << 16)
        fields = sorted(query.ALL_FIELDS[what].keys())[:10]

        self.rapi.AddResponse(str(job_id))
        self.assertEqual(self.client.Query(what, fields, filter_=filter_),
                         job_id)
        self.assertItems([what])
        self.assertHandler(rlib2.R_2_query)
        self.assertFalse(self.rapi.GetLastHandler().queryargs)
        data = serializer.LoadJson(self.rapi.GetLastRequestData())
        self.assertEqual(data["fields"], fields)
        if filter_ is None:
          self.assertTrue("filter" not in data)
        else:
          self.assertEqual(data["filter"], filter_)
        self.assertEqual(self.rapi.CountPending(), 0)

  def testQueryFields(self):
    exp_result = objects.QueryFieldsResponse(fields=[
      objects.QueryFieldDefinition(name="pnode", title="PNode",
                                   kind=constants.QFT_NUMBER),
      objects.QueryFieldDefinition(name="other", title="Other",
                                   kind=constants.QFT_BOOL),
      ])

    for what in constants.QR_VIA_RAPI:
      for fields in [None, ["name", "_unknown_"], ["&", "?|"]]:
        self.rapi.AddResponse(serializer.DumpJson(exp_result.ToDict()))
        result = self.client.QueryFields(what, fields=fields)
        self.assertItems([what])
        self.assertHandler(rlib2.R_2_query_fields)
        self.assertFalse(self.rapi.GetLastRequestData())

        queryargs = self.rapi.GetLastHandler().queryargs
        if fields is None:
          self.assertFalse(queryargs)
        else:
          self.assertEqual(queryargs, {
            "fields": [",".join(fields)],
            })

        self.assertEqual(objects.QueryFieldsResponse.FromDict(result).ToDict(),
                         exp_result.ToDict())

        self.assertEqual(self.rapi.CountPending(), 0)

David Knowles's avatar
David Knowles committed
1206

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
class RapiTestRunner(unittest.TextTestRunner):
  def run(self, *args):
    global _used_handlers
    assert _used_handlers is None

    _used_handlers = set()
    try:
      # Run actual tests
      result = unittest.TextTestRunner.run(self, *args)

      diff = (set(connector.CONNECTOR.values()) - _used_handlers -
             _KNOWN_UNUSED)
      if diff:
        raise AssertionError("The following RAPI resources were not used by the"
                             " RAPI client: %r" % utils.CommaJoin(diff))
    finally:
      # Reset global variable
      _used_handlers = None

    return result


David Knowles's avatar
David Knowles committed
1229
if __name__ == '__main__':
1230
  client.UsesRapiClient(testutils.GanetiTestProgram)(testRunner=RapiTestRunner)