Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ a268af8d

History | View | Annotate | Download (42.6 kB)

1
#
2
#
3

    
4
# Copyright (C) 2010 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Ganeti RAPI client.
23

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

31
"""
32

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

    
36
import logging
37
import simplejson
38
import socket
39
import urllib
40
import threading
41
import pycurl
42

    
43
try:
44
  from cStringIO import StringIO
45
except ImportError:
46
  from StringIO import StringIO
47

    
48

    
49
GANETI_RAPI_PORT = 5080
50
GANETI_RAPI_VERSION = 2
51

    
52
HTTP_DELETE = "DELETE"
53
HTTP_GET = "GET"
54
HTTP_PUT = "PUT"
55
HTTP_POST = "POST"
56
HTTP_OK = 200
57
HTTP_NOT_FOUND = 404
58
HTTP_APP_JSON = "application/json"
59

    
60
REPLACE_DISK_PRI = "replace_on_primary"
61
REPLACE_DISK_SECONDARY = "replace_on_secondary"
62
REPLACE_DISK_CHG = "replace_new_secondary"
63
REPLACE_DISK_AUTO = "replace_auto"
64

    
65
NODE_ROLE_DRAINED = "drained"
66
NODE_ROLE_MASTER_CANDIATE = "master-candidate"
67
NODE_ROLE_MASTER = "master"
68
NODE_ROLE_OFFLINE = "offline"
69
NODE_ROLE_REGULAR = "regular"
70

    
71
# Internal constants
72
_REQ_DATA_VERSION_FIELD = "__version__"
73
_INST_CREATE_REQV1 = "instance-create-reqv1"
74
_INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
75
_INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link", "bridge"])
76
_INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
77
_INST_CREATE_V0_PARAMS = frozenset([
78
  "os", "pnode", "snode", "iallocator", "start", "ip_check", "name_check",
79
  "hypervisor", "file_storage_dir", "file_driver", "dry_run",
80
  ])
81
_INST_CREATE_V0_DPARAMS = frozenset(["beparams", "hvparams"])
82

    
83
# Older pycURL versions don't have all error constants
84
try:
85
  _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
86
  _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
87
except AttributeError:
88
  _CURLE_SSL_CACERT = 60
89
  _CURLE_SSL_CACERT_BADFILE = 77
90

    
91
_CURL_SSL_CERT_ERRORS = frozenset([
92
  _CURLE_SSL_CACERT,
93
  _CURLE_SSL_CACERT_BADFILE,
94
  ])
95

    
96

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

100
  """
101
  pass
102

    
103

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

107
  """
108
  pass
109

    
110

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

114
  """
115
  def __init__(self, msg, code=None):
116
    Error.__init__(self, msg)
117
    self.code = code
118

    
119

    
120
def UsesRapiClient(fn):
121
  """Decorator for code using RAPI client to initialize pycURL.
122

123
  """
124
  def wrapper(*args, **kwargs):
125
    # curl_global_init(3) and curl_global_cleanup(3) must be called with only
126
    # one thread running. This check is just a safety measure -- it doesn't
127
    # cover all cases.
128
    assert threading.activeCount() == 1, \
129
           "Found active threads when initializing pycURL"
130

    
131
    pycurl.global_init(pycurl.GLOBAL_ALL)
132
    try:
133
      return fn(*args, **kwargs)
134
    finally:
135
      pycurl.global_cleanup()
136

    
137
  return wrapper
138

    
139

    
140
def GenericCurlConfig(verbose=False, use_signal=False,
141
                      use_curl_cabundle=False, cafile=None, capath=None,
142
                      proxy=None, verify_hostname=False,
143
                      connect_timeout=None, timeout=None,
144
                      _pycurl_version_fn=pycurl.version_info):
145
  """Curl configuration function generator.
146

147
  @type verbose: bool
148
  @param verbose: Whether to set cURL to verbose mode
149
  @type use_signal: bool
150
  @param use_signal: Whether to allow cURL to use signals
151
  @type use_curl_cabundle: bool
152
  @param use_curl_cabundle: Whether to use cURL's default CA bundle
153
  @type cafile: string
154
  @param cafile: In which file we can find the certificates
155
  @type capath: string
156
  @param capath: In which directory we can find the certificates
157
  @type proxy: string
158
  @param proxy: Proxy to use, None for default behaviour and empty string for
159
                disabling proxies (see curl_easy_setopt(3))
160
  @type verify_hostname: bool
161
  @param verify_hostname: Whether to verify the remote peer certificate's
162
                          commonName
163
  @type connect_timeout: number
164
  @param connect_timeout: Timeout for establishing connection in seconds
165
  @type timeout: number
166
  @param timeout: Timeout for complete transfer in seconds (see
167
                  curl_easy_setopt(3)).
168

169
  """
170
  if use_curl_cabundle and (cafile or capath):
171
    raise Error("Can not use default CA bundle when CA file or path is set")
172

    
173
  def _ConfigCurl(curl, logger):
174
    """Configures a cURL object
175

176
    @type curl: pycurl.Curl
177
    @param curl: cURL object
178

179
    """
180
    logger.debug("Using cURL version %s", pycurl.version)
181

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

    
190
    lcsslver = sslver.lower()
191
    if lcsslver.startswith("openssl/"):
192
      pass
193
    elif lcsslver.startswith("gnutls/"):
194
      if capath:
195
        raise Error("cURL linked against GnuTLS has no support for a"
196
                    " CA path (%s)" % (pycurl.version, ))
197
    else:
198
      raise NotImplementedError("cURL uses unsupported SSL version '%s'" %
199
                                sslver)
200

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

    
204
    # Whether to verify remote peer's CN
205
    if verify_hostname:
206
      # curl_easy_setopt(3): "When CURLOPT_SSL_VERIFYHOST is 2, that
207
      # certificate must indicate that the server is the server to which you
208
      # meant to connect, or the connection fails. [...] When the value is 1,
209
      # the certificate must contain a Common Name field, but it doesn't matter
210
      # what name it says. [...]"
211
      curl.setopt(pycurl.SSL_VERIFYHOST, 2)
212
    else:
213
      curl.setopt(pycurl.SSL_VERIFYHOST, 0)
214

    
215
    if cafile or capath or use_curl_cabundle:
216
      # Require certificates to be checked
217
      curl.setopt(pycurl.SSL_VERIFYPEER, True)
218
      if cafile:
219
        curl.setopt(pycurl.CAINFO, str(cafile))
220
      if capath:
221
        curl.setopt(pycurl.CAPATH, str(capath))
222
      # Not changing anything for using default CA bundle
223
    else:
224
      # Disable SSL certificate verification
225
      curl.setopt(pycurl.SSL_VERIFYPEER, False)
226

    
227
    if proxy is not None:
228
      curl.setopt(pycurl.PROXY, str(proxy))
229

    
230
    # Timeouts
231
    if connect_timeout is not None:
232
      curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
233
    if timeout is not None:
234
      curl.setopt(pycurl.TIMEOUT, timeout)
235

    
236
  return _ConfigCurl
237

    
238

    
239
class GanetiRapiClient(object):
240
  """Ganeti RAPI client.
241

242
  """
243
  USER_AGENT = "Ganeti RAPI Client"
244
  _json_encoder = simplejson.JSONEncoder(sort_keys=True)
245

    
246
  def __init__(self, host, port=GANETI_RAPI_PORT,
247
               username=None, password=None, logger=logging,
248
               curl_config_fn=None, curl_factory=None):
249
    """Initializes this class.
250

251
    @type host: string
252
    @param host: the ganeti cluster master to interact with
253
    @type port: int
254
    @param port: the port on which the RAPI is running (default is 5080)
255
    @type username: string
256
    @param username: the username to connect with
257
    @type password: string
258
    @param password: the password to connect with
259
    @type curl_config_fn: callable
260
    @param curl_config_fn: Function to configure C{pycurl.Curl} object
261
    @param logger: Logging object
262

263
    """
264
    self._username = username
265
    self._password = password
266
    self._logger = logger
267
    self._curl_config_fn = curl_config_fn
268
    self._curl_factory = curl_factory
269

    
270
    try:
271
      socket.inet_pton(socket.AF_INET6, host)
272
      address = "[%s]:%s" % (host, port)
273
    except socket.error:
274
      address = "%s:%s" % (host, port)
275

    
276
    self._base_url = "https://%s" % address
277

    
278
    if username is not None:
279
      if password is None:
280
        raise Error("Password not specified")
281
    elif password:
282
      raise Error("Specified password without username")
283

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

287
    """
288
    # Create pycURL object if no factory is provided
289
    if self._curl_factory:
290
      curl = self._curl_factory()
291
    else:
292
      curl = pycurl.Curl()
293

    
294
    # Default cURL settings
295
    curl.setopt(pycurl.VERBOSE, False)
296
    curl.setopt(pycurl.FOLLOWLOCATION, False)
297
    curl.setopt(pycurl.MAXREDIRS, 5)
298
    curl.setopt(pycurl.NOSIGNAL, True)
299
    curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
300
    curl.setopt(pycurl.SSL_VERIFYHOST, 0)
301
    curl.setopt(pycurl.SSL_VERIFYPEER, False)
302
    curl.setopt(pycurl.HTTPHEADER, [
303
      "Accept: %s" % HTTP_APP_JSON,
304
      "Content-type: %s" % HTTP_APP_JSON,
305
      ])
306

    
307
    assert ((self._username is None and self._password is None) ^
308
            (self._username is not None and self._password is not None))
309

    
310
    if self._username:
311
      # Setup authentication
312
      curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
313
      curl.setopt(pycurl.USERPWD,
314
                  str("%s:%s" % (self._username, self._password)))
315

    
316
    # Call external configuration function
317
    if self._curl_config_fn:
318
      self._curl_config_fn(curl, self._logger)
319

    
320
    return curl
321

    
322
  @staticmethod
323
  def _EncodeQuery(query):
324
    """Encode query values for RAPI URL.
325

326
    @type query: list of two-tuples
327
    @param query: Query arguments
328
    @rtype: list
329
    @return: Query list with encoded values
330

331
    """
332
    result = []
333

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

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

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

    
345
      else:
346
        result.append((name, value))
347

    
348
    return result
349

    
350
  def _SendRequest(self, method, path, query, content):
351
    """Sends an HTTP request.
352

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

356
    @type method: string
357
    @param method: HTTP method to use
358
    @type path: string
359
    @param path: HTTP URL path
360
    @type query: list of two-tuples
361
    @param query: query arguments to pass to urllib.urlencode
362
    @type content: str or None
363
    @param content: HTTP body content
364

365
    @rtype: str
366
    @return: JSON-Decoded response
367

368
    @raises CertificateError: If an invalid SSL certificate is found
369
    @raises GanetiApiError: If an invalid response is returned
370

371
    """
372
    assert path.startswith("/")
373

    
374
    curl = self._CreateCurl()
375

    
376
    if content is not None:
377
      encoded_content = self._json_encoder.encode(content)
378
    else:
379
      encoded_content = ""
380

    
381
    # Build URL
382
    urlparts = [self._base_url, path]
383
    if query:
384
      urlparts.append("?")
385
      urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
386

    
387
    url = "".join(urlparts)
388

    
389
    self._logger.debug("Sending request %s %s (content=%r)",
390
                       method, url, encoded_content)
391

    
392
    # Buffer for response
393
    encoded_resp_body = StringIO()
394

    
395
    # Configure cURL
396
    curl.setopt(pycurl.CUSTOMREQUEST, str(method))
397
    curl.setopt(pycurl.URL, str(url))
398
    curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
399
    curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
400

    
401
    try:
402
      # Send request and wait for response
403
      try:
404
        curl.perform()
405
      except pycurl.error, err:
406
        if err.args[0] in _CURL_SSL_CERT_ERRORS:
407
          raise CertificateError("SSL certificate error %s" % err)
408

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

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

    
419
    # Was anything written to the response buffer?
420
    if encoded_resp_body.tell():
421
      response_content = simplejson.loads(encoded_resp_body.getvalue())
422
    else:
423
      response_content = None
424

    
425
    if http_code != HTTP_OK:
426
      if isinstance(response_content, dict):
427
        msg = ("%s %s: %s" %
428
               (response_content["code"],
429
                response_content["message"],
430
                response_content["explain"]))
431
      else:
432
        msg = str(response_content)
433

    
434
      raise GanetiApiError(msg, code=http_code)
435

    
436
    return response_content
437

    
438
  def GetVersion(self):
439
    """Gets the Remote API version running on the cluster.
440

441
    @rtype: int
442
    @return: Ganeti Remote API version
443

444
    """
445
    return self._SendRequest(HTTP_GET, "/version", None, None)
446

    
447
  def GetFeatures(self):
448
    """Gets the list of optional features supported by RAPI server.
449

450
    @rtype: list
451
    @return: List of optional features
452

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

    
462
      raise
463

    
464
  def GetOperatingSystems(self):
465
    """Gets the Operating Systems running in the Ganeti cluster.
466

467
    @rtype: list of str
468
    @return: operating systems
469

470
    """
471
    return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
472
                             None, None)
473

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

477
    @rtype: dict
478
    @return: information about the cluster
479

480
    """
481
    return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
482
                             None, None)
483

    
484
  def GetClusterTags(self):
485
    """Gets the cluster tags.
486

487
    @rtype: list of str
488
    @return: cluster tags
489

490
    """
491
    return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
492
                             None, None)
493

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

497
    @type tags: list of str
498
    @param tags: tags to add to the cluster
499
    @type dry_run: bool
500
    @param dry_run: whether to perform a dry run
501

502
    @rtype: int
503
    @return: job id
504

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

    
510
    return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
511
                             query, None)
512

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

516
    @type tags: list of str
517
    @param tags: tags to delete
518
    @type dry_run: bool
519
    @param dry_run: whether to perform a dry run
520

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

    
526
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
527
                             query, None)
528

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

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

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

538
    """
539
    query = []
540
    if bulk:
541
      query.append(("bulk", 1))
542

    
543
    instances = self._SendRequest(HTTP_GET,
544
                                  "/%s/instances" % GANETI_RAPI_VERSION,
545
                                  query, None)
546
    if bulk:
547
      return instances
548
    else:
549
      return [i["id"] for i in instances]
550

    
551
  def GetInstance(self, instance):
552
    """Gets information about an instance.
553

554
    @type instance: str
555
    @param instance: instance whose info to return
556

557
    @rtype: dict
558
    @return: info about the instance
559

560
    """
561
    return self._SendRequest(HTTP_GET,
562
                             ("/%s/instances/%s" %
563
                              (GANETI_RAPI_VERSION, instance)), None, None)
564

    
565
  def GetInstanceInfo(self, instance, static=None):
566
    """Gets information about an instance.
567

568
    @type instance: string
569
    @param instance: Instance name
570
    @rtype: string
571
    @return: Job ID
572

573
    """
574
    if static is not None:
575
      query = [("static", static)]
576
    else:
577
      query = None
578

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

    
583
  def CreateInstance(self, mode, name, disk_template, disks, nics,
584
                     **kwargs):
585
    """Creates a new instance.
586

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

589
    @type mode: string
590
    @param mode: Instance creation mode
591
    @type name: string
592
    @param name: Hostname of the instance to create
593
    @type disk_template: string
594
    @param disk_template: Disk template for instance (e.g. plain, diskless,
595
                          file, or drbd)
596
    @type disks: list of dicts
597
    @param disks: List of disk definitions
598
    @type nics: list of dicts
599
    @param nics: List of NIC definitions
600
    @type dry_run: bool
601
    @keyword dry_run: whether to perform a dry run
602

603
    @rtype: int
604
    @return: job id
605

606
    """
607
    query = []
608

    
609
    if kwargs.get("dry_run"):
610
      query.append(("dry-run", 1))
611

    
612
    if _INST_CREATE_REQV1 in self.GetFeatures():
613
      # All required fields for request data version 1
614
      body = {
615
        _REQ_DATA_VERSION_FIELD: 1,
616
        "mode": mode,
617
        "name": name,
618
        "disk_template": disk_template,
619
        "disks": disks,
620
        "nics": nics,
621
        }
622

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

    
628
      body.update((key, value) for key, value in kwargs.iteritems()
629
                  if key != "dry_run")
630
    else:
631
      # Old request format (version 0)
632

    
633
      # The following code must make sure that an exception is raised when an
634
      # unsupported setting is requested by the caller. Otherwise this can lead
635
      # to bugs difficult to find. The interface of this function must stay
636
      # exactly the same for version 0 and 1 (e.g. they aren't allowed to
637
      # require different data types).
638

    
639
      # Validate disks
640
      for idx, disk in enumerate(disks):
641
        unsupported = set(disk.keys()) - _INST_CREATE_V0_DISK_PARAMS
642
        if unsupported:
643
          raise GanetiApiError("Server supports request version 0 only, but"
644
                               " disk %s specifies the unsupported parameters"
645
                               " %s, allowed are %s" %
646
                               (idx, unsupported,
647
                                list(_INST_CREATE_V0_DISK_PARAMS)))
648

    
649
      assert (len(_INST_CREATE_V0_DISK_PARAMS) == 1 and
650
              "size" in _INST_CREATE_V0_DISK_PARAMS)
651
      disk_sizes = [disk["size"] for disk in disks]
652

    
653
      # Validate NICs
654
      if not nics:
655
        raise GanetiApiError("Server supports request version 0 only, but"
656
                             " no NIC specified")
657
      elif len(nics) > 1:
658
        raise GanetiApiError("Server supports request version 0 only, but"
659
                             " more than one NIC specified")
660

    
661
      assert len(nics) == 1
662

    
663
      unsupported = set(nics[0].keys()) - _INST_NIC_PARAMS
664
      if unsupported:
665
        raise GanetiApiError("Server supports request version 0 only, but"
666
                             " NIC 0 specifies the unsupported parameters %s,"
667
                             " allowed are %s" %
668
                             (unsupported, list(_INST_NIC_PARAMS)))
669

    
670
      # Validate other parameters
671
      unsupported = (set(kwargs.keys()) - _INST_CREATE_V0_PARAMS -
672
                     _INST_CREATE_V0_DPARAMS)
673
      if unsupported:
674
        allowed = _INST_CREATE_V0_PARAMS.union(_INST_CREATE_V0_DPARAMS)
675
        raise GanetiApiError("Server supports request version 0 only, but"
676
                             " the following unsupported parameters are"
677
                             " specified: %s, allowed are %s" %
678
                             (unsupported, list(allowed)))
679

    
680
      # All required fields for request data version 0
681
      body = {
682
        _REQ_DATA_VERSION_FIELD: 0,
683
        "name": name,
684
        "disk_template": disk_template,
685
        "disks": disk_sizes,
686
        }
687

    
688
      # NIC fields
689
      assert len(nics) == 1
690
      assert not (set(body.keys()) & set(nics[0].keys()))
691
      body.update(nics[0])
692

    
693
      # Copy supported fields
694
      assert not (set(body.keys()) & set(kwargs.keys()))
695
      body.update(dict((key, value) for key, value in kwargs.items()
696
                       if key in _INST_CREATE_V0_PARAMS))
697

    
698
      # Merge dictionaries
699
      for i in (value for key, value in kwargs.items()
700
                if key in _INST_CREATE_V0_DPARAMS):
701
        assert not (set(body.keys()) & set(i.keys()))
702
        body.update(i)
703

    
704
      assert not (set(kwargs.keys()) -
705
                  (_INST_CREATE_V0_PARAMS | _INST_CREATE_V0_DPARAMS))
706
      assert not (set(body.keys()) & _INST_CREATE_V0_DPARAMS)
707

    
708
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
709
                             query, body)
710

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

714
    @type instance: str
715
    @param instance: the instance to delete
716

717
    @rtype: int
718
    @return: job id
719

720
    """
721
    query = []
722
    if dry_run:
723
      query.append(("dry-run", 1))
724

    
725
    return self._SendRequest(HTTP_DELETE,
726
                             ("/%s/instances/%s" %
727
                              (GANETI_RAPI_VERSION, instance)), query, None)
728

    
729
  def ModifyInstance(self, instance, **kwargs):
730
    """Modifies an instance.
731

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

734
    @type instance: string
735
    @param instance: Instance name
736
    @rtype: int
737
    @return: job id
738

739
    """
740
    body = kwargs
741

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

    
746
  def GetInstanceTags(self, instance):
747
    """Gets tags for an instance.
748

749
    @type instance: str
750
    @param instance: instance whose tags to return
751

752
    @rtype: list of str
753
    @return: tags for the instance
754

755
    """
756
    return self._SendRequest(HTTP_GET,
757
                             ("/%s/instances/%s/tags" %
758
                              (GANETI_RAPI_VERSION, instance)), None, None)
759

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

763
    @type instance: str
764
    @param instance: instance to add tags to
765
    @type tags: list of str
766
    @param tags: tags to add to the instance
767
    @type dry_run: bool
768
    @param dry_run: whether to perform a dry run
769

770
    @rtype: int
771
    @return: job id
772

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

    
778
    return self._SendRequest(HTTP_PUT,
779
                             ("/%s/instances/%s/tags" %
780
                              (GANETI_RAPI_VERSION, instance)), query, None)
781

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

785
    @type instance: str
786
    @param instance: instance to delete tags from
787
    @type tags: list of str
788
    @param tags: tags to delete
789
    @type dry_run: bool
790
    @param dry_run: whether to perform a dry run
791

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

    
797
    return self._SendRequest(HTTP_DELETE,
798
                             ("/%s/instances/%s/tags" %
799
                              (GANETI_RAPI_VERSION, instance)), query, None)
800

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

805
    @type instance: str
806
    @param instance: instance to rebot
807
    @type reboot_type: str
808
    @param reboot_type: one of: hard, soft, full
809
    @type ignore_secondaries: bool
810
    @param ignore_secondaries: if True, ignores errors for the secondary node
811
        while re-assembling disks (in hard-reboot mode only)
812
    @type dry_run: bool
813
    @param dry_run: whether to perform a dry run
814

815
    """
816
    query = []
817
    if reboot_type:
818
      query.append(("type", reboot_type))
819
    if ignore_secondaries is not None:
820
      query.append(("ignore_secondaries", ignore_secondaries))
821
    if dry_run:
822
      query.append(("dry-run", 1))
823

    
824
    return self._SendRequest(HTTP_POST,
825
                             ("/%s/instances/%s/reboot" %
826
                              (GANETI_RAPI_VERSION, instance)), query, None)
827

    
828
  def ShutdownInstance(self, instance, dry_run=False):
829
    """Shuts down an instance.
830

831
    @type instance: str
832
    @param instance: the instance to shut down
833
    @type dry_run: bool
834
    @param dry_run: whether to perform a dry run
835

836
    """
837
    query = []
838
    if dry_run:
839
      query.append(("dry-run", 1))
840

    
841
    return self._SendRequest(HTTP_PUT,
842
                             ("/%s/instances/%s/shutdown" %
843
                              (GANETI_RAPI_VERSION, instance)), query, None)
844

    
845
  def StartupInstance(self, instance, dry_run=False):
846
    """Starts up an instance.
847

848
    @type instance: str
849
    @param instance: the instance to start up
850
    @type dry_run: bool
851
    @param dry_run: whether to perform a dry run
852

853
    """
854
    query = []
855
    if dry_run:
856
      query.append(("dry-run", 1))
857

    
858
    return self._SendRequest(HTTP_PUT,
859
                             ("/%s/instances/%s/startup" %
860
                              (GANETI_RAPI_VERSION, instance)), query, None)
861

    
862
  def ReinstallInstance(self, instance, os=None, no_startup=False,
863
                        osparams=None):
864
    """Reinstalls an instance.
865

866
    @type instance: str
867
    @param instance: The instance to reinstall
868
    @type os: str or None
869
    @param os: The operating system to reinstall. If None, the instance's
870
        current operating system will be installed again
871
    @type no_startup: bool
872
    @param no_startup: Whether to start the instance automatically
873

874
    """
875
    if _INST_REINSTALL_REQV1 in self.GetFeatures():
876
      body = {
877
        "start": not no_startup,
878
        }
879
      if os is not None:
880
        body["os"] = os
881
      if osparams is not None:
882
        body["osparams"] = osparams
883
      return self._SendRequest(HTTP_POST,
884
                               ("/%s/instances/%s/reinstall" %
885
                                (GANETI_RAPI_VERSION, instance)), None, body)
886

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

    
892
    query = []
893
    if os:
894
      query.append(("os", os))
895
    if no_startup:
896
      query.append(("nostartup", 1))
897
    return self._SendRequest(HTTP_POST,
898
                             ("/%s/instances/%s/reinstall" %
899
                              (GANETI_RAPI_VERSION, instance)), query, None)
900

    
901
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
902
                           remote_node=None, iallocator=None, dry_run=False):
903
    """Replaces disks on an instance.
904

905
    @type instance: str
906
    @param instance: instance whose disks to replace
907
    @type disks: list of ints
908
    @param disks: Indexes of disks to replace
909
    @type mode: str
910
    @param mode: replacement mode to use (defaults to replace_auto)
911
    @type remote_node: str or None
912
    @param remote_node: new secondary node to use (for use with
913
        replace_new_secondary mode)
914
    @type iallocator: str or None
915
    @param iallocator: instance allocator plugin to use (for use with
916
                       replace_auto mode)
917
    @type dry_run: bool
918
    @param dry_run: whether to perform a dry run
919

920
    @rtype: int
921
    @return: job id
922

923
    """
924
    query = [
925
      ("mode", mode),
926
      ]
927

    
928
    if disks:
929
      query.append(("disks", ",".join(str(idx) for idx in disks)))
930

    
931
    if remote_node:
932
      query.append(("remote_node", remote_node))
933

    
934
    if iallocator:
935
      query.append(("iallocator", iallocator))
936

    
937
    if dry_run:
938
      query.append(("dry-run", 1))
939

    
940
    return self._SendRequest(HTTP_POST,
941
                             ("/%s/instances/%s/replace-disks" %
942
                              (GANETI_RAPI_VERSION, instance)), query, None)
943

    
944
  def PrepareExport(self, instance, mode):
945
    """Prepares an instance for an export.
946

947
    @type instance: string
948
    @param instance: Instance name
949
    @type mode: string
950
    @param mode: Export mode
951
    @rtype: string
952
    @return: Job ID
953

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

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

965
    @type instance: string
966
    @param instance: Instance name
967
    @type mode: string
968
    @param mode: Export mode
969
    @rtype: string
970
    @return: Job ID
971

972
    """
973
    body = {
974
      "destination": destination,
975
      "mode": mode,
976
      }
977

    
978
    if shutdown is not None:
979
      body["shutdown"] = shutdown
980

    
981
    if remove_instance is not None:
982
      body["remove_instance"] = remove_instance
983

    
984
    if x509_key_name is not None:
985
      body["x509_key_name"] = x509_key_name
986

    
987
    if destination_x509_ca is not None:
988
      body["destination_x509_ca"] = destination_x509_ca
989

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

    
994
  def MigrateInstance(self, instance, mode=None, cleanup=None):
995
    """Migrates an instance.
996

997
    @type instance: string
998
    @param instance: Instance name
999
    @type mode: string
1000
    @param mode: Migration mode
1001
    @type cleanup: bool
1002
    @param cleanup: Whether to clean up a previously failed migration
1003

1004
    """
1005
    body = {}
1006

    
1007
    if mode is not None:
1008
      body["mode"] = mode
1009

    
1010
    if cleanup is not None:
1011
      body["cleanup"] = cleanup
1012

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

    
1017
  def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
1018
    """Changes the name of an instance.
1019

1020
    @type instance: string
1021
    @param instance: Instance name
1022
    @type new_name: string
1023
    @param new_name: New instance name
1024
    @type ip_check: bool
1025
    @param ip_check: Whether to ensure instance's IP address is inactive
1026
    @type name_check: bool
1027
    @param name_check: Whether to ensure instance's name is resolvable
1028

1029
    """
1030
    body = {
1031
      "new_name": new_name,
1032
      }
1033

    
1034
    if ip_check is not None:
1035
      body["ip_check"] = ip_check
1036

    
1037
    if name_check is not None:
1038
      body["name_check"] = name_check
1039

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

    
1044
  def GetJobs(self):
1045
    """Gets all jobs for the cluster.
1046

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

1050
    """
1051
    return [int(j["id"])
1052
            for j in self._SendRequest(HTTP_GET,
1053
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1054
                                       None, None)]
1055

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

1059
    @type job_id: int
1060
    @param job_id: job id whose status to query
1061

1062
    @rtype: dict
1063
    @return: job status
1064

1065
    """
1066
    return self._SendRequest(HTTP_GET,
1067
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1068
                             None, None)
1069

    
1070
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1071
    """Waits for job changes.
1072

1073
    @type job_id: int
1074
    @param job_id: Job ID for which to wait
1075

1076
    """
1077
    body = {
1078
      "fields": fields,
1079
      "previous_job_info": prev_job_info,
1080
      "previous_log_serial": prev_log_serial,
1081
      }
1082

    
1083
    return self._SendRequest(HTTP_GET,
1084
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1085
                             None, body)
1086

    
1087
  def CancelJob(self, job_id, dry_run=False):
1088
    """Cancels a job.
1089

1090
    @type job_id: int
1091
    @param job_id: id of the job to delete
1092
    @type dry_run: bool
1093
    @param dry_run: whether to perform a dry run
1094

1095
    """
1096
    query = []
1097
    if dry_run:
1098
      query.append(("dry-run", 1))
1099

    
1100
    return self._SendRequest(HTTP_DELETE,
1101
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1102
                             query, None)
1103

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

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

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

1114
    """
1115
    query = []
1116
    if bulk:
1117
      query.append(("bulk", 1))
1118

    
1119
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1120
                              query, None)
1121
    if bulk:
1122
      return nodes
1123
    else:
1124
      return [n["id"] for n in nodes]
1125

    
1126
  def GetNode(self, node):
1127
    """Gets information about a node.
1128

1129
    @type node: str
1130
    @param node: node whose info to return
1131

1132
    @rtype: dict
1133
    @return: info about the node
1134

1135
    """
1136
    return self._SendRequest(HTTP_GET,
1137
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1138
                             None, None)
1139

    
1140
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1141
                   dry_run=False, early_release=False):
1142
    """Evacuates instances from a Ganeti node.
1143

1144
    @type node: str
1145
    @param node: node to evacuate
1146
    @type iallocator: str or None
1147
    @param iallocator: instance allocator to use
1148
    @type remote_node: str
1149
    @param remote_node: node to evaucate to
1150
    @type dry_run: bool
1151
    @param dry_run: whether to perform a dry run
1152
    @type early_release: bool
1153
    @param early_release: whether to enable parallelization
1154

1155
    @rtype: list
1156
    @return: list of (job ID, instance name, new secondary node); if
1157
        dry_run was specified, then the actual move jobs were not
1158
        submitted and the job IDs will be C{None}
1159

1160
    @raises GanetiApiError: if an iallocator and remote_node are both
1161
        specified
1162

1163
    """
1164
    if iallocator and remote_node:
1165
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1166

    
1167
    query = []
1168
    if iallocator:
1169
      query.append(("iallocator", iallocator))
1170
    if remote_node:
1171
      query.append(("remote_node", remote_node))
1172
    if dry_run:
1173
      query.append(("dry-run", 1))
1174
    if early_release:
1175
      query.append(("early_release", 1))
1176

    
1177
    return self._SendRequest(HTTP_POST,
1178
                             ("/%s/nodes/%s/evacuate" %
1179
                              (GANETI_RAPI_VERSION, node)), query, None)
1180

    
1181
  def MigrateNode(self, node, mode=None, dry_run=False):
1182
    """Migrates all primary instances from a node.
1183

1184
    @type node: str
1185
    @param node: node to migrate
1186
    @type mode: string
1187
    @param mode: if passed, it will overwrite the live migration type,
1188
        otherwise the hypervisor default will be used
1189
    @type dry_run: bool
1190
    @param dry_run: whether to perform a dry run
1191

1192
    @rtype: int
1193
    @return: job id
1194

1195
    """
1196
    query = []
1197
    if mode is not None:
1198
      query.append(("mode", mode))
1199
    if dry_run:
1200
      query.append(("dry-run", 1))
1201

    
1202
    return self._SendRequest(HTTP_POST,
1203
                             ("/%s/nodes/%s/migrate" %
1204
                              (GANETI_RAPI_VERSION, node)), query, None)
1205

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

1209
    @type node: str
1210
    @param node: node whose role to return
1211

1212
    @rtype: str
1213
    @return: the current role for a node
1214

1215
    """
1216
    return self._SendRequest(HTTP_GET,
1217
                             ("/%s/nodes/%s/role" %
1218
                              (GANETI_RAPI_VERSION, node)), None, None)
1219

    
1220
  def SetNodeRole(self, node, role, force=False):
1221
    """Sets the role for a node.
1222

1223
    @type node: str
1224
    @param node: the node whose role to set
1225
    @type role: str
1226
    @param role: the role to set for the node
1227
    @type force: bool
1228
    @param force: whether to force the role change
1229

1230
    @rtype: int
1231
    @return: job id
1232

1233
    """
1234
    query = [
1235
      ("force", force),
1236
      ]
1237

    
1238
    return self._SendRequest(HTTP_PUT,
1239
                             ("/%s/nodes/%s/role" %
1240
                              (GANETI_RAPI_VERSION, node)), query, role)
1241

    
1242
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1243
    """Gets the storage units for a node.
1244

1245
    @type node: str
1246
    @param node: the node whose storage units to return
1247
    @type storage_type: str
1248
    @param storage_type: storage type whose units to return
1249
    @type output_fields: str
1250
    @param output_fields: storage type fields to return
1251

1252
    @rtype: int
1253
    @return: job id where results can be retrieved
1254

1255
    """
1256
    query = [
1257
      ("storage_type", storage_type),
1258
      ("output_fields", output_fields),
1259
      ]
1260

    
1261
    return self._SendRequest(HTTP_GET,
1262
                             ("/%s/nodes/%s/storage" %
1263
                              (GANETI_RAPI_VERSION, node)), query, None)
1264

    
1265
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1266
    """Modifies parameters of storage units on the node.
1267

1268
    @type node: str
1269
    @param node: node whose storage units to modify
1270
    @type storage_type: str
1271
    @param storage_type: storage type whose units to modify
1272
    @type name: str
1273
    @param name: name of the storage unit
1274
    @type allocatable: bool or None
1275
    @param allocatable: Whether to set the "allocatable" flag on the storage
1276
                        unit (None=no modification, True=set, False=unset)
1277

1278
    @rtype: int
1279
    @return: job id
1280

1281
    """
1282
    query = [
1283
      ("storage_type", storage_type),
1284
      ("name", name),
1285
      ]
1286

    
1287
    if allocatable is not None:
1288
      query.append(("allocatable", allocatable))
1289

    
1290
    return self._SendRequest(HTTP_PUT,
1291
                             ("/%s/nodes/%s/storage/modify" %
1292
                              (GANETI_RAPI_VERSION, node)), query, None)
1293

    
1294
  def RepairNodeStorageUnits(self, node, storage_type, name):
1295
    """Repairs a storage unit on the node.
1296

1297
    @type node: str
1298
    @param node: node whose storage units to repair
1299
    @type storage_type: str
1300
    @param storage_type: storage type to repair
1301
    @type name: str
1302
    @param name: name of the storage unit to repair
1303

1304
    @rtype: int
1305
    @return: job id
1306

1307
    """
1308
    query = [
1309
      ("storage_type", storage_type),
1310
      ("name", name),
1311
      ]
1312

    
1313
    return self._SendRequest(HTTP_PUT,
1314
                             ("/%s/nodes/%s/storage/repair" %
1315
                              (GANETI_RAPI_VERSION, node)), query, None)
1316

    
1317
  def GetNodeTags(self, node):
1318
    """Gets the tags for a node.
1319

1320
    @type node: str
1321
    @param node: node whose tags to return
1322

1323
    @rtype: list of str
1324
    @return: tags for the node
1325

1326
    """
1327
    return self._SendRequest(HTTP_GET,
1328
                             ("/%s/nodes/%s/tags" %
1329
                              (GANETI_RAPI_VERSION, node)), None, None)
1330

    
1331
  def AddNodeTags(self, node, tags, dry_run=False):
1332
    """Adds tags to a node.
1333

1334
    @type node: str
1335
    @param node: node to add tags to
1336
    @type tags: list of str
1337
    @param tags: tags to add to the node
1338
    @type dry_run: bool
1339
    @param dry_run: whether to perform a dry run
1340

1341
    @rtype: int
1342
    @return: job id
1343

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

    
1349
    return self._SendRequest(HTTP_PUT,
1350
                             ("/%s/nodes/%s/tags" %
1351
                              (GANETI_RAPI_VERSION, node)), query, tags)
1352

    
1353
  def DeleteNodeTags(self, node, tags, dry_run=False):
1354
    """Delete tags from a node.
1355

1356
    @type node: str
1357
    @param node: node to remove tags from
1358
    @type tags: list of str
1359
    @param tags: tags to remove from the node
1360
    @type dry_run: bool
1361
    @param dry_run: whether to perform a dry run
1362

1363
    @rtype: int
1364
    @return: job id
1365

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

    
1371
    return self._SendRequest(HTTP_DELETE,
1372
                             ("/%s/nodes/%s/tags" %
1373
                              (GANETI_RAPI_VERSION, node)), query, None)
1374

    
1375
  def GetGroups(self, bulk=False):
1376
    """Gets all node groups in the cluster.
1377

1378
    @type bulk: bool
1379
    @param bulk: whether to return all information about the groups
1380

1381
    @rtype: list of dict or str
1382
    @return: if bulk is true, a list of dictionaries with info about all node
1383
        groups in the cluster, else a list of names of those node groups
1384

1385
    """
1386
    query = []
1387
    if bulk:
1388
      query.append(("bulk", 1))
1389

    
1390
    groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1391
                               query, None)
1392
    if bulk:
1393
      return groups
1394
    else:
1395
      return [g["name"] for g in groups]
1396

    
1397
  def GetGroup(self, group):
1398
    """Gets information about a node group.
1399

1400
    @type group: str
1401
    @param group: name of the node group whose info to return
1402

1403
    @rtype: dict
1404
    @return: info about the node group
1405

1406
    """
1407
    return self._SendRequest(HTTP_GET,
1408
                             "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
1409
                             None, None)
1410

    
1411
  def CreateGroup(self, name, dry_run=False):
1412
    """Creates a new node group.
1413

1414
    @type name: str
1415
    @param name: the name of node group to create
1416
    @type dry_run: bool
1417
    @param dry_run: whether to peform a dry run
1418

1419
    @rtype: int
1420
    @return: job id
1421

1422
    """
1423
    query = []
1424
    if dry_run:
1425
      query.append(("dry-run", 1))
1426

    
1427
    body = {
1428
      "name": name,
1429
      }
1430

    
1431
    return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1432
                             query, body)
1433

    
1434
  def DeleteGroup(self, group, dry_run=False):
1435
    """Deletes a node group.
1436

1437
    @type group: str
1438
    @param group: the node group to delete
1439
    @type dry_run: bool
1440
    @param dry_run: whether to peform a dry run
1441

1442
    @rtype: int
1443
    @return: job id
1444

1445
    """
1446
    query = []
1447
    if dry_run:
1448
      query.append(("dry-run", 1))
1449

    
1450
    return self._SendRequest(HTTP_DELETE,
1451
                             ("/%s/groups/%s" %
1452
                              (GANETI_RAPI_VERSION, group)), query, None)
1453

    
1454
  def RenameGroup(self, group, new_name):
1455
    """Changes the name of a node group.
1456

1457
    @type group: string
1458
    @param group: Node group name
1459
    @type new_name: string
1460
    @param new_name: New node group name
1461

1462
    @rtype: int
1463
    @return: job id
1464

1465
    """
1466
    body = {
1467
      "new_name": new_name,
1468
      }
1469

    
1470
    return self._SendRequest(HTTP_PUT,
1471
                             ("/%s/groups/%s/rename" %
1472
                              (GANETI_RAPI_VERSION, group)), None, body)