Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ 62e999a5

History | View | Annotate | Download (43.5 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 ModifyCluster(self, **kwargs):
485
    """Modifies cluster parameters.
486

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

489
    @rtype: int
490
    @return: job id
491

492
    """
493
    body = kwargs
494

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

    
498
  def GetClusterTags(self):
499
    """Gets the cluster tags.
500

501
    @rtype: list of str
502
    @return: cluster tags
503

504
    """
505
    return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
506
                             None, None)
507

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

511
    @type tags: list of str
512
    @param tags: tags to add to the cluster
513
    @type dry_run: bool
514
    @param dry_run: whether to perform a dry run
515

516
    @rtype: int
517
    @return: job id
518

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

    
524
    return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
525
                             query, None)
526

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

530
    @type tags: list of str
531
    @param tags: tags to delete
532
    @type dry_run: bool
533
    @param dry_run: whether to perform a dry run
534

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

    
540
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
541
                             query, None)
542

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

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

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

552
    """
553
    query = []
554
    if bulk:
555
      query.append(("bulk", 1))
556

    
557
    instances = self._SendRequest(HTTP_GET,
558
                                  "/%s/instances" % GANETI_RAPI_VERSION,
559
                                  query, None)
560
    if bulk:
561
      return instances
562
    else:
563
      return [i["id"] for i in instances]
564

    
565
  def GetInstance(self, instance):
566
    """Gets information about an instance.
567

568
    @type instance: str
569
    @param instance: instance whose info to return
570

571
    @rtype: dict
572
    @return: info about the instance
573

574
    """
575
    return self._SendRequest(HTTP_GET,
576
                             ("/%s/instances/%s" %
577
                              (GANETI_RAPI_VERSION, instance)), None, None)
578

    
579
  def GetInstanceInfo(self, instance, static=None):
580
    """Gets information about an instance.
581

582
    @type instance: string
583
    @param instance: Instance name
584
    @rtype: string
585
    @return: Job ID
586

587
    """
588
    if static is not None:
589
      query = [("static", static)]
590
    else:
591
      query = None
592

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

    
597
  def CreateInstance(self, mode, name, disk_template, disks, nics,
598
                     **kwargs):
599
    """Creates a new instance.
600

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

603
    @type mode: string
604
    @param mode: Instance creation mode
605
    @type name: string
606
    @param name: Hostname of the instance to create
607
    @type disk_template: string
608
    @param disk_template: Disk template for instance (e.g. plain, diskless,
609
                          file, or drbd)
610
    @type disks: list of dicts
611
    @param disks: List of disk definitions
612
    @type nics: list of dicts
613
    @param nics: List of NIC definitions
614
    @type dry_run: bool
615
    @keyword dry_run: whether to perform a dry run
616

617
    @rtype: int
618
    @return: job id
619

620
    """
621
    query = []
622

    
623
    if kwargs.get("dry_run"):
624
      query.append(("dry-run", 1))
625

    
626
    if _INST_CREATE_REQV1 in self.GetFeatures():
627
      # All required fields for request data version 1
628
      body = {
629
        _REQ_DATA_VERSION_FIELD: 1,
630
        "mode": mode,
631
        "name": name,
632
        "disk_template": disk_template,
633
        "disks": disks,
634
        "nics": nics,
635
        }
636

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

    
642
      body.update((key, value) for key, value in kwargs.iteritems()
643
                  if key != "dry_run")
644
    else:
645
      # Old request format (version 0)
646

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

    
653
      # Validate disks
654
      for idx, disk in enumerate(disks):
655
        unsupported = set(disk.keys()) - _INST_CREATE_V0_DISK_PARAMS
656
        if unsupported:
657
          raise GanetiApiError("Server supports request version 0 only, but"
658
                               " disk %s specifies the unsupported parameters"
659
                               " %s, allowed are %s" %
660
                               (idx, unsupported,
661
                                list(_INST_CREATE_V0_DISK_PARAMS)))
662

    
663
      assert (len(_INST_CREATE_V0_DISK_PARAMS) == 1 and
664
              "size" in _INST_CREATE_V0_DISK_PARAMS)
665
      disk_sizes = [disk["size"] for disk in disks]
666

    
667
      # Validate NICs
668
      if not nics:
669
        raise GanetiApiError("Server supports request version 0 only, but"
670
                             " no NIC specified")
671
      elif len(nics) > 1:
672
        raise GanetiApiError("Server supports request version 0 only, but"
673
                             " more than one NIC specified")
674

    
675
      assert len(nics) == 1
676

    
677
      unsupported = set(nics[0].keys()) - _INST_NIC_PARAMS
678
      if unsupported:
679
        raise GanetiApiError("Server supports request version 0 only, but"
680
                             " NIC 0 specifies the unsupported parameters %s,"
681
                             " allowed are %s" %
682
                             (unsupported, list(_INST_NIC_PARAMS)))
683

    
684
      # Validate other parameters
685
      unsupported = (set(kwargs.keys()) - _INST_CREATE_V0_PARAMS -
686
                     _INST_CREATE_V0_DPARAMS)
687
      if unsupported:
688
        allowed = _INST_CREATE_V0_PARAMS.union(_INST_CREATE_V0_DPARAMS)
689
        raise GanetiApiError("Server supports request version 0 only, but"
690
                             " the following unsupported parameters are"
691
                             " specified: %s, allowed are %s" %
692
                             (unsupported, list(allowed)))
693

    
694
      # All required fields for request data version 0
695
      body = {
696
        _REQ_DATA_VERSION_FIELD: 0,
697
        "name": name,
698
        "disk_template": disk_template,
699
        "disks": disk_sizes,
700
        }
701

    
702
      # NIC fields
703
      assert len(nics) == 1
704
      assert not (set(body.keys()) & set(nics[0].keys()))
705
      body.update(nics[0])
706

    
707
      # Copy supported fields
708
      assert not (set(body.keys()) & set(kwargs.keys()))
709
      body.update(dict((key, value) for key, value in kwargs.items()
710
                       if key in _INST_CREATE_V0_PARAMS))
711

    
712
      # Merge dictionaries
713
      for i in (value for key, value in kwargs.items()
714
                if key in _INST_CREATE_V0_DPARAMS):
715
        assert not (set(body.keys()) & set(i.keys()))
716
        body.update(i)
717

    
718
      assert not (set(kwargs.keys()) -
719
                  (_INST_CREATE_V0_PARAMS | _INST_CREATE_V0_DPARAMS))
720
      assert not (set(body.keys()) & _INST_CREATE_V0_DPARAMS)
721

    
722
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
723
                             query, body)
724

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

728
    @type instance: str
729
    @param instance: the instance to delete
730

731
    @rtype: int
732
    @return: job id
733

734
    """
735
    query = []
736
    if dry_run:
737
      query.append(("dry-run", 1))
738

    
739
    return self._SendRequest(HTTP_DELETE,
740
                             ("/%s/instances/%s" %
741
                              (GANETI_RAPI_VERSION, instance)), query, None)
742

    
743
  def ModifyInstance(self, instance, **kwargs):
744
    """Modifies an instance.
745

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

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

753
    """
754
    body = kwargs
755

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

    
760
  def GetInstanceTags(self, instance):
761
    """Gets tags for an instance.
762

763
    @type instance: str
764
    @param instance: instance whose tags to return
765

766
    @rtype: list of str
767
    @return: tags for the instance
768

769
    """
770
    return self._SendRequest(HTTP_GET,
771
                             ("/%s/instances/%s/tags" %
772
                              (GANETI_RAPI_VERSION, instance)), None, None)
773

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

777
    @type instance: str
778
    @param instance: instance to add tags to
779
    @type tags: list of str
780
    @param tags: tags to add to the instance
781
    @type dry_run: bool
782
    @param dry_run: whether to perform a dry run
783

784
    @rtype: int
785
    @return: job id
786

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

    
792
    return self._SendRequest(HTTP_PUT,
793
                             ("/%s/instances/%s/tags" %
794
                              (GANETI_RAPI_VERSION, instance)), query, None)
795

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

799
    @type instance: str
800
    @param instance: instance to delete tags from
801
    @type tags: list of str
802
    @param tags: tags to delete
803
    @type dry_run: bool
804
    @param dry_run: whether to perform a dry run
805

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

    
811
    return self._SendRequest(HTTP_DELETE,
812
                             ("/%s/instances/%s/tags" %
813
                              (GANETI_RAPI_VERSION, instance)), query, None)
814

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

819
    @type instance: str
820
    @param instance: instance to rebot
821
    @type reboot_type: str
822
    @param reboot_type: one of: hard, soft, full
823
    @type ignore_secondaries: bool
824
    @param ignore_secondaries: if True, ignores errors for the secondary node
825
        while re-assembling disks (in hard-reboot mode only)
826
    @type dry_run: bool
827
    @param dry_run: whether to perform a dry run
828

829
    """
830
    query = []
831
    if reboot_type:
832
      query.append(("type", reboot_type))
833
    if ignore_secondaries is not None:
834
      query.append(("ignore_secondaries", ignore_secondaries))
835
    if dry_run:
836
      query.append(("dry-run", 1))
837

    
838
    return self._SendRequest(HTTP_POST,
839
                             ("/%s/instances/%s/reboot" %
840
                              (GANETI_RAPI_VERSION, instance)), query, None)
841

    
842
  def ShutdownInstance(self, instance, dry_run=False):
843
    """Shuts down an instance.
844

845
    @type instance: str
846
    @param instance: the instance to shut down
847
    @type dry_run: bool
848
    @param dry_run: whether to perform a dry run
849

850
    """
851
    query = []
852
    if dry_run:
853
      query.append(("dry-run", 1))
854

    
855
    return self._SendRequest(HTTP_PUT,
856
                             ("/%s/instances/%s/shutdown" %
857
                              (GANETI_RAPI_VERSION, instance)), query, None)
858

    
859
  def StartupInstance(self, instance, dry_run=False):
860
    """Starts up an instance.
861

862
    @type instance: str
863
    @param instance: the instance to start up
864
    @type dry_run: bool
865
    @param dry_run: whether to perform a dry run
866

867
    """
868
    query = []
869
    if dry_run:
870
      query.append(("dry-run", 1))
871

    
872
    return self._SendRequest(HTTP_PUT,
873
                             ("/%s/instances/%s/startup" %
874
                              (GANETI_RAPI_VERSION, instance)), query, None)
875

    
876
  def ReinstallInstance(self, instance, os=None, no_startup=False,
877
                        osparams=None):
878
    """Reinstalls an instance.
879

880
    @type instance: str
881
    @param instance: The instance to reinstall
882
    @type os: str or None
883
    @param os: The operating system to reinstall. If None, the instance's
884
        current operating system will be installed again
885
    @type no_startup: bool
886
    @param no_startup: Whether to start the instance automatically
887

888
    """
889
    if _INST_REINSTALL_REQV1 in self.GetFeatures():
890
      body = {
891
        "start": not no_startup,
892
        }
893
      if os is not None:
894
        body["os"] = os
895
      if osparams is not None:
896
        body["osparams"] = osparams
897
      return self._SendRequest(HTTP_POST,
898
                               ("/%s/instances/%s/reinstall" %
899
                                (GANETI_RAPI_VERSION, instance)), None, body)
900

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

    
906
    query = []
907
    if os:
908
      query.append(("os", os))
909
    if no_startup:
910
      query.append(("nostartup", 1))
911
    return self._SendRequest(HTTP_POST,
912
                             ("/%s/instances/%s/reinstall" %
913
                              (GANETI_RAPI_VERSION, instance)), query, None)
914

    
915
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
916
                           remote_node=None, iallocator=None, dry_run=False):
917
    """Replaces disks on an instance.
918

919
    @type instance: str
920
    @param instance: instance whose disks to replace
921
    @type disks: list of ints
922
    @param disks: Indexes of disks to replace
923
    @type mode: str
924
    @param mode: replacement mode to use (defaults to replace_auto)
925
    @type remote_node: str or None
926
    @param remote_node: new secondary node to use (for use with
927
        replace_new_secondary mode)
928
    @type iallocator: str or None
929
    @param iallocator: instance allocator plugin to use (for use with
930
                       replace_auto mode)
931
    @type dry_run: bool
932
    @param dry_run: whether to perform a dry run
933

934
    @rtype: int
935
    @return: job id
936

937
    """
938
    query = [
939
      ("mode", mode),
940
      ]
941

    
942
    if disks:
943
      query.append(("disks", ",".join(str(idx) for idx in disks)))
944

    
945
    if remote_node:
946
      query.append(("remote_node", remote_node))
947

    
948
    if iallocator:
949
      query.append(("iallocator", iallocator))
950

    
951
    if dry_run:
952
      query.append(("dry-run", 1))
953

    
954
    return self._SendRequest(HTTP_POST,
955
                             ("/%s/instances/%s/replace-disks" %
956
                              (GANETI_RAPI_VERSION, instance)), query, None)
957

    
958
  def PrepareExport(self, instance, mode):
959
    """Prepares an instance for an export.
960

961
    @type instance: string
962
    @param instance: Instance name
963
    @type mode: string
964
    @param mode: Export mode
965
    @rtype: string
966
    @return: Job ID
967

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

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

979
    @type instance: string
980
    @param instance: Instance name
981
    @type mode: string
982
    @param mode: Export mode
983
    @rtype: string
984
    @return: Job ID
985

986
    """
987
    body = {
988
      "destination": destination,
989
      "mode": mode,
990
      }
991

    
992
    if shutdown is not None:
993
      body["shutdown"] = shutdown
994

    
995
    if remove_instance is not None:
996
      body["remove_instance"] = remove_instance
997

    
998
    if x509_key_name is not None:
999
      body["x509_key_name"] = x509_key_name
1000

    
1001
    if destination_x509_ca is not None:
1002
      body["destination_x509_ca"] = destination_x509_ca
1003

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

    
1008
  def MigrateInstance(self, instance, mode=None, cleanup=None):
1009
    """Migrates an instance.
1010

1011
    @type instance: string
1012
    @param instance: Instance name
1013
    @type mode: string
1014
    @param mode: Migration mode
1015
    @type cleanup: bool
1016
    @param cleanup: Whether to clean up a previously failed migration
1017

1018
    """
1019
    body = {}
1020

    
1021
    if mode is not None:
1022
      body["mode"] = mode
1023

    
1024
    if cleanup is not None:
1025
      body["cleanup"] = cleanup
1026

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

    
1031
  def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
1032
    """Changes the name of an instance.
1033

1034
    @type instance: string
1035
    @param instance: Instance name
1036
    @type new_name: string
1037
    @param new_name: New instance name
1038
    @type ip_check: bool
1039
    @param ip_check: Whether to ensure instance's IP address is inactive
1040
    @type name_check: bool
1041
    @param name_check: Whether to ensure instance's name is resolvable
1042

1043
    """
1044
    body = {
1045
      "new_name": new_name,
1046
      }
1047

    
1048
    if ip_check is not None:
1049
      body["ip_check"] = ip_check
1050

    
1051
    if name_check is not None:
1052
      body["name_check"] = name_check
1053

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

    
1058
  def GetJobs(self):
1059
    """Gets all jobs for the cluster.
1060

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

1064
    """
1065
    return [int(j["id"])
1066
            for j in self._SendRequest(HTTP_GET,
1067
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1068
                                       None, None)]
1069

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

1073
    @type job_id: int
1074
    @param job_id: job id whose status to query
1075

1076
    @rtype: dict
1077
    @return: job status
1078

1079
    """
1080
    return self._SendRequest(HTTP_GET,
1081
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1082
                             None, None)
1083

    
1084
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1085
    """Waits for job changes.
1086

1087
    @type job_id: int
1088
    @param job_id: Job ID for which to wait
1089

1090
    """
1091
    body = {
1092
      "fields": fields,
1093
      "previous_job_info": prev_job_info,
1094
      "previous_log_serial": prev_log_serial,
1095
      }
1096

    
1097
    return self._SendRequest(HTTP_GET,
1098
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1099
                             None, body)
1100

    
1101
  def CancelJob(self, job_id, dry_run=False):
1102
    """Cancels a job.
1103

1104
    @type job_id: int
1105
    @param job_id: id of the job to delete
1106
    @type dry_run: bool
1107
    @param dry_run: whether to perform a dry run
1108

1109
    """
1110
    query = []
1111
    if dry_run:
1112
      query.append(("dry-run", 1))
1113

    
1114
    return self._SendRequest(HTTP_DELETE,
1115
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1116
                             query, None)
1117

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

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

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

1128
    """
1129
    query = []
1130
    if bulk:
1131
      query.append(("bulk", 1))
1132

    
1133
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1134
                              query, None)
1135
    if bulk:
1136
      return nodes
1137
    else:
1138
      return [n["id"] for n in nodes]
1139

    
1140
  def GetNode(self, node):
1141
    """Gets information about a node.
1142

1143
    @type node: str
1144
    @param node: node whose info to return
1145

1146
    @rtype: dict
1147
    @return: info about the node
1148

1149
    """
1150
    return self._SendRequest(HTTP_GET,
1151
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1152
                             None, None)
1153

    
1154
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1155
                   dry_run=False, early_release=False):
1156
    """Evacuates instances from a Ganeti node.
1157

1158
    @type node: str
1159
    @param node: node to evacuate
1160
    @type iallocator: str or None
1161
    @param iallocator: instance allocator to use
1162
    @type remote_node: str
1163
    @param remote_node: node to evaucate to
1164
    @type dry_run: bool
1165
    @param dry_run: whether to perform a dry run
1166
    @type early_release: bool
1167
    @param early_release: whether to enable parallelization
1168

1169
    @rtype: list
1170
    @return: list of (job ID, instance name, new secondary node); if
1171
        dry_run was specified, then the actual move jobs were not
1172
        submitted and the job IDs will be C{None}
1173

1174
    @raises GanetiApiError: if an iallocator and remote_node are both
1175
        specified
1176

1177
    """
1178
    if iallocator and remote_node:
1179
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1180

    
1181
    query = []
1182
    if iallocator:
1183
      query.append(("iallocator", iallocator))
1184
    if remote_node:
1185
      query.append(("remote_node", remote_node))
1186
    if dry_run:
1187
      query.append(("dry-run", 1))
1188
    if early_release:
1189
      query.append(("early_release", 1))
1190

    
1191
    return self._SendRequest(HTTP_POST,
1192
                             ("/%s/nodes/%s/evacuate" %
1193
                              (GANETI_RAPI_VERSION, node)), query, None)
1194

    
1195
  def MigrateNode(self, node, mode=None, dry_run=False):
1196
    """Migrates all primary instances from a node.
1197

1198
    @type node: str
1199
    @param node: node to migrate
1200
    @type mode: string
1201
    @param mode: if passed, it will overwrite the live migration type,
1202
        otherwise the hypervisor default will be used
1203
    @type dry_run: bool
1204
    @param dry_run: whether to perform a dry run
1205

1206
    @rtype: int
1207
    @return: job id
1208

1209
    """
1210
    query = []
1211
    if mode is not None:
1212
      query.append(("mode", mode))
1213
    if dry_run:
1214
      query.append(("dry-run", 1))
1215

    
1216
    return self._SendRequest(HTTP_POST,
1217
                             ("/%s/nodes/%s/migrate" %
1218
                              (GANETI_RAPI_VERSION, node)), query, None)
1219

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

1223
    @type node: str
1224
    @param node: node whose role to return
1225

1226
    @rtype: str
1227
    @return: the current role for a node
1228

1229
    """
1230
    return self._SendRequest(HTTP_GET,
1231
                             ("/%s/nodes/%s/role" %
1232
                              (GANETI_RAPI_VERSION, node)), None, None)
1233

    
1234
  def SetNodeRole(self, node, role, force=False):
1235
    """Sets the role for a node.
1236

1237
    @type node: str
1238
    @param node: the node whose role to set
1239
    @type role: str
1240
    @param role: the role to set for the node
1241
    @type force: bool
1242
    @param force: whether to force the role change
1243

1244
    @rtype: int
1245
    @return: job id
1246

1247
    """
1248
    query = [
1249
      ("force", force),
1250
      ]
1251

    
1252
    return self._SendRequest(HTTP_PUT,
1253
                             ("/%s/nodes/%s/role" %
1254
                              (GANETI_RAPI_VERSION, node)), query, role)
1255

    
1256
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1257
    """Gets the storage units for a node.
1258

1259
    @type node: str
1260
    @param node: the node whose storage units to return
1261
    @type storage_type: str
1262
    @param storage_type: storage type whose units to return
1263
    @type output_fields: str
1264
    @param output_fields: storage type fields to return
1265

1266
    @rtype: int
1267
    @return: job id where results can be retrieved
1268

1269
    """
1270
    query = [
1271
      ("storage_type", storage_type),
1272
      ("output_fields", output_fields),
1273
      ]
1274

    
1275
    return self._SendRequest(HTTP_GET,
1276
                             ("/%s/nodes/%s/storage" %
1277
                              (GANETI_RAPI_VERSION, node)), query, None)
1278

    
1279
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1280
    """Modifies parameters of storage units on the node.
1281

1282
    @type node: str
1283
    @param node: node whose storage units to modify
1284
    @type storage_type: str
1285
    @param storage_type: storage type whose units to modify
1286
    @type name: str
1287
    @param name: name of the storage unit
1288
    @type allocatable: bool or None
1289
    @param allocatable: Whether to set the "allocatable" flag on the storage
1290
                        unit (None=no modification, True=set, False=unset)
1291

1292
    @rtype: int
1293
    @return: job id
1294

1295
    """
1296
    query = [
1297
      ("storage_type", storage_type),
1298
      ("name", name),
1299
      ]
1300

    
1301
    if allocatable is not None:
1302
      query.append(("allocatable", allocatable))
1303

    
1304
    return self._SendRequest(HTTP_PUT,
1305
                             ("/%s/nodes/%s/storage/modify" %
1306
                              (GANETI_RAPI_VERSION, node)), query, None)
1307

    
1308
  def RepairNodeStorageUnits(self, node, storage_type, name):
1309
    """Repairs a storage unit on the node.
1310

1311
    @type node: str
1312
    @param node: node whose storage units to repair
1313
    @type storage_type: str
1314
    @param storage_type: storage type to repair
1315
    @type name: str
1316
    @param name: name of the storage unit to repair
1317

1318
    @rtype: int
1319
    @return: job id
1320

1321
    """
1322
    query = [
1323
      ("storage_type", storage_type),
1324
      ("name", name),
1325
      ]
1326

    
1327
    return self._SendRequest(HTTP_PUT,
1328
                             ("/%s/nodes/%s/storage/repair" %
1329
                              (GANETI_RAPI_VERSION, node)), query, None)
1330

    
1331
  def GetNodeTags(self, node):
1332
    """Gets the tags for a node.
1333

1334
    @type node: str
1335
    @param node: node whose tags to return
1336

1337
    @rtype: list of str
1338
    @return: tags for the node
1339

1340
    """
1341
    return self._SendRequest(HTTP_GET,
1342
                             ("/%s/nodes/%s/tags" %
1343
                              (GANETI_RAPI_VERSION, node)), None, None)
1344

    
1345
  def AddNodeTags(self, node, tags, dry_run=False):
1346
    """Adds tags to a node.
1347

1348
    @type node: str
1349
    @param node: node to add tags to
1350
    @type tags: list of str
1351
    @param tags: tags to add to the node
1352
    @type dry_run: bool
1353
    @param dry_run: whether to perform a dry run
1354

1355
    @rtype: int
1356
    @return: job id
1357

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

    
1363
    return self._SendRequest(HTTP_PUT,
1364
                             ("/%s/nodes/%s/tags" %
1365
                              (GANETI_RAPI_VERSION, node)), query, tags)
1366

    
1367
  def DeleteNodeTags(self, node, tags, dry_run=False):
1368
    """Delete tags from a node.
1369

1370
    @type node: str
1371
    @param node: node to remove tags from
1372
    @type tags: list of str
1373
    @param tags: tags to remove from the node
1374
    @type dry_run: bool
1375
    @param dry_run: whether to perform a dry run
1376

1377
    @rtype: int
1378
    @return: job id
1379

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

    
1385
    return self._SendRequest(HTTP_DELETE,
1386
                             ("/%s/nodes/%s/tags" %
1387
                              (GANETI_RAPI_VERSION, node)), query, None)
1388

    
1389
  def GetGroups(self, bulk=False):
1390
    """Gets all node groups in the cluster.
1391

1392
    @type bulk: bool
1393
    @param bulk: whether to return all information about the groups
1394

1395
    @rtype: list of dict or str
1396
    @return: if bulk is true, a list of dictionaries with info about all node
1397
        groups in the cluster, else a list of names of those node groups
1398

1399
    """
1400
    query = []
1401
    if bulk:
1402
      query.append(("bulk", 1))
1403

    
1404
    groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1405
                               query, None)
1406
    if bulk:
1407
      return groups
1408
    else:
1409
      return [g["name"] for g in groups]
1410

    
1411
  def GetGroup(self, group):
1412
    """Gets information about a node group.
1413

1414
    @type group: str
1415
    @param group: name of the node group whose info to return
1416

1417
    @rtype: dict
1418
    @return: info about the node group
1419

1420
    """
1421
    return self._SendRequest(HTTP_GET,
1422
                             "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
1423
                             None, None)
1424

    
1425
  def CreateGroup(self, name, alloc_policy=None, dry_run=False):
1426
    """Creates a new node group.
1427

1428
    @type name: str
1429
    @param name: the name of node group to create
1430
    @type alloc_policy: str
1431
    @param alloc_policy: the desired allocation policy for the group, if any
1432
    @type dry_run: bool
1433
    @param dry_run: whether to peform a dry run
1434

1435
    @rtype: int
1436
    @return: job id
1437

1438
    """
1439
    query = []
1440
    if dry_run:
1441
      query.append(("dry-run", 1))
1442

    
1443
    body = {
1444
      "name": name,
1445
      "alloc_policy": alloc_policy
1446
      }
1447

    
1448
    return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1449
                             query, body)
1450

    
1451
  def ModifyGroup(self, group, **kwargs):
1452
    """Modifies a node group.
1453

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

1456
    @type group: string
1457
    @param group: Node group name
1458
    @rtype: int
1459
    @return: job id
1460

1461
    """
1462
    return self._SendRequest(HTTP_PUT,
1463
                             ("/%s/groups/%s/modify" %
1464
                              (GANETI_RAPI_VERSION, group)), None, kwargs)
1465

    
1466
  def DeleteGroup(self, group, dry_run=False):
1467
    """Deletes a node group.
1468

1469
    @type group: str
1470
    @param group: the node group to delete
1471
    @type dry_run: bool
1472
    @param dry_run: whether to peform a dry run
1473

1474
    @rtype: int
1475
    @return: job id
1476

1477
    """
1478
    query = []
1479
    if dry_run:
1480
      query.append(("dry-run", 1))
1481

    
1482
    return self._SendRequest(HTTP_DELETE,
1483
                             ("/%s/groups/%s" %
1484
                              (GANETI_RAPI_VERSION, group)), query, None)
1485

    
1486
  def RenameGroup(self, group, new_name):
1487
    """Changes the name of a node group.
1488

1489
    @type group: string
1490
    @param group: Node group name
1491
    @type new_name: string
1492
    @param new_name: New node group name
1493

1494
    @rtype: int
1495
    @return: job id
1496

1497
    """
1498
    body = {
1499
      "new_name": new_name,
1500
      }
1501

    
1502
    return self._SendRequest(HTTP_PUT,
1503
                             ("/%s/groups/%s/rename" %
1504
                              (GANETI_RAPI_VERSION, group)), None, body)