client.py 54 KB
Newer Older
David Knowles's avatar
David Knowles committed
1
2
3
#
#

4
# Copyright (C) 2010, 2011 Google Inc.
David Knowles's avatar
David Knowles committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#
# 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.


22
23
24
25
26
27
28
29
30
31
"""Ganeti RAPI client.

@attention: To use the RAPI client, the application B{must} call
            C{pycurl.global_init} during initialization and
            C{pycurl.global_cleanup} before exiting the process. This is very
            important in multi-threaded programs. See curl_global_init(3) and
            curl_global_cleanup(3) for details. The decorator L{UsesRapiClient}
            can be used.

"""
David Knowles's avatar
David Knowles committed
32

33
34
35
# No Ganeti-specific modules should be imported. The RAPI client is supposed to
# be standalone.

36
import logging
David Knowles's avatar
David Knowles committed
37
import simplejson
38
import socket
David Knowles's avatar
David Knowles committed
39
import urllib
40
41
import threading
import pycurl
42
import time
43
44
45
46
47

try:
  from cStringIO import StringIO
except ImportError:
  from StringIO import StringIO
David Knowles's avatar
David Knowles committed
48
49


50
GANETI_RAPI_PORT = 5080
51
GANETI_RAPI_VERSION = 2
52

David Knowles's avatar
David Knowles committed
53
54
55
56
HTTP_DELETE = "DELETE"
HTTP_GET = "GET"
HTTP_PUT = "PUT"
HTTP_POST = "POST"
57
HTTP_OK = 200
58
HTTP_NOT_FOUND = 404
59
60
HTTP_APP_JSON = "application/json"

David Knowles's avatar
David Knowles committed
61
62
63
64
REPLACE_DISK_PRI = "replace_on_primary"
REPLACE_DISK_SECONDARY = "replace_on_secondary"
REPLACE_DISK_CHG = "replace_new_secondary"
REPLACE_DISK_AUTO = "replace_auto"
65
66
67
68
69
70

NODE_ROLE_DRAINED = "drained"
NODE_ROLE_MASTER_CANDIATE = "master-candidate"
NODE_ROLE_MASTER = "master"
NODE_ROLE_OFFLINE = "offline"
NODE_ROLE_REGULAR = "regular"
David Knowles's avatar
David Knowles committed
71

72
JOB_STATUS_QUEUED = "queued"
73
JOB_STATUS_WAITING = "waiting"
74
75
76
77
78
79
80
81
82
83
84
85
JOB_STATUS_CANCELING = "canceling"
JOB_STATUS_RUNNING = "running"
JOB_STATUS_CANCELED = "canceled"
JOB_STATUS_SUCCESS = "success"
JOB_STATUS_ERROR = "error"
JOB_STATUS_FINALIZED = frozenset([
  JOB_STATUS_CANCELED,
  JOB_STATUS_SUCCESS,
  JOB_STATUS_ERROR,
  ])
JOB_STATUS_ALL = frozenset([
  JOB_STATUS_QUEUED,
86
  JOB_STATUS_WAITING,
87
88
89
90
  JOB_STATUS_CANCELING,
  JOB_STATUS_RUNNING,
  ]) | JOB_STATUS_FINALIZED

91
92
93
# Legacy name
JOB_STATUS_WAITLOCK = JOB_STATUS_WAITING

94
95
96
# Internal constants
_REQ_DATA_VERSION_FIELD = "__version__"
_INST_CREATE_REQV1 = "instance-create-reqv1"
97
_INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
98
_NODE_MIGRATE_REQV1 = "node-migrate-reqv1"
99
_NODE_EVAC_RES1 = "node-evac-res1"
100
_INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link"])
101
102
103
104
105
106
_INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
_INST_CREATE_V0_PARAMS = frozenset([
  "os", "pnode", "snode", "iallocator", "start", "ip_check", "name_check",
  "hypervisor", "file_storage_dir", "file_driver", "dry_run",
  ])
_INST_CREATE_V0_DPARAMS = frozenset(["beparams", "hvparams"])
107

108
109
110
111
112
113
114
115
116
117
118
119
120
# Older pycURL versions don't have all error constants
try:
  _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
  _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
except AttributeError:
  _CURLE_SSL_CACERT = 60
  _CURLE_SSL_CACERT_BADFILE = 77

_CURL_SSL_CERT_ERRORS = frozenset([
  _CURLE_SSL_CACERT,
  _CURLE_SSL_CACERT_BADFILE,
  ])

David Knowles's avatar
David Knowles committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

class Error(Exception):
  """Base error class for this module.

  """
  pass


class CertificateError(Error):
  """Raised when a problem is found with the SSL certificate.

  """
  pass


class GanetiApiError(Error):
  """Generic error raised from Ganeti API.

  """
140
141
142
  def __init__(self, msg, code=None):
    Error.__init__(self, msg)
    self.code = code
David Knowles's avatar
David Knowles committed
143
144


145
146
def UsesRapiClient(fn):
  """Decorator for code using RAPI client to initialize pycURL.
147
148

  """
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
  def wrapper(*args, **kwargs):
    # curl_global_init(3) and curl_global_cleanup(3) must be called with only
    # one thread running. This check is just a safety measure -- it doesn't
    # cover all cases.
    assert threading.activeCount() == 1, \
           "Found active threads when initializing pycURL"

    pycurl.global_init(pycurl.GLOBAL_ALL)
    try:
      return fn(*args, **kwargs)
    finally:
      pycurl.global_cleanup()

  return wrapper


def GenericCurlConfig(verbose=False, use_signal=False,
                      use_curl_cabundle=False, cafile=None, capath=None,
                      proxy=None, verify_hostname=False,
                      connect_timeout=None, timeout=None,
                      _pycurl_version_fn=pycurl.version_info):
  """Curl configuration function generator.

  @type verbose: bool
  @param verbose: Whether to set cURL to verbose mode
  @type use_signal: bool
  @param use_signal: Whether to allow cURL to use signals
  @type use_curl_cabundle: bool
  @param use_curl_cabundle: Whether to use cURL's default CA bundle
  @type cafile: string
  @param cafile: In which file we can find the certificates
  @type capath: string
  @param capath: In which directory we can find the certificates
  @type proxy: string
  @param proxy: Proxy to use, None for default behaviour and empty string for
                disabling proxies (see curl_easy_setopt(3))
  @type verify_hostname: bool
  @param verify_hostname: Whether to verify the remote peer certificate's
                          commonName
  @type connect_timeout: number
  @param connect_timeout: Timeout for establishing connection in seconds
  @type timeout: number
  @param timeout: Timeout for complete transfer in seconds (see
                  curl_easy_setopt(3)).
193
194

  """
195
196
  if use_curl_cabundle and (cafile or capath):
    raise Error("Can not use default CA bundle when CA file or path is set")
197

198
199
  def _ConfigCurl(curl, logger):
    """Configures a cURL object
200

201
202
    @type curl: pycurl.Curl
    @param curl: cURL object
203
204

    """
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    logger.debug("Using cURL version %s", pycurl.version)

    # pycurl.version_info returns a tuple with information about the used
    # version of libcurl. Item 5 is the SSL library linked to it.
    # e.g.: (3, '7.18.0', 463360, 'x86_64-pc-linux-gnu', 1581, 'GnuTLS/2.0.4',
    # 0, '1.2.3.3', ...)
    sslver = _pycurl_version_fn()[5]
    if not sslver:
      raise Error("No SSL support in cURL")

    lcsslver = sslver.lower()
    if lcsslver.startswith("openssl/"):
      pass
    elif lcsslver.startswith("gnutls/"):
      if capath:
        raise Error("cURL linked against GnuTLS has no support for a"
                    " CA path (%s)" % (pycurl.version, ))
222
    else:
223
224
225
226
227
228
229
230
231
232
233
234
235
236
      raise NotImplementedError("cURL uses unsupported SSL version '%s'" %
                                sslver)

    curl.setopt(pycurl.VERBOSE, verbose)
    curl.setopt(pycurl.NOSIGNAL, not use_signal)

    # Whether to verify remote peer's CN
    if verify_hostname:
      # curl_easy_setopt(3): "When CURLOPT_SSL_VERIFYHOST is 2, that
      # certificate must indicate that the server is the server to which you
      # meant to connect, or the connection fails. [...] When the value is 1,
      # the certificate must contain a Common Name field, but it doesn't matter
      # what name it says. [...]"
      curl.setopt(pycurl.SSL_VERIFYHOST, 2)
237
    else:
238
239
240
241
242
243
244
245
246
247
248
249
250
      curl.setopt(pycurl.SSL_VERIFYHOST, 0)

    if cafile or capath or use_curl_cabundle:
      # Require certificates to be checked
      curl.setopt(pycurl.SSL_VERIFYPEER, True)
      if cafile:
        curl.setopt(pycurl.CAINFO, str(cafile))
      if capath:
        curl.setopt(pycurl.CAPATH, str(capath))
      # Not changing anything for using default CA bundle
    else:
      # Disable SSL certificate verification
      curl.setopt(pycurl.SSL_VERIFYPEER, False)
251

252
253
    if proxy is not None:
      curl.setopt(pycurl.PROXY, str(proxy))
254

255
256
257
258
259
    # Timeouts
    if connect_timeout is not None:
      curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
    if timeout is not None:
      curl.setopt(pycurl.TIMEOUT, timeout)
260

261
  return _ConfigCurl
262
263


264
class GanetiRapiClient(object): # pylint: disable=R0904
David Knowles's avatar
David Knowles committed
265
266
267
268
  """Ganeti RAPI client.

  """
  USER_AGENT = "Ganeti RAPI Client"
269
  _json_encoder = simplejson.JSONEncoder(sort_keys=True)
David Knowles's avatar
David Knowles committed
270

271
  def __init__(self, host, port=GANETI_RAPI_PORT,
272
               username=None, password=None, logger=logging,
273
               curl_config_fn=None, curl_factory=None):
274
    """Initializes this class.
David Knowles's avatar
David Knowles committed
275

276
277
    @type host: string
    @param host: the ganeti cluster master to interact with
David Knowles's avatar
David Knowles committed
278
    @type port: int
279
280
    @param port: the port on which the RAPI is running (default is 5080)
    @type username: string
David Knowles's avatar
David Knowles committed
281
    @param username: the username to connect with
282
    @type password: string
David Knowles's avatar
David Knowles committed
283
    @param password: the password to connect with
284
285
    @type curl_config_fn: callable
    @param curl_config_fn: Function to configure C{pycurl.Curl} object
286
    @param logger: Logging object
David Knowles's avatar
David Knowles committed
287
288

    """
289
290
    self._username = username
    self._password = password
291
    self._logger = logger
292
293
    self._curl_config_fn = curl_config_fn
    self._curl_factory = curl_factory
David Knowles's avatar
David Knowles committed
294

295
296
297
298
299
300
301
    try:
      socket.inet_pton(socket.AF_INET6, host)
      address = "[%s]:%s" % (host, port)
    except socket.error:
      address = "%s:%s" % (host, port)

    self._base_url = "https://%s" % address
David Knowles's avatar
David Knowles committed
302

303
304
305
306
307
308
309
310
311
312
313
314
315
316
    if username is not None:
      if password is None:
        raise Error("Password not specified")
    elif password:
      raise Error("Specified password without username")

  def _CreateCurl(self):
    """Creates a cURL object.

    """
    # Create pycURL object if no factory is provided
    if self._curl_factory:
      curl = self._curl_factory()
    else:
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
      curl = pycurl.Curl()

    # Default cURL settings
    curl.setopt(pycurl.VERBOSE, False)
    curl.setopt(pycurl.FOLLOWLOCATION, False)
    curl.setopt(pycurl.MAXREDIRS, 5)
    curl.setopt(pycurl.NOSIGNAL, True)
    curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
    curl.setopt(pycurl.SSL_VERIFYHOST, 0)
    curl.setopt(pycurl.SSL_VERIFYPEER, False)
    curl.setopt(pycurl.HTTPHEADER, [
      "Accept: %s" % HTTP_APP_JSON,
      "Content-type: %s" % HTTP_APP_JSON,
      ])

332
333
334
335
336
    assert ((self._username is None and self._password is None) ^
            (self._username is not None and self._password is not None))

    if self._username:
      # Setup authentication
337
      curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
338
339
      curl.setopt(pycurl.USERPWD,
                  str("%s:%s" % (self._username, self._password)))
340

341
    # Call external configuration function
342
343
    if self._curl_config_fn:
      self._curl_config_fn(curl, self._logger)
David Knowles's avatar
David Knowles committed
344

345
    return curl
David Knowles's avatar
David Knowles committed
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
  @staticmethod
  def _EncodeQuery(query):
    """Encode query values for RAPI URL.

    @type query: list of two-tuples
    @param query: Query arguments
    @rtype: list
    @return: Query list with encoded values

    """
    result = []

    for name, value in query:
      if value is None:
        result.append((name, ""))

      elif isinstance(value, bool):
        # Boolean values must be encoded as 0 or 1
        result.append((name, int(value)))

      elif isinstance(value, (list, tuple, dict)):
        raise ValueError("Invalid query data type %r" % type(value).__name__)

      else:
        result.append((name, value))

    return result

375
  def _SendRequest(self, method, path, query, content):
David Knowles's avatar
David Knowles committed
376
377
378
379
380
    """Sends an HTTP request.

    This constructs a full URL, encodes and decodes HTTP bodies, and
    handles invalid responses in a pythonic way.

381
    @type method: string
David Knowles's avatar
David Knowles committed
382
    @param method: HTTP method to use
383
    @type path: string
David Knowles's avatar
David Knowles committed
384
385
386
387
388
389
390
391
392
    @param path: HTTP URL path
    @type query: list of two-tuples
    @param query: query arguments to pass to urllib.urlencode
    @type content: str or None
    @param content: HTTP body content

    @rtype: str
    @return: JSON-Decoded response

David Knowles's avatar
David Knowles committed
393
    @raises CertificateError: If an invalid SSL certificate is found
David Knowles's avatar
David Knowles committed
394
395
396
    @raises GanetiApiError: If an invalid response is returned

    """
397
398
    assert path.startswith("/")

399
    curl = self._CreateCurl()
400

401
    if content is not None:
402
403
      encoded_content = self._json_encoder.encode(content)
    else:
404
      encoded_content = ""
David Knowles's avatar
David Knowles committed
405

406
    # Build URL
407
    urlparts = [self._base_url, path]
408
    if query:
409
410
      urlparts.append("?")
      urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
411

412
413
    url = "".join(urlparts)

414
415
    self._logger.debug("Sending request %s %s (content=%r)",
                       method, url, encoded_content)
416
417
418

    # Buffer for response
    encoded_resp_body = StringIO()
419

420
421
422
423
424
    # Configure cURL
    curl.setopt(pycurl.CUSTOMREQUEST, str(method))
    curl.setopt(pycurl.URL, str(url))
    curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
    curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
425

David Knowles's avatar
David Knowles committed
426
    try:
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
      # Send request and wait for response
      try:
        curl.perform()
      except pycurl.error, err:
        if err.args[0] in _CURL_SSL_CERT_ERRORS:
          raise CertificateError("SSL certificate error %s" % err)

        raise GanetiApiError(str(err))
    finally:
      # Reset settings to not keep references to large objects in memory
      # between requests
      curl.setopt(pycurl.POSTFIELDS, "")
      curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)

    # Get HTTP response code
    http_code = curl.getinfo(pycurl.RESPONSE_CODE)

    # Was anything written to the response buffer?
    if encoded_resp_body.tell():
      response_content = simplejson.loads(encoded_resp_body.getvalue())
447
448
    else:
      response_content = None
David Knowles's avatar
David Knowles committed
449

450
    if http_code != HTTP_OK:
451
      if isinstance(response_content, dict):
David Knowles's avatar
David Knowles committed
452
        msg = ("%s %s: %s" %
453
454
455
               (response_content["code"],
                response_content["message"],
                response_content["explain"]))
David Knowles's avatar
David Knowles committed
456
      else:
457
458
        msg = str(response_content)

459
      raise GanetiApiError(msg, code=http_code)
David Knowles's avatar
David Knowles committed
460

461
    return response_content
David Knowles's avatar
David Knowles committed
462
463

  def GetVersion(self):
464
    """Gets the Remote API version running on the cluster.
David Knowles's avatar
David Knowles committed
465
466

    @rtype: int
David Knowles's avatar
David Knowles committed
467
    @return: Ganeti Remote API version
David Knowles's avatar
David Knowles committed
468
469

    """
470
    return self._SendRequest(HTTP_GET, "/version", None, None)
David Knowles's avatar
David Knowles committed
471

472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
  def GetFeatures(self):
    """Gets the list of optional features supported by RAPI server.

    @rtype: list
    @return: List of optional features

    """
    try:
      return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
                               None, None)
    except GanetiApiError, err:
      # Older RAPI servers don't support this resource
      if err.code == HTTP_NOT_FOUND:
        return []

      raise

David Knowles's avatar
David Knowles committed
489
490
491
492
493
494
495
  def GetOperatingSystems(self):
    """Gets the Operating Systems running in the Ganeti cluster.

    @rtype: list of str
    @return: operating systems

    """
496
497
    return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
                             None, None)
David Knowles's avatar
David Knowles committed
498
499
500
501
502
503
504
505

  def GetInfo(self):
    """Gets info about the cluster.

    @rtype: dict
    @return: information about the cluster

    """
506
507
    return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
                             None, None)
David Knowles's avatar
David Knowles committed
508

509
510
511
  def RedistributeConfig(self):
    """Tells the cluster to redistribute its configuration files.

512
    @rtype: string
513
514
515
516
517
518
519
    @return: job id

    """
    return self._SendRequest(HTTP_PUT,
                             "/%s/redistribute-config" % GANETI_RAPI_VERSION,
                             None, None)

520
521
522
523
524
  def ModifyCluster(self, **kwargs):
    """Modifies cluster parameters.

    More details for parameters can be found in the RAPI documentation.

525
    @rtype: string
526
527
528
529
530
531
532
533
    @return: job id

    """
    body = kwargs

    return self._SendRequest(HTTP_PUT,
                             "/%s/modify" % GANETI_RAPI_VERSION, None, body)

David Knowles's avatar
David Knowles committed
534
535
536
537
538
539
540
  def GetClusterTags(self):
    """Gets the cluster tags.

    @rtype: list of str
    @return: cluster tags

    """
541
542
    return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
                             None, None)
David Knowles's avatar
David Knowles committed
543
544
545
546
547
548
549
550
551

  def AddClusterTags(self, tags, dry_run=False):
    """Adds tags to the cluster.

    @type tags: list of str
    @param tags: tags to add to the cluster
    @type dry_run: bool
    @param dry_run: whether to perform a dry run

552
    @rtype: string
David Knowles's avatar
David Knowles committed
553
554
555
556
557
558
559
    @return: job id

    """
    query = [("tag", t) for t in tags]
    if dry_run:
      query.append(("dry-run", 1))

560
561
    return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
                             query, None)
David Knowles's avatar
David Knowles committed
562
563
564
565
566
567
568
569

  def DeleteClusterTags(self, tags, dry_run=False):
    """Deletes tags from the cluster.

    @type tags: list of str
    @param tags: tags to delete
    @type dry_run: bool
    @param dry_run: whether to perform a dry run
570
571
    @rtype: string
    @return: job id
David Knowles's avatar
David Knowles committed
572
573
574
575
576
577

    """
    query = [("tag", t) for t in tags]
    if dry_run:
      query.append(("dry-run", 1))

578
579
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
                             query, None)
David Knowles's avatar
David Knowles committed
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594

  def GetInstances(self, bulk=False):
    """Gets information about instances on the cluster.

    @type bulk: bool
    @param bulk: whether to return all information about all instances

    @rtype: list of dict or list of str
    @return: if bulk is True, info about the instances, else a list of instances

    """
    query = []
    if bulk:
      query.append(("bulk", 1))

595
596
597
    instances = self._SendRequest(HTTP_GET,
                                  "/%s/instances" % GANETI_RAPI_VERSION,
                                  query, None)
David Knowles's avatar
David Knowles committed
598
599
600
601
602
    if bulk:
      return instances
    else:
      return [i["id"] for i in instances]

603
  def GetInstance(self, instance):
David Knowles's avatar
David Knowles committed
604
605
606
607
608
609
610
611
612
    """Gets information about an instance.

    @type instance: str
    @param instance: instance whose info to return

    @rtype: dict
    @return: info about the instance

    """
613
614
615
    return self._SendRequest(HTTP_GET,
                             ("/%s/instances/%s" %
                              (GANETI_RAPI_VERSION, instance)), None, None)
David Knowles's avatar
David Knowles committed
616

617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
  def GetInstanceInfo(self, instance, static=None):
    """Gets information about an instance.

    @type instance: string
    @param instance: Instance name
    @rtype: string
    @return: Job ID

    """
    if static is not None:
      query = [("static", static)]
    else:
      query = None

    return self._SendRequest(HTTP_GET,
                             ("/%s/instances/%s/info" %
                              (GANETI_RAPI_VERSION, instance)), query, None)

635
636
  def CreateInstance(self, mode, name, disk_template, disks, nics,
                     **kwargs):
David Knowles's avatar
David Knowles committed
637
638
    """Creates a new instance.

639
640
641
642
643
644
645
646
647
648
649
650
651
    More details for parameters can be found in the RAPI documentation.

    @type mode: string
    @param mode: Instance creation mode
    @type name: string
    @param name: Hostname of the instance to create
    @type disk_template: string
    @param disk_template: Disk template for instance (e.g. plain, diskless,
                          file, or drbd)
    @type disks: list of dicts
    @param disks: List of disk definitions
    @type nics: list of dicts
    @param nics: List of NIC definitions
David Knowles's avatar
David Knowles committed
652
    @type dry_run: bool
653
    @keyword dry_run: whether to perform a dry run
David Knowles's avatar
David Knowles committed
654

655
    @rtype: string
David Knowles's avatar
David Knowles committed
656
657
658
659
    @return: job id

    """
    query = []
660
661

    if kwargs.get("dry_run"):
David Knowles's avatar
David Knowles committed
662
663
      query.append(("dry-run", 1))

664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
    if _INST_CREATE_REQV1 in self.GetFeatures():
      # All required fields for request data version 1
      body = {
        _REQ_DATA_VERSION_FIELD: 1,
        "mode": mode,
        "name": name,
        "disk_template": disk_template,
        "disks": disks,
        "nics": nics,
        }

      conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
      if conflicts:
        raise GanetiApiError("Required fields can not be specified as"
                             " keywords: %s" % ", ".join(conflicts))

      body.update((key, value) for key, value in kwargs.iteritems()
                  if key != "dry_run")
    else:
683
684
      raise GanetiApiError("Server does not support new-style (version 1)"
                           " instance creation requests")
685

686
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
687
                             query, body)
David Knowles's avatar
David Knowles committed
688
689
690
691
692
693
694

  def DeleteInstance(self, instance, dry_run=False):
    """Deletes an instance.

    @type instance: str
    @param instance: the instance to delete

695
    @rtype: string
696
697
    @return: job id

David Knowles's avatar
David Knowles committed
698
699
700
701
702
    """
    query = []
    if dry_run:
      query.append(("dry-run", 1))

703
704
705
    return self._SendRequest(HTTP_DELETE,
                             ("/%s/instances/%s" %
                              (GANETI_RAPI_VERSION, instance)), query, None)
David Knowles's avatar
David Knowles committed
706

707
708
709
710
711
712
713
  def ModifyInstance(self, instance, **kwargs):
    """Modifies an instance.

    More details for parameters can be found in the RAPI documentation.

    @type instance: string
    @param instance: Instance name
714
    @rtype: string
715
716
717
718
719
720
721
722
723
    @return: job id

    """
    body = kwargs

    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/modify" %
                              (GANETI_RAPI_VERSION, instance)), None, body)

724
725
726
727
728
729
730
  def ActivateInstanceDisks(self, instance, ignore_size=None):
    """Activates an instance's disks.

    @type instance: string
    @param instance: Instance name
    @type ignore_size: bool
    @param ignore_size: Whether to ignore recorded size
731
    @rtype: string
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
    @return: job id

    """
    query = []
    if ignore_size:
      query.append(("ignore_size", 1))

    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/activate-disks" %
                              (GANETI_RAPI_VERSION, instance)), query, None)

  def DeactivateInstanceDisks(self, instance):
    """Deactivates an instance's disks.

    @type instance: string
    @param instance: Instance name
748
    @rtype: string
749
750
751
752
753
754
755
    @return: job id

    """
    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/deactivate-disks" %
                              (GANETI_RAPI_VERSION, instance)), None, None)

756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
  def RecreateInstanceDisks(self, instance, disks=None, nodes=None):
    """Recreate an instance's disks.

    @type instance: string
    @param instance: Instance name
    @type disks: list of int
    @param disks: List of disk indexes
    @type nodes: list of string
    @param nodes: New instance nodes, if relocation is desired
    @rtype: string
    @return: job id

    """
    body = {}

    if disks is not None:
      body["disks"] = disks

    if nodes is not None:
      body["nodes"] = nodes

    return self._SendRequest(HTTP_POST,
                             ("/%s/instances/%s/recreate-disks" %
                              (GANETI_RAPI_VERSION, instance)), None, body)

781
782
783
784
785
786
787
788
789
790
791
792
793
  def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
    """Grows a disk of an instance.

    More details for parameters can be found in the RAPI documentation.

    @type instance: string
    @param instance: Instance name
    @type disk: integer
    @param disk: Disk index
    @type amount: integer
    @param amount: Grow disk by this amount (MiB)
    @type wait_for_sync: bool
    @param wait_for_sync: Wait for disk to synchronize
794
    @rtype: string
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
    @return: job id

    """
    body = {
      "amount": amount,
      }

    if wait_for_sync is not None:
      body["wait_for_sync"] = wait_for_sync

    return self._SendRequest(HTTP_POST,
                             ("/%s/instances/%s/disk/%s/grow" %
                              (GANETI_RAPI_VERSION, instance, disk)),
                             None, body)

David Knowles's avatar
David Knowles committed
810
811
812
813
814
815
816
817
818
819
  def GetInstanceTags(self, instance):
    """Gets tags for an instance.

    @type instance: str
    @param instance: instance whose tags to return

    @rtype: list of str
    @return: tags for the instance

    """
820
821
822
    return self._SendRequest(HTTP_GET,
                             ("/%s/instances/%s/tags" %
                              (GANETI_RAPI_VERSION, instance)), None, None)
David Knowles's avatar
David Knowles committed
823
824
825
826
827
828
829
830
831
832
833

  def AddInstanceTags(self, instance, tags, dry_run=False):
    """Adds tags to an instance.

    @type instance: str
    @param instance: instance to add tags to
    @type tags: list of str
    @param tags: tags to add to the instance
    @type dry_run: bool
    @param dry_run: whether to perform a dry run

834
    @rtype: string
David Knowles's avatar
David Knowles committed
835
836
837
838
839
840
841
    @return: job id

    """
    query = [("tag", t) for t in tags]
    if dry_run:
      query.append(("dry-run", 1))

842
843
844
    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/tags" %
                              (GANETI_RAPI_VERSION, instance)), query, None)
David Knowles's avatar
David Knowles committed
845
846
847
848
849
850
851
852
853
854

  def DeleteInstanceTags(self, instance, tags, dry_run=False):
    """Deletes tags from an instance.

    @type instance: str
    @param instance: instance to delete tags from
    @type tags: list of str
    @param tags: tags to delete
    @type dry_run: bool
    @param dry_run: whether to perform a dry run
855
856
    @rtype: string
    @return: job id
David Knowles's avatar
David Knowles committed
857
858
859
860
861
862

    """
    query = [("tag", t) for t in tags]
    if dry_run:
      query.append(("dry-run", 1))

863
864
865
    return self._SendRequest(HTTP_DELETE,
                             ("/%s/instances/%s/tags" %
                              (GANETI_RAPI_VERSION, instance)), query, None)
David Knowles's avatar
David Knowles committed
866
867
868
869
870
871
872
873
874
875
876
877
878
879

  def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
                     dry_run=False):
    """Reboots an instance.

    @type instance: str
    @param instance: instance to rebot
    @type reboot_type: str
    @param reboot_type: one of: hard, soft, full
    @type ignore_secondaries: bool
    @param ignore_secondaries: if True, ignores errors for the secondary node
        while re-assembling disks (in hard-reboot mode only)
    @type dry_run: bool
    @param dry_run: whether to perform a dry run
880
881
    @rtype: string
    @return: job id
David Knowles's avatar
David Knowles committed
882
883
884
885
886
887
888
889
890
891

    """
    query = []
    if reboot_type:
      query.append(("type", reboot_type))
    if ignore_secondaries is not None:
      query.append(("ignore_secondaries", ignore_secondaries))
    if dry_run:
      query.append(("dry-run", 1))

892
893
894
    return self._SendRequest(HTTP_POST,
                             ("/%s/instances/%s/reboot" %
                              (GANETI_RAPI_VERSION, instance)), query, None)
David Knowles's avatar
David Knowles committed
895

896
  def ShutdownInstance(self, instance, dry_run=False, no_remember=False):
David Knowles's avatar
David Knowles committed
897
898
899
900
901
902
    """Shuts down an instance.

    @type instance: str
    @param instance: the instance to shut down
    @type dry_run: bool
    @param dry_run: whether to perform a dry run
903
904
    @type no_remember: bool
    @param no_remember: if true, will not record the state change
905
906
    @rtype: string
    @return: job id
David Knowles's avatar
David Knowles committed
907
908
909
910
911

    """
    query = []
    if dry_run:
      query.append(("dry-run", 1))
912
913
    if no_remember:
      query.append(("no-remember", 1))
David Knowles's avatar
David Knowles committed
914

915
916
917
    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/shutdown" %
                              (GANETI_RAPI_VERSION, instance)), query, None)
David Knowles's avatar
David Knowles committed
918

919
  def StartupInstance(self, instance, dry_run=False, no_remember=False):
David Knowles's avatar
David Knowles committed
920
921
922
923
924
925
    """Starts up an instance.

    @type instance: str
    @param instance: the instance to start up
    @type dry_run: bool
    @param dry_run: whether to perform a dry run
926
927
    @type no_remember: bool
    @param no_remember: if true, will not record the state change
928
929
    @rtype: string
    @return: job id
David Knowles's avatar
David Knowles committed
930
931
932
933
934

    """
    query = []
    if dry_run:
      query.append(("dry-run", 1))
935
936
    if no_remember:
      query.append(("no-remember", 1))
David Knowles's avatar
David Knowles committed
937

938
939
940
    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/startup" %
                              (GANETI_RAPI_VERSION, instance)), query, None)
David Knowles's avatar
David Knowles committed
941

942
943
  def ReinstallInstance(self, instance, os=None, no_startup=False,
                        osparams=None):
David Knowles's avatar
David Knowles committed
944
945
946
    """Reinstalls an instance.

    @type instance: str
947
948
949
950
    @param instance: The instance to reinstall
    @type os: str or None
    @param os: The operating system to reinstall. If None, the instance's
        current operating system will be installed again
David Knowles's avatar
David Knowles committed
951
    @type no_startup: bool
952
    @param no_startup: Whether to start the instance automatically
953
954
    @rtype: string
    @return: job id
David Knowles's avatar
David Knowles committed
955
956

    """
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
    if _INST_REINSTALL_REQV1 in self.GetFeatures():
      body = {
        "start": not no_startup,
        }
      if os is not None:
        body["os"] = os
      if osparams is not None:
        body["osparams"] = osparams
      return self._SendRequest(HTTP_POST,
                               ("/%s/instances/%s/reinstall" %
                                (GANETI_RAPI_VERSION, instance)), None, body)

    # Use old request format
    if osparams:
      raise GanetiApiError("Server does not support specifying OS parameters"
                           " for instance reinstallation")

974
975
976
    query = []
    if os:
      query.append(("os", os))
David Knowles's avatar
David Knowles committed
977
978
    if no_startup:
      query.append(("nostartup", 1))
979
980
981
    return self._SendRequest(HTTP_POST,
                             ("/%s/instances/%s/reinstall" %
                              (GANETI_RAPI_VERSION, instance)), query, None)
David Knowles's avatar
David Knowles committed
982

983
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
984
                           remote_node=None, iallocator=None, dry_run=False):
David Knowles's avatar
David Knowles committed
985
986
987
988
    """Replaces disks on an instance.

    @type instance: str
    @param instance: instance whose disks to replace
989
990
    @type disks: list of ints
    @param disks: Indexes of disks to replace
David Knowles's avatar
David Knowles committed
991
    @type mode: str
992
    @param mode: replacement mode to use (defaults to replace_auto)
David Knowles's avatar
David Knowles committed
993
994
    @type remote_node: str or None
    @param remote_node: new secondary node to use (for use with
995
        replace_new_secondary mode)
David Knowles's avatar
David Knowles committed
996
997
    @type iallocator: str or None
    @param iallocator: instance allocator plugin to use (for use with
998
                       replace_auto mode)
David Knowles's avatar
David Knowles committed
999
1000
1001
    @type dry_run: bool
    @param dry_run: whether to perform a dry run

1002
    @rtype: string
David Knowles's avatar
David Knowles committed
1003
1004
1005
    @return: job id

    """
1006
1007
1008
    query = [
      ("mode", mode),
      ]
David Knowles's avatar
David Knowles committed
1009

1010
1011
1012
1013
    if disks:
      query.append(("disks", ",".join(str(idx) for idx in disks)))

    if remote_node:
David Knowles's avatar
David Knowles committed
1014
1015
      query.append(("remote_node", remote_node))

1016
1017
1018
    if iallocator:
      query.append(("iallocator", iallocator))

David Knowles's avatar
David Knowles committed
1019
1020
1021
1022
    if dry_run:
      query.append(("dry-run", 1))

    return self._SendRequest(HTTP_POST,
1023
1024
                             ("/%s/instances/%s/replace-disks" %
                              (GANETI_RAPI_VERSION, instance)), query, None)
David Knowles's avatar
David Knowles committed
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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
  def PrepareExport(self, instance, mode):
    """Prepares an instance for an export.

    @type instance: string
    @param instance: Instance name
    @type mode: string
    @param mode: Export mode
    @rtype: string
    @return: Job ID

    """
    query = [("mode", mode)]
    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/prepare-export" %
                              (GANETI_RAPI_VERSION, instance)), query, None)

  def ExportInstance(self, instance, mode, destination, shutdown=None,
                     remove_instance=None,
                     x509_key_name=None, destination_x509_ca=None):
    """Exports an instance.

    @type instance: string
    @param instance: Instance name
    @type mode: string
    @param mode: Export mode
    @rtype: string
    @return: Job ID

    """
    body = {
      "destination": destination,
      "mode": mode,
      }

    if shutdown is not None:
      body["shutdown"] = shutdown

    if remove_instance is not None:
      body["remove_instance"] = remove_instance

    if x509_key_name is not None:
      body["x509_key_name"] = x509_key_name

    if destination_x509_ca is not None:
      body["destination_x509_ca"] = destination_x509_ca

    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/export" %
                              (GANETI_RAPI_VERSION, instance)), None, body)

1076
  def MigrateInstance(self, instance, mode=None, cleanup=None):
1077
    """Migrates an instance.
1078
1079
1080
1081
1082
1083
1084

    @type instance: string
    @param instance: Instance name
    @type mode: string
    @param mode: Migration mode
    @type cleanup: bool
    @param cleanup: Whether to clean up a previously failed migration
1085
1086
    @rtype: string
    @return: job id
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100

    """
    body = {}

    if mode is not None:
      body["mode"] = mode

    if cleanup is not None:
      body["cleanup"] = cleanup

    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/migrate" %
                              (GANETI_RAPI_VERSION, instance)), None, body)

1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
  def FailoverInstance(self, instance, iallocator=None,
                       ignore_consistency=None, target_node=None):
    """Does a failover of an instance.

    @type instance: string
    @param instance: Instance name
    @type iallocator: string
    @param iallocator: Iallocator for deciding the target node for
      shared-storage instances
    @type ignore_consistency: bool
    @param ignore_consistency: Whether to ignore disk consistency
    @type target_node: string
    @param target_node: Target node for shared-storage instances
    @rtype: string
    @return: job id

    """
    body = {}

    if iallocator is not None:
      body["iallocator"] = iallocator

    if ignore_consistency is not None:
      body["ignore_consistency"] = ignore_consistency

    if target_node is not None:
      body["target_node"] = target_node

    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/failover" %
                              (GANETI_RAPI_VERSION, instance)), None, body)

1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
  def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
    """Changes the name of an instance.

    @type instance: string
    @param instance: Instance name
    @type new_name: string
    @param new_name: New instance name
    @type ip_check: bool
    @param ip_check: Whether to ensure instance's IP address is inactive
    @type name_check: bool
    @param name_check: Whether to ensure instance's name is resolvable
1144
1145
    @rtype: string
    @return: job id
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161

    """
    body = {
      "new_name": new_name,
      }

    if ip_check is not None:
      body["ip_check"] = ip_check

    if name_check is not None:
      body["name_check"] = name_check

    return self._SendRequest(HTTP_PUT,
                             ("/%s/instances/%s/rename" %
                              (GANETI_RAPI_VERSION, instance)), None, body)

1162
1163
1164
1165
1166
  def GetInstanceConsole(self, instance):
    """Request information for connecting to instance's console.

    @type instance: string
    @param instance: Instance name
1167
1168
    @rtype: dict
    @return: dictionary containing information about instance's console
1169
1170
1171
1172
1173
1174

    """
    return self._SendRequest(HTTP_GET,
                             ("/%s/instances/%s/console" %
                              (GANETI_RAPI_VERSION, instance)), None, None)

David Knowles's avatar
David Knowles committed
1175
1176
1177
1178
1179
1180
1181
  def GetJobs(self):
    """Gets all jobs for the cluster.

    @rtype: list of int
    @return: job ids for the cluster

    """
1182
    return [int(j["id"])
1183
1184
1185
            for j in self._SendRequest(HTTP_GET,
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
                                       None, None)]
David Knowles's avatar
David Knowles committed
1186
1187
1188
1189

  def GetJobStatus(self, job_id):
    """Gets the status of a job.

1190
    @type job_id: string
David Knowles's avatar
David Knowles committed
1191
1192
1193
1194
1195
1196
    @param job_id: job id whose status to query

    @rtype: dict
    @return: job status

    """
1197
1198
1199
    return self._SendRequest(HTTP_GET,
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
                             None, None)
David Knowles's avatar
David Knowles committed
1200

1201
1202
1203
  def WaitForJobCompletion(self, job_id, period=5, retries=-1):
    """Polls cluster for job status until completion.

1204
1205
    Completion is defined as any of the following states listed in
    L{JOB_STATUS_FINALIZED}.
1206

1207
    @type job_id: string
1208
1209
1210
1211
1212
1213
1214
1215
    @param job_id: job id to watch
    @type period: int
    @param period: how often to poll for status (optional, default 5s)
    @type retries: int
    @param retries: how many time to poll before giving up
                    (optional, default -1 means unlimited)

    @rtype: bool
1216
1217
1218
1219
    @return: C{True} if job succeeded or C{False} if failed/status timeout
    @deprecated: It is recommended to use L{WaitForJobChange} wherever
      possible; L{WaitForJobChange} returns immediately after a job changed and
      does not use polling
1220

1221
1222
1223
    """
    while retries != 0:
      job_result = self.GetJobStatus(job_id)
1224
1225

      if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
1226
        return True
1227
1228
1229
1230
1231
1232
      elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
        return False

      if period:
        time.sleep(period)

1233
1234
      if retries > 0:
        retries -= 1
1235

1236
1237
    return False

1238
1239
1240
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
    """Waits for job changes.

1241
    @type job_id: string
1242
    @param job_id: Job ID for which to wait
1243
1244
1245
    @return: C{None} if no changes have been detected and a dict with two keys,
      C{job_info} and C{log_entries} otherwise.
    @rtype: dict
1246
1247
1248
1249
1250
1251
1252
1253

    """
    body = {
      "fields": fields,
      "previous_job_info": prev_job_info,
      "previous_log_serial": prev_log_serial,
      }

1254
1255
1256
    return self._SendRequest(HTTP_GET,
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
                             None, body)
1257

1258
1259
  def CancelJob(self, job_id, dry_run=False):
    """Cancels a job.
David Knowles's avatar
David Knowles committed
1260

1261
    @type job_id: string
David Knowles's avatar
David Knowles committed
1262
1263
1264
    @param job_id: id of the job to delete
    @type dry_run: bool
    @param dry_run: whether to perform a dry run
1265
1266
    @rtype: tuple
    @return: tuple containing the result, and a message (bool, string)
David Knowles's avatar
David Knowles committed
1267
1268
1269
1270
1271
1272

    """
    query = []
    if dry_run:
      query.append(("dry-run", 1))

1273
1274
1275
    return self._SendRequest(HTTP_DELETE,
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
                             query, None)
David Knowles's avatar
David Knowles committed
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291

  def GetNodes(self, bulk=False):
    """Gets all nodes in the cluster.

    @type bulk: bool
    @param bulk: whether to return all information about all instances

    @rtype: list of dict or str
    @return: if bulk is true, info about nodes in the cluster,
        else list of nodes in the cluster

    """
    query = []
    if bulk:
      query.append(("bulk", 1))

1292
1293
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
                              query, None)
David Knowles's avatar
David Knowles committed
1294
1295
1296
1297
1298
    if bulk:
      return nodes
    else:
      return [n["id"] for n in nodes]

1299
  def GetNode(self, node):
David Knowles's avatar
David Knowles committed
1300
1301
1302
1303
1304
1305
1306
1307
1308
    """Gets information about a node.

    @type node: str
    @param node: node whose info to return

    @rtype: dict
    @return: info about the node

    """
1309
1310
1311
    return self._SendRequest(HTTP_GET,
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
                             None, None)
David Knowles's avatar
David Knowles committed
1312
1313

  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1314
1315
                   dry_run=False, early_release=None,
                   primary=None, secondary=None, accept_old=False):
David Knowles's avatar
David Knowles committed
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
    """Evacuates instances from a Ganeti node.

    @type node: str
    @param node: node to evacuate
    @type iallocator: str or None
    @param iallocator: instance allocator to use
    @type remote_node: str
    @param remote_node: node to evaucate to
    @type dry_run: bool
    @param dry_run: whether to perform a dry run
1326
1327
    @type early_release: bool
    @param early_release: whether to enable parallelization
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
    @type primary: bool
    @param primary: Whether to evacuate primary instances
    @type secondary: bool
    @param secondary: Whether to evacuate secondary instances
    @type accept_old: bool
    @param accept_old: Whether caller is ready to accept old-style (pre-2.5)
        results

    @rtype: string, or a list for pre-2.5 results
    @return: Job ID or, if C{accept_old} is set and server is pre-2.5,
      list of (job ID, instance name, new secondary node); if dry_run was
      specified, then the actual move jobs were not submitted and the job IDs
      will be C{None}
David Knowles's avatar
David Knowles committed
1341

1342
1343
    @raises GanetiApiError: if an iallocator and remote_node are both
        specified
David Knowles's avatar
David Knowles committed
1344
1345
1346

    """
    if iallocator and remote_node:
1347
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
David Knowles's avatar
David Knowles committed
1348

1349
    query = []
David Knowles's avatar
David Knowles committed
1350
1351
    if dry_run:
      query.append(("dry-run", 1))
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383

    if _NODE_EVAC_RES1 in self.GetFeatures():
      body = {}

      if iallocator is not None:
        body["iallocator"] = iallocator
      if remote_node is not None:
        body["remote_node"] = remote_node
      if early_release is not None:
        body["early_release"] = early_release
      if primary is not None:
        body["primary"] = primary
      if secondary is not None:
        body["secondary"] = secondary
    else:
      # Pre-2.5 request format
      body = None

      if not accept_old:
        raise GanetiApiError("Server is version 2.4 or earlier and caller does"
                             " not accept old-style results (parameter"
                             " accept_old)")

      if primary or primary is None or not (secondary is None or secondary):
        raise GanetiApiError("Server can only evacuate secondary instances")

      if iallocator:
        query.append(("iallocator", iallocator))
      if remote_node:
        query.append(("remote_node", remote_node))
      if early_release:
        query.append(("early_release", 1))
David Knowles's avatar
David Knowles committed
1384

1385
1386
    return self._SendRequest(HTTP_POST,
                             ("/%s/nodes/%s/evacuate" %
1387
                              (GANETI_RAPI_VERSION, node)), query, body)
David Knowles's avatar
David Knowles committed
1388

1389
1390
  def MigrateNode(self, node, mode=None, dry_run=False, iallocator=None,
                  target_node=None):
David Knowles's avatar
David Knowles committed
1391
1392
1393
1394
    """Migrates all primary instances from a node.

    @type node: str
    @param node: node to migrate
1395
1396
1397
    @type mode: string
    @param mode: if passed, it will overwrite the live migration type,
        otherwise the hypervisor default will be used
David Knowles's avatar
David Knowles committed
1398
1399
    @type dry_run: bool
    @param dry_run: whether to perform a dry run
1400
1401
1402
1403
    @type iallocator: string
    @param iallocator: instance allocator to use
    @type target_node: string
    @param target_node: Target node for shared-storage instances
David Knowles's avatar
David Knowles committed
1404

1405
    @rtype: string
David Knowles's avatar
David Knowles committed
1406
1407
1408
1409
1410
1411
1412
    @return: job id

    """
    query = []
    if dry_run:
      query.append(("dry-run", 1))

1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
    if _NODE_MIGRATE_REQV1 in self.GetFeatures():
      body = {}

      if mode is not None:
        body["mode"] = mode
      if iallocator is not None:
        body["iallocator"] = iallocator
      if target_node is not None:
        body["target_node"] = target_node

      assert len(query) <= 1

      return self._SendRequest(HTTP_POST,
                               ("/%s/nodes/%s/migrate" %
                                (GANETI_RAPI_VERSION, node)), query, body)
    else:
      # Use old request format
      if target_node is not None:
        raise GanetiApiError("Server does not support specifying target node"
                             " for node migration")

      if mode is not None:
        query.append(("mode", mode))

      return self._SendRequest(HTTP_POST,
                               ("/%s/nodes/%s/migrate" %
                                (GANETI_RAPI_VERSION, node)), query, None)
David Knowles's avatar
David Knowles committed
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450

  def GetNodeRole(self, node):
    """Gets the current role for a node.

    @type node: str
    @param node: node whose role to return

    @rtype: str
    @return: the current role for a node

    """
1451
1452
1453
    return self._SendRequest(HTTP_GET,
                             ("/%s/nodes/%s/role" %
                              (GANETI_RAPI_VERSION, node)), None, None)
David Knowles's avatar
David Knowles committed
1454

1455
  def SetNodeRole(self, node, role, force=False, auto_promote=None):
David Knowles's avatar
David Knowles committed
1456
1457
1458
1459
1460
1461
1462
1463
    """Sets the role for a node.

    @type node: str
    @param node: the node whose role to set
    @type role: str
    @param role: the role to set for the node
    @type force: bool
    @param force: whether to force the role change
1464
1465
1466
    @type auto_promote: bool
    @param auto_promote: Whether node(s) should be promoted to master candidate
                         if necessary
David Knowles's avatar
David Knowles committed
1467

1468
    @rtype: string
David Knowles's avatar
David Knowles committed
1469
1470
1471
    @return: job id

    """
1472
1473
1474
    query = [
      ("force", force),
      ]
1475

1476
1477
1478
    if auto_promote is not None:
      query.append(("auto-promote", auto_promote))

1479 <