qa_rapi.py 19.7 KB
Newer Older
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
1
2
#

Iustin Pop's avatar
Iustin Pop committed
3
# Copyright (C) 2007, 2008, 2009, 2010, 2011 Google Inc.
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#
# 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.


"""Remote API QA tests.

"""

Michael Hanselmann's avatar
Michael Hanselmann committed
25
import tempfile
26
import random
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
27
28
29
30

from ganeti import utils
from ganeti import constants
from ganeti import errors
Michael Hanselmann's avatar
Michael Hanselmann committed
31
32
from ganeti import cli
from ganeti import rapi
33
from ganeti import objects
34
35
36
from ganeti import query
from ganeti import compat
from ganeti import qlang
Michael Hanselmann's avatar
Michael Hanselmann committed
37

38
import ganeti.rapi.client        # pylint: disable=W0611
Michael Hanselmann's avatar
Michael Hanselmann committed
39
import ganeti.rapi.client_utils
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
40
41
42
43
44

import qa_config
import qa_utils
import qa_error

Iustin Pop's avatar
Iustin Pop committed
45
from qa_utils import (AssertEqual, AssertIn, AssertMatch, StartLocalCommand)
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
46
47


Michael Hanselmann's avatar
Michael Hanselmann committed
48
49
_rapi_ca = None
_rapi_client = None
50
51
_rapi_username = None
_rapi_password = None
52
53


Michael Hanselmann's avatar
Michael Hanselmann committed
54
55
def Setup(username, password):
  """Configures the RAPI client.
56

Michael Hanselmann's avatar
Michael Hanselmann committed
57
  """
58
  # pylint: disable=W0603
Iustin Pop's avatar
Iustin Pop committed
59
  # due to global usage
Michael Hanselmann's avatar
Michael Hanselmann committed
60
61
  global _rapi_ca
  global _rapi_client
62
63
64
65
66
  global _rapi_username
  global _rapi_password

  _rapi_username = username
  _rapi_password = password
67

Michael Hanselmann's avatar
Michael Hanselmann committed
68
  master = qa_config.GetMasterNode()
69

Michael Hanselmann's avatar
Michael Hanselmann committed
70
71
  # Load RAPI certificate from master node
  cmd = ["cat", constants.RAPI_CERT_FILE]
72

Michael Hanselmann's avatar
Michael Hanselmann committed
73
74
75
76
77
  # Write to temporary file
  _rapi_ca = tempfile.NamedTemporaryFile()
  _rapi_ca.write(qa_utils.GetCommandOutput(master["primary"],
                                           utils.ShellQuoteArgs(cmd)))
  _rapi_ca.flush()
78

Michael Hanselmann's avatar
Michael Hanselmann committed
79
  port = qa_config.get("rapi-port", default=constants.DEFAULT_RAPI_PORT)
80
81
  cfg_curl = rapi.client.GenericCurlConfig(cafile=_rapi_ca.name,
                                           proxy="")
82

Michael Hanselmann's avatar
Michael Hanselmann committed
83
84
85
  _rapi_client = rapi.client.GanetiRapiClient(master["primary"], port=port,
                                              username=username,
                                              password=password,
86
                                              curl_config_fn=cfg_curl)
87

Michael Hanselmann's avatar
Michael Hanselmann committed
88
  print "RAPI protocol version: %s" % _rapi_client.GetVersion()
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
89
90
91


INSTANCE_FIELDS = ("name", "os", "pnode", "snodes",
92
93
                   "admin_state",
                   "disk_template", "disk.sizes",
94
                   "nic.ips", "nic.macs", "nic.modes", "nic.links",
95
                   "beparams", "hvparams",
96
                   "oper_state", "oper_ram", "oper_vcpus", "status", "tags")
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
97
98
99
100
101

NODE_FIELDS = ("name", "dtotal", "dfree",
               "mtotal", "mnode", "mfree",
               "pinst_cnt", "sinst_cnt", "tags")

102
103
GROUP_FIELDS = frozenset([
  "name", "uuid",
104
  "alloc_policy",
105
106
107
  "node_cnt", "node_list",
  ])

108
109
110
111
112
113
JOB_FIELDS = frozenset([
  "id", "ops", "status", "summary",
  "opstatus", "opresult", "oplog",
  "received_ts", "start_ts", "end_ts",
  ])

Iustin Pop's avatar
Iustin Pop committed
114
LIST_FIELDS = ("id", "uri")
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
115
116
117
118
119
120


def Enabled():
  """Return whether remote API tests should be run.

  """
Iustin Pop's avatar
Iustin Pop committed
121
  return qa_config.TestEnabled("rapi")
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
122
123
124


def _DoTests(uris):
125
  # pylint: disable=W0212
Iustin Pop's avatar
Iustin Pop committed
126
  # due to _SendRequest usage
127
  results = []
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
128

129
  for uri, verify, method, body in uris:
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
130
131
    assert uri.startswith("/")

132
    print "%s %s" % (method, uri)
Michael Hanselmann's avatar
Michael Hanselmann committed
133
    data = _rapi_client._SendRequest(method, uri, None, body)
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
134
135
136
137
138
139
140

    if verify is not None:
      if callable(verify):
        verify(data)
      else:
        AssertEqual(data, verify)

141
    results.append(data)
142
143
144
145
146

  return results


def _VerifyReturnsJob(data):
Iustin Pop's avatar
Iustin Pop committed
147
  AssertMatch(data, r"^\d+$")
148

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
149
150
151
152
153
154

def TestVersion():
  """Testing remote API version.

  """
  _DoTests([
Iustin Pop's avatar
Iustin Pop committed
155
    ("/version", constants.RAPI_VERSION, "GET", None),
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
156
157
158
159
160
161
162
    ])


def TestEmptyCluster():
  """Testing remote API on an empty cluster.

  """
163
164
  master = qa_config.GetMasterNode()
  master_full = qa_utils.ResolveNodeName(master)
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
165
166
167
168

  def _VerifyInfo(data):
    AssertIn("name", data)
    AssertIn("master", data)
169
    AssertEqual(data["master"], master_full)
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
170
171
172

  def _VerifyNodes(data):
    master_entry = {
173
174
      "id": master_full,
      "uri": "/2/nodes/%s" % master_full,
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
175
176
177
178
179
180
181
182
      }
    AssertIn(master_entry, data)

  def _VerifyNodesBulk(data):
    for node in data:
      for entry in NODE_FIELDS:
        AssertIn(entry, node)

183
184
  def _VerifyGroups(data):
    default_group = {
185
186
      "name": constants.INITIAL_NODE_GROUP_NAME,
      "uri": "/2/groups/" + constants.INITIAL_NODE_GROUP_NAME,
187
188
189
190
191
192
193
194
      }
    AssertIn(default_group, data)

  def _VerifyGroupsBulk(data):
    for group in data:
      for field in GROUP_FIELDS:
        AssertIn(field, group)

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
195
  _DoTests([
Iustin Pop's avatar
Iustin Pop committed
196
197
198
199
200
201
202
203
204
205
    ("/", None, "GET", None),
    ("/2/info", _VerifyInfo, "GET", None),
    ("/2/tags", None, "GET", None),
    ("/2/nodes", _VerifyNodes, "GET", None),
    ("/2/nodes?bulk=1", _VerifyNodesBulk, "GET", None),
    ("/2/groups", _VerifyGroups, "GET", None),
    ("/2/groups?bulk=1", _VerifyGroupsBulk, "GET", None),
    ("/2/instances", [], "GET", None),
    ("/2/instances?bulk=1", [], "GET", None),
    ("/2/os", None, "GET", None),
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
206
207
    ])

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
  # Test HTTP Not Found
  for method in ["GET", "PUT", "POST", "DELETE"]:
    try:
      _DoTests([("/99/resource/not/here/99", None, method, None)])
    except rapi.client.GanetiApiError, err:
      AssertEqual(err.code, 404)
    else:
      raise qa_error.Error("Non-existent resource didn't return HTTP 404")

  # Test HTTP Not Implemented
  for method in ["PUT", "POST", "DELETE"]:
    try:
      _DoTests([("/version", None, method, None)])
    except rapi.client.GanetiApiError, err:
      AssertEqual(err.code, 501)
    else:
      raise qa_error.Error("Non-implemented method didn't fail")

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
226

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def TestRapiQuery():
  """Testing resource queries via remote API.

  """
  master_name = qa_utils.ResolveNodeName(qa_config.GetMasterNode())
  rnd = random.Random(7818)

  for what in constants.QR_VIA_RAPI:
    all_fields = query.ALL_FIELDS[what].keys()
    rnd.shuffle(all_fields)

    # No fields, should return everything
    result = _rapi_client.QueryFields(what)
    qresult = objects.QueryFieldsResponse.FromDict(result)
    AssertEqual(len(qresult.fields), len(all_fields))

    # One field
    result = _rapi_client.QueryFields(what, fields=["name"])
    qresult = objects.QueryFieldsResponse.FromDict(result)
    AssertEqual(len(qresult.fields), 1)

    # Specify all fields, order must be correct
    result = _rapi_client.QueryFields(what, fields=all_fields)
    qresult = objects.QueryFieldsResponse.FromDict(result)
    AssertEqual(len(qresult.fields), len(all_fields))
    AssertEqual([fdef.name for fdef in qresult.fields], all_fields)

    # Unknown field
    result = _rapi_client.QueryFields(what, fields=["_unknown!"])
    qresult = objects.QueryFieldsResponse.FromDict(result)
    AssertEqual(len(qresult.fields), 1)
    AssertEqual(qresult.fields[0].name, "_unknown!")
    AssertEqual(qresult.fields[0].kind, constants.QFT_UNKNOWN)

    # Try once more, this time without the client
    _DoTests([
      ("/2/query/%s/fields" % what, None, "GET", None),
      ("/2/query/%s/fields?fields=name,name,%s" % (what, all_fields[0]),
       None, "GET", None),
      ])

    # Try missing query argument
    try:
      _DoTests([
        ("/2/query/%s" % what, None, "GET", None),
        ])
    except rapi.client.GanetiApiError, err:
      AssertEqual(err.code, 400)
    else:
      raise qa_error.Error("Request missing 'fields' parameter didn't fail")

    def _Check(exp_fields, data):
      qresult = objects.QueryResponse.FromDict(data)
      AssertEqual([fdef.name for fdef in qresult.fields], exp_fields)
      if not isinstance(qresult.data, list):
        raise qa_error.Error("Query did not return a list")

    _DoTests([
      # Specify fields in query
      ("/2/query/%s?fields=%s" % (what, ",".join(all_fields)),
       compat.partial(_Check, all_fields), "GET", None),

      ("/2/query/%s?fields=name" % what,
       compat.partial(_Check, ["name"]), "GET", None),

      # Note the spaces
      ("/2/query/%s?fields=name,%%20name%%09,name%%20" % what,
       compat.partial(_Check, ["name"] * 3), "GET", None),

      # PUT with fields in query
      ("/2/query/%s?fields=name" % what,
       compat.partial(_Check, ["name"]), "PUT", {}),

      # Fields in body
      ("/2/query/%s" % what, compat.partial(_Check, all_fields), "PUT", {
         "fields": all_fields,
         }),

      ("/2/query/%s" % what, compat.partial(_Check, ["name"] * 4), "PUT", {
         "fields": ["name"] * 4,
         }),
      ])

    def _CheckFilter():
      _DoTests([
        # With filter
        ("/2/query/%s" % what, compat.partial(_Check, all_fields), "PUT", {
           "fields": all_fields,
           "filter": [qlang.OP_TRUE, "name"],
           }),
        ])

    if what == constants.QR_LOCK:
      # Locks can't be filtered
      try:
        _CheckFilter()
      except rapi.client.GanetiApiError, err:
        AssertEqual(err.code, 500)
      else:
        raise qa_error.Error("Filtering locks didn't fail")
    else:
      _CheckFilter()

    if what == constants.QR_NODE:
      # Test with filter
      (nodes, ) = _DoTests([("/2/query/%s" % what,
        compat.partial(_Check, ["name", "master"]), "PUT", {
        "fields": ["name", "master"],
        "filter": [qlang.OP_TRUE, "master"],
        })])
      qresult = objects.QueryResponse.FromDict(nodes)
      AssertEqual(qresult.data, [
        [[constants.RS_NORMAL, master_name], [constants.RS_NORMAL, True]],
        ])


Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
343
344
345
346
347
348
349
def TestInstance(instance):
  """Testing getting instance(s) info via remote API.

  """
  def _VerifyInstance(data):
    for entry in INSTANCE_FIELDS:
      AssertIn(entry, data)
350

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
351
352
  def _VerifyInstancesList(data):
    for instance in data:
353
      for entry in LIST_FIELDS:
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
354
        AssertIn(entry, instance)
355

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
356
357
358
359
360
  def _VerifyInstancesBulk(data):
    for instance_data in data:
      _VerifyInstance(instance_data)

  _DoTests([
Iustin Pop's avatar
Iustin Pop committed
361
362
363
    ("/2/instances/%s" % instance["name"], _VerifyInstance, "GET", None),
    ("/2/instances", _VerifyInstancesList, "GET", None),
    ("/2/instances?bulk=1", _VerifyInstancesBulk, "GET", None),
364
    ("/2/instances/%s/activate-disks" % instance["name"],
Iustin Pop's avatar
Iustin Pop committed
365
     _VerifyReturnsJob, "PUT", None),
366
    ("/2/instances/%s/deactivate-disks" % instance["name"],
Iustin Pop's avatar
Iustin Pop committed
367
     _VerifyReturnsJob, "PUT", None),
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
368
369
    ])

370
  # Test OpBackupPrepare
371
372
373
374
375
376
377
378
379
380
381
382
  (job_id, ) = _DoTests([
    ("/2/instances/%s/prepare-export?mode=%s" %
     (instance["name"], constants.EXPORT_MODE_REMOTE),
     _VerifyReturnsJob, "PUT", None),
    ])

  result = _WaitForRapiJob(job_id)[0]
  AssertEqual(len(result["handshake"]), 3)
  AssertEqual(result["handshake"][0], constants.RIE_VERSION)
  AssertEqual(len(result["x509_key_name"]), 3)
  AssertIn("-----BEGIN CERTIFICATE-----", result["x509_ca"])

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
383
384
385
386
387
388
389
390

def TestNode(node):
  """Testing getting node(s) info via remote API.

  """
  def _VerifyNode(data):
    for entry in NODE_FIELDS:
      AssertIn(entry, data)
391

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
392
393
  def _VerifyNodesList(data):
    for node in data:
394
      for entry in LIST_FIELDS:
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
395
        AssertIn(entry, node)
396

Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
397
398
399
400
401
  def _VerifyNodesBulk(data):
    for node_data in data:
      _VerifyNode(node_data)

  _DoTests([
Iustin Pop's avatar
Iustin Pop committed
402
403
404
    ("/2/nodes/%s" % node["primary"], _VerifyNode, "GET", None),
    ("/2/nodes", _VerifyNodesList, "GET", None),
    ("/2/nodes?bulk=1", _VerifyNodesBulk, "GET", None),
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
405
406
407
408
409
410
411
412
    ])


def TestTags(kind, name, tags):
  """Tests .../tags resources.

  """
  if kind == constants.TAG_CLUSTER:
413
    uri = "/2/tags"
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
414
  elif kind == constants.TAG_NODE:
415
    uri = "/2/nodes/%s/tags" % name
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
416
  elif kind == constants.TAG_INSTANCE:
417
    uri = "/2/instances/%s/tags" % name
418
419
  elif kind == constants.TAG_NODEGROUP:
    uri = "/2/groups/%s/tags" % name
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
420
421
422
423
  else:
    raise errors.ProgrammerError("Unknown tag kind")

  def _VerifyTags(data):
424
    AssertEqual(sorted(tags), sorted(data))
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
425

426
  queryargs = "&".join("tag=%s" % i for i in tags)
427
428
429

  # Add tags
  (job_id, ) = _DoTests([
430
    ("%s?%s" % (uri, queryargs), _VerifyReturnsJob, "PUT", None),
431
432
433
434
    ])
  _WaitForRapiJob(job_id)

  # Retrieve tags
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
435
  _DoTests([
Iustin Pop's avatar
Iustin Pop committed
436
    (uri, _VerifyTags, "GET", None),
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
437
    ])
438

439
440
  # Remove tags
  (job_id, ) = _DoTests([
441
    ("%s?%s" % (uri, queryargs), _VerifyReturnsJob, "DELETE", None),
442
443
444
    ])
  _WaitForRapiJob(job_id)

445
446
447
448
449
450
451
452
453
454
455
456
457
458

def _WaitForRapiJob(job_id):
  """Waits for a job to finish.

  """
  def _VerifyJob(data):
    AssertEqual(data["id"], job_id)
    for field in JOB_FIELDS:
      AssertIn(field, data)

  _DoTests([
    ("/2/jobs/%s" % job_id, _VerifyJob, "GET", None),
    ])

459
460
  return rapi.client_utils.PollJob(_rapi_client, job_id,
                                   cli.StdioJobPollReportCb())
461
462


463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
def TestRapiNodeGroups():
  """Test several node group operations using RAPI.

  """
  groups = qa_config.get("groups", {})
  group1, group2, group3 = groups.get("inexistent-groups",
                                      ["group1", "group2", "group3"])[:3]

  # Create a group with no attributes
  body = {
    "name": group1,
    }

  (job_id, ) = _DoTests([
    ("/2/groups", _VerifyReturnsJob, "POST", body),
    ])

  _WaitForRapiJob(job_id)

  # Create a group specifying alloc_policy
  body = {
    "name": group2,
    "alloc_policy": constants.ALLOC_POLICY_UNALLOCABLE,
    }

  (job_id, ) = _DoTests([
    ("/2/groups", _VerifyReturnsJob, "POST", body),
    ])

  _WaitForRapiJob(job_id)

  # Modify alloc_policy
  body = {
    "alloc_policy": constants.ALLOC_POLICY_UNALLOCABLE,
    }

  (job_id, ) = _DoTests([
    ("/2/groups/%s/modify" % group1, _VerifyReturnsJob, "PUT", body),
    ])

  _WaitForRapiJob(job_id)

  # Rename a group
  body = {
    "new_name": group3,
    }

  (job_id, ) = _DoTests([
    ("/2/groups/%s/rename" % group2, _VerifyReturnsJob, "PUT", body),
    ])

  _WaitForRapiJob(job_id)

  # Delete groups
  for group in [group1, group3]:
    (job_id, ) = _DoTests([
      ("/2/groups/%s" % group, _VerifyReturnsJob, "DELETE", None),
      ])

    _WaitForRapiJob(job_id)


525
def TestRapiInstanceAdd(node, use_client):
526
527
528
  """Test adding a new instance via RAPI"""
  instance = qa_config.AcquireInstance()
  try:
529
530
    memory = utils.ParseUnit(qa_config.get("mem"))
    disk_sizes = [utils.ParseUnit(size) for size in qa_config.get("disk")]
531
532
    disks = [{"size": size} for size in disk_sizes]
    nics = [{}]
533

534
535
536
    beparams = {
      constants.BE_MEMORY: memory,
      }
537

538
    if use_client:
539
540
541
542
543
544
545
546
547
      job_id = _rapi_client.CreateInstance(constants.INSTANCE_CREATE,
                                           instance["name"],
                                           constants.DT_PLAIN,
                                           disks, nics,
                                           os=qa_config.get("os"),
                                           pnode=node["primary"],
                                           beparams=beparams)
    else:
      body = {
548
549
        "__version__": 1,
        "mode": constants.INSTANCE_CREATE,
550
        "name": instance["name"],
551
        "os_type": qa_config.get("os"),
552
553
        "disk_template": constants.DT_PLAIN,
        "pnode": node["primary"],
554
555
556
        "beparams": beparams,
        "disks": disks,
        "nics": nics,
557
558
559
560
561
        }

      (job_id, ) = _DoTests([
        ("/2/instances", _VerifyReturnsJob, "POST", body),
        ])
562
563
564
565
566
567
568
569
570

    _WaitForRapiJob(job_id)

    return instance
  except:
    qa_config.ReleaseInstance(instance)
    raise


571
def TestRapiInstanceRemove(instance, use_client):
572
  """Test removing instance via RAPI"""
573
574
575
576
577
578
  if use_client:
    job_id = _rapi_client.DeleteInstance(instance["name"])
  else:
    (job_id, ) = _DoTests([
      ("/2/instances/%s" % instance["name"], _VerifyReturnsJob, "DELETE", None),
      ])
579
580
581
582

  _WaitForRapiJob(job_id)

  qa_config.ReleaseInstance(instance)
583
584


585
586
587
588
589
590
def TestRapiInstanceMigrate(instance):
  """Test migrating instance via RAPI"""
  # Move to secondary node
  _WaitForRapiJob(_rapi_client.MigrateInstance(instance["name"]))
  # And back to previous primary
  _WaitForRapiJob(_rapi_client.MigrateInstance(instance["name"]))
591
592
593
594
595
596
597
598


def TestRapiInstanceFailover(instance):
  """Test failing over instance via RAPI"""
  # Move to secondary node
  _WaitForRapiJob(_rapi_client.FailoverInstance(instance["name"]))
  # And back to previous primary
  _WaitForRapiJob(_rapi_client.FailoverInstance(instance["name"]))
599
600
601
602
603
604
605
606
607
608


def TestRapiInstanceShutdown(instance):
  """Test stopping an instance via RAPI"""
  _WaitForRapiJob(_rapi_client.ShutdownInstance(instance["name"]))


def TestRapiInstanceStartup(instance):
  """Test starting an instance via RAPI"""
  _WaitForRapiJob(_rapi_client.StartupInstance(instance["name"]))
609
610


611
def TestRapiInstanceRename(rename_source, rename_target):
612
  """Test renaming instance via RAPI"""
613
  _WaitForRapiJob(_rapi_client.RenameInstance(rename_source, rename_target))
614
615


616
617
def TestRapiInstanceReinstall(instance):
  """Test reinstalling an instance via RAPI"""
618
  _WaitForRapiJob(_rapi_client.ReinstallInstance(instance["name"]))
619
620


621
622
623
624
625
626
627
628
def TestRapiInstanceReplaceDisks(instance):
  """Test replacing instance disks via RAPI"""
  _WaitForRapiJob(_rapi_client.ReplaceInstanceDisks(instance["name"],
    mode=constants.REPLACE_DISK_AUTO, disks=[]))
  _WaitForRapiJob(_rapi_client.ReplaceInstanceDisks(instance["name"],
    mode=constants.REPLACE_DISK_SEC, disks="0"))


629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def TestRapiInstanceModify(instance):
  """Test modifying instance via RAPI"""
  def _ModifyInstance(**kwargs):
    _WaitForRapiJob(_rapi_client.ModifyInstance(instance["name"], **kwargs))

  _ModifyInstance(hvparams={
    constants.HV_KERNEL_ARGS: "single",
    })

  _ModifyInstance(beparams={
    constants.BE_VCPUS: 3,
    })

  _ModifyInstance(beparams={
    constants.BE_VCPUS: constants.VALUE_DEFAULT,
    })

  _ModifyInstance(hvparams={
    constants.HV_KERNEL_ARGS: constants.VALUE_DEFAULT,
    })


651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
def TestRapiInstanceConsole(instance):
  """Test getting instance console information via RAPI"""
  result = _rapi_client.GetInstanceConsole(instance["name"])
  console = objects.InstanceConsole.FromDict(result)
  AssertEqual(console.Validate(), True)
  AssertEqual(console.instance, qa_utils.ResolveInstanceName(instance["name"]))


def TestRapiStoppedInstanceConsole(instance):
  """Test getting stopped instance's console information via RAPI"""
  try:
    _rapi_client.GetInstanceConsole(instance["name"])
  except rapi.client.GanetiApiError, err:
    AssertEqual(err.code, 503)
  else:
    raise qa_error.Error("Getting console for stopped instance didn't"
                         " return HTTP 503")


670
671
672
673
674
675
676
def GetOperatingSystems():
  """Retrieves a list of all available operating systems.

  """
  return _rapi_client.GetOperatingSystems()


677
678
def TestInterClusterInstanceMove(src_instance, dest_instance,
                                 pnode, snode, tnode):
679
680
681
682
683
684
685
686
  """Test tools/move-instance"""
  master = qa_config.GetMasterNode()

  rapi_pw_file = tempfile.NamedTemporaryFile()
  rapi_pw_file.write(_rapi_password)
  rapi_pw_file.flush()

  # TODO: Run some instance tests before moving back
Iustin Pop's avatar
Iustin Pop committed
687

688
689
690
691
692
693
694
695
  if snode is None:
    # instance is not redundant, but we still need to pass a node
    # (which will be ignored)
    fsec = tnode
  else:
    fsec = snode
  # note: pnode:snode are the *current* nodes, so we move it first to
  # tnode:pnode, then back to pnode:snode
Iustin Pop's avatar
Iustin Pop committed
696
  for si, di, pn, sn in [(src_instance["name"], dest_instance["name"],
697
                          tnode["primary"], pnode["primary"]),
Iustin Pop's avatar
Iustin Pop committed
698
                         (dest_instance["name"], src_instance["name"],
699
                          pnode["primary"], fsec["primary"])]:
700
701
702
703
704
705
    cmd = [
      "../tools/move-instance",
      "--verbose",
      "--src-ca-file=%s" % _rapi_ca.name,
      "--src-username=%s" % _rapi_username,
      "--src-password-file=%s" % rapi_pw_file.name,
Iustin Pop's avatar
Iustin Pop committed
706
707
708
      "--dest-instance-name=%s" % di,
      "--dest-primary-node=%s" % pn,
      "--dest-secondary-node=%s" % sn,
709
      "--net=0:mac=%s" % constants.VALUE_GENERATE,
710
711
      master["primary"],
      master["primary"],
Iustin Pop's avatar
Iustin Pop committed
712
      si,
713
714
715
      ]

    AssertEqual(StartLocalCommand(cmd).wait(), 0)