Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ e23881ed

History | View | Annotate | Download (44.3 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 GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
761
    """Grows a disk of an instance.
762

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

765
    @type instance: string
766
    @param instance: Instance name
767
    @type disk: integer
768
    @param disk: Disk index
769
    @type amount: integer
770
    @param amount: Grow disk by this amount (MiB)
771
    @type wait_for_sync: bool
772
    @param wait_for_sync: Wait for disk to synchronize
773
    @rtype: int
774
    @return: job id
775

776
    """
777
    body = {
778
      "amount": amount,
779
      }
780

    
781
    if wait_for_sync is not None:
782
      body["wait_for_sync"] = wait_for_sync
783

    
784
    return self._SendRequest(HTTP_POST,
785
                             ("/%s/instances/%s/disk/%s/grow" %
786
                              (GANETI_RAPI_VERSION, instance, disk)),
787
                             None, body)
788

    
789
  def GetInstanceTags(self, instance):
790
    """Gets tags for an instance.
791

792
    @type instance: str
793
    @param instance: instance whose tags to return
794

795
    @rtype: list of str
796
    @return: tags for the instance
797

798
    """
799
    return self._SendRequest(HTTP_GET,
800
                             ("/%s/instances/%s/tags" %
801
                              (GANETI_RAPI_VERSION, instance)), None, None)
802

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

806
    @type instance: str
807
    @param instance: instance to add tags to
808
    @type tags: list of str
809
    @param tags: tags to add to the instance
810
    @type dry_run: bool
811
    @param dry_run: whether to perform a dry run
812

813
    @rtype: int
814
    @return: job id
815

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

    
821
    return self._SendRequest(HTTP_PUT,
822
                             ("/%s/instances/%s/tags" %
823
                              (GANETI_RAPI_VERSION, instance)), query, None)
824

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

828
    @type instance: str
829
    @param instance: instance to delete tags from
830
    @type tags: list of str
831
    @param tags: tags to delete
832
    @type dry_run: bool
833
    @param dry_run: whether to perform a dry run
834

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

    
840
    return self._SendRequest(HTTP_DELETE,
841
                             ("/%s/instances/%s/tags" %
842
                              (GANETI_RAPI_VERSION, instance)), query, None)
843

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

848
    @type instance: str
849
    @param instance: instance to rebot
850
    @type reboot_type: str
851
    @param reboot_type: one of: hard, soft, full
852
    @type ignore_secondaries: bool
853
    @param ignore_secondaries: if True, ignores errors for the secondary node
854
        while re-assembling disks (in hard-reboot mode only)
855
    @type dry_run: bool
856
    @param dry_run: whether to perform a dry run
857

858
    """
859
    query = []
860
    if reboot_type:
861
      query.append(("type", reboot_type))
862
    if ignore_secondaries is not None:
863
      query.append(("ignore_secondaries", ignore_secondaries))
864
    if dry_run:
865
      query.append(("dry-run", 1))
866

    
867
    return self._SendRequest(HTTP_POST,
868
                             ("/%s/instances/%s/reboot" %
869
                              (GANETI_RAPI_VERSION, instance)), query, None)
870

    
871
  def ShutdownInstance(self, instance, dry_run=False):
872
    """Shuts down an instance.
873

874
    @type instance: str
875
    @param instance: the instance to shut down
876
    @type dry_run: bool
877
    @param dry_run: whether to perform a dry run
878

879
    """
880
    query = []
881
    if dry_run:
882
      query.append(("dry-run", 1))
883

    
884
    return self._SendRequest(HTTP_PUT,
885
                             ("/%s/instances/%s/shutdown" %
886
                              (GANETI_RAPI_VERSION, instance)), query, None)
887

    
888
  def StartupInstance(self, instance, dry_run=False):
889
    """Starts up an instance.
890

891
    @type instance: str
892
    @param instance: the instance to start up
893
    @type dry_run: bool
894
    @param dry_run: whether to perform a dry run
895

896
    """
897
    query = []
898
    if dry_run:
899
      query.append(("dry-run", 1))
900

    
901
    return self._SendRequest(HTTP_PUT,
902
                             ("/%s/instances/%s/startup" %
903
                              (GANETI_RAPI_VERSION, instance)), query, None)
904

    
905
  def ReinstallInstance(self, instance, os=None, no_startup=False,
906
                        osparams=None):
907
    """Reinstalls an instance.
908

909
    @type instance: str
910
    @param instance: The instance to reinstall
911
    @type os: str or None
912
    @param os: The operating system to reinstall. If None, the instance's
913
        current operating system will be installed again
914
    @type no_startup: bool
915
    @param no_startup: Whether to start the instance automatically
916

917
    """
918
    if _INST_REINSTALL_REQV1 in self.GetFeatures():
919
      body = {
920
        "start": not no_startup,
921
        }
922
      if os is not None:
923
        body["os"] = os
924
      if osparams is not None:
925
        body["osparams"] = osparams
926
      return self._SendRequest(HTTP_POST,
927
                               ("/%s/instances/%s/reinstall" %
928
                                (GANETI_RAPI_VERSION, instance)), None, body)
929

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

    
935
    query = []
936
    if os:
937
      query.append(("os", os))
938
    if no_startup:
939
      query.append(("nostartup", 1))
940
    return self._SendRequest(HTTP_POST,
941
                             ("/%s/instances/%s/reinstall" %
942
                              (GANETI_RAPI_VERSION, instance)), query, None)
943

    
944
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
945
                           remote_node=None, iallocator=None, dry_run=False):
946
    """Replaces disks on an instance.
947

948
    @type instance: str
949
    @param instance: instance whose disks to replace
950
    @type disks: list of ints
951
    @param disks: Indexes of disks to replace
952
    @type mode: str
953
    @param mode: replacement mode to use (defaults to replace_auto)
954
    @type remote_node: str or None
955
    @param remote_node: new secondary node to use (for use with
956
        replace_new_secondary mode)
957
    @type iallocator: str or None
958
    @param iallocator: instance allocator plugin to use (for use with
959
                       replace_auto mode)
960
    @type dry_run: bool
961
    @param dry_run: whether to perform a dry run
962

963
    @rtype: int
964
    @return: job id
965

966
    """
967
    query = [
968
      ("mode", mode),
969
      ]
970

    
971
    if disks:
972
      query.append(("disks", ",".join(str(idx) for idx in disks)))
973

    
974
    if remote_node:
975
      query.append(("remote_node", remote_node))
976

    
977
    if iallocator:
978
      query.append(("iallocator", iallocator))
979

    
980
    if dry_run:
981
      query.append(("dry-run", 1))
982

    
983
    return self._SendRequest(HTTP_POST,
984
                             ("/%s/instances/%s/replace-disks" %
985
                              (GANETI_RAPI_VERSION, instance)), query, None)
986

    
987
  def PrepareExport(self, instance, mode):
988
    """Prepares an instance for an export.
989

990
    @type instance: string
991
    @param instance: Instance name
992
    @type mode: string
993
    @param mode: Export mode
994
    @rtype: string
995
    @return: Job ID
996

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

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

1008
    @type instance: string
1009
    @param instance: Instance name
1010
    @type mode: string
1011
    @param mode: Export mode
1012
    @rtype: string
1013
    @return: Job ID
1014

1015
    """
1016
    body = {
1017
      "destination": destination,
1018
      "mode": mode,
1019
      }
1020

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

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

    
1027
    if x509_key_name is not None:
1028
      body["x509_key_name"] = x509_key_name
1029

    
1030
    if destination_x509_ca is not None:
1031
      body["destination_x509_ca"] = destination_x509_ca
1032

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

    
1037
  def MigrateInstance(self, instance, mode=None, cleanup=None):
1038
    """Migrates an instance.
1039

1040
    @type instance: string
1041
    @param instance: Instance name
1042
    @type mode: string
1043
    @param mode: Migration mode
1044
    @type cleanup: bool
1045
    @param cleanup: Whether to clean up a previously failed migration
1046

1047
    """
1048
    body = {}
1049

    
1050
    if mode is not None:
1051
      body["mode"] = mode
1052

    
1053
    if cleanup is not None:
1054
      body["cleanup"] = cleanup
1055

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

    
1060
  def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
1061
    """Changes the name of an instance.
1062

1063
    @type instance: string
1064
    @param instance: Instance name
1065
    @type new_name: string
1066
    @param new_name: New instance name
1067
    @type ip_check: bool
1068
    @param ip_check: Whether to ensure instance's IP address is inactive
1069
    @type name_check: bool
1070
    @param name_check: Whether to ensure instance's name is resolvable
1071

1072
    """
1073
    body = {
1074
      "new_name": new_name,
1075
      }
1076

    
1077
    if ip_check is not None:
1078
      body["ip_check"] = ip_check
1079

    
1080
    if name_check is not None:
1081
      body["name_check"] = name_check
1082

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

    
1087
  def GetJobs(self):
1088
    """Gets all jobs for the cluster.
1089

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

1093
    """
1094
    return [int(j["id"])
1095
            for j in self._SendRequest(HTTP_GET,
1096
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1097
                                       None, None)]
1098

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

1102
    @type job_id: int
1103
    @param job_id: job id whose status to query
1104

1105
    @rtype: dict
1106
    @return: job status
1107

1108
    """
1109
    return self._SendRequest(HTTP_GET,
1110
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1111
                             None, None)
1112

    
1113
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1114
    """Waits for job changes.
1115

1116
    @type job_id: int
1117
    @param job_id: Job ID for which to wait
1118

1119
    """
1120
    body = {
1121
      "fields": fields,
1122
      "previous_job_info": prev_job_info,
1123
      "previous_log_serial": prev_log_serial,
1124
      }
1125

    
1126
    return self._SendRequest(HTTP_GET,
1127
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1128
                             None, body)
1129

    
1130
  def CancelJob(self, job_id, dry_run=False):
1131
    """Cancels a job.
1132

1133
    @type job_id: int
1134
    @param job_id: id of the job to delete
1135
    @type dry_run: bool
1136
    @param dry_run: whether to perform a dry run
1137

1138
    """
1139
    query = []
1140
    if dry_run:
1141
      query.append(("dry-run", 1))
1142

    
1143
    return self._SendRequest(HTTP_DELETE,
1144
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1145
                             query, None)
1146

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

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

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

1157
    """
1158
    query = []
1159
    if bulk:
1160
      query.append(("bulk", 1))
1161

    
1162
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1163
                              query, None)
1164
    if bulk:
1165
      return nodes
1166
    else:
1167
      return [n["id"] for n in nodes]
1168

    
1169
  def GetNode(self, node):
1170
    """Gets information about a node.
1171

1172
    @type node: str
1173
    @param node: node whose info to return
1174

1175
    @rtype: dict
1176
    @return: info about the node
1177

1178
    """
1179
    return self._SendRequest(HTTP_GET,
1180
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1181
                             None, None)
1182

    
1183
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1184
                   dry_run=False, early_release=False):
1185
    """Evacuates instances from a Ganeti node.
1186

1187
    @type node: str
1188
    @param node: node to evacuate
1189
    @type iallocator: str or None
1190
    @param iallocator: instance allocator to use
1191
    @type remote_node: str
1192
    @param remote_node: node to evaucate to
1193
    @type dry_run: bool
1194
    @param dry_run: whether to perform a dry run
1195
    @type early_release: bool
1196
    @param early_release: whether to enable parallelization
1197

1198
    @rtype: list
1199
    @return: list of (job ID, instance name, new secondary node); if
1200
        dry_run was specified, then the actual move jobs were not
1201
        submitted and the job IDs will be C{None}
1202

1203
    @raises GanetiApiError: if an iallocator and remote_node are both
1204
        specified
1205

1206
    """
1207
    if iallocator and remote_node:
1208
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1209

    
1210
    query = []
1211
    if iallocator:
1212
      query.append(("iallocator", iallocator))
1213
    if remote_node:
1214
      query.append(("remote_node", remote_node))
1215
    if dry_run:
1216
      query.append(("dry-run", 1))
1217
    if early_release:
1218
      query.append(("early_release", 1))
1219

    
1220
    return self._SendRequest(HTTP_POST,
1221
                             ("/%s/nodes/%s/evacuate" %
1222
                              (GANETI_RAPI_VERSION, node)), query, None)
1223

    
1224
  def MigrateNode(self, node, mode=None, dry_run=False):
1225
    """Migrates all primary instances from a node.
1226

1227
    @type node: str
1228
    @param node: node to migrate
1229
    @type mode: string
1230
    @param mode: if passed, it will overwrite the live migration type,
1231
        otherwise the hypervisor default will be used
1232
    @type dry_run: bool
1233
    @param dry_run: whether to perform a dry run
1234

1235
    @rtype: int
1236
    @return: job id
1237

1238
    """
1239
    query = []
1240
    if mode is not None:
1241
      query.append(("mode", mode))
1242
    if dry_run:
1243
      query.append(("dry-run", 1))
1244

    
1245
    return self._SendRequest(HTTP_POST,
1246
                             ("/%s/nodes/%s/migrate" %
1247
                              (GANETI_RAPI_VERSION, node)), query, None)
1248

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

1252
    @type node: str
1253
    @param node: node whose role to return
1254

1255
    @rtype: str
1256
    @return: the current role for a node
1257

1258
    """
1259
    return self._SendRequest(HTTP_GET,
1260
                             ("/%s/nodes/%s/role" %
1261
                              (GANETI_RAPI_VERSION, node)), None, None)
1262

    
1263
  def SetNodeRole(self, node, role, force=False):
1264
    """Sets the role for a node.
1265

1266
    @type node: str
1267
    @param node: the node whose role to set
1268
    @type role: str
1269
    @param role: the role to set for the node
1270
    @type force: bool
1271
    @param force: whether to force the role change
1272

1273
    @rtype: int
1274
    @return: job id
1275

1276
    """
1277
    query = [
1278
      ("force", force),
1279
      ]
1280

    
1281
    return self._SendRequest(HTTP_PUT,
1282
                             ("/%s/nodes/%s/role" %
1283
                              (GANETI_RAPI_VERSION, node)), query, role)
1284

    
1285
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1286
    """Gets the storage units for a node.
1287

1288
    @type node: str
1289
    @param node: the node whose storage units to return
1290
    @type storage_type: str
1291
    @param storage_type: storage type whose units to return
1292
    @type output_fields: str
1293
    @param output_fields: storage type fields to return
1294

1295
    @rtype: int
1296
    @return: job id where results can be retrieved
1297

1298
    """
1299
    query = [
1300
      ("storage_type", storage_type),
1301
      ("output_fields", output_fields),
1302
      ]
1303

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

    
1308
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1309
    """Modifies parameters of storage units on the node.
1310

1311
    @type node: str
1312
    @param node: node whose storage units to modify
1313
    @type storage_type: str
1314
    @param storage_type: storage type whose units to modify
1315
    @type name: str
1316
    @param name: name of the storage unit
1317
    @type allocatable: bool or None
1318
    @param allocatable: Whether to set the "allocatable" flag on the storage
1319
                        unit (None=no modification, True=set, False=unset)
1320

1321
    @rtype: int
1322
    @return: job id
1323

1324
    """
1325
    query = [
1326
      ("storage_type", storage_type),
1327
      ("name", name),
1328
      ]
1329

    
1330
    if allocatable is not None:
1331
      query.append(("allocatable", allocatable))
1332

    
1333
    return self._SendRequest(HTTP_PUT,
1334
                             ("/%s/nodes/%s/storage/modify" %
1335
                              (GANETI_RAPI_VERSION, node)), query, None)
1336

    
1337
  def RepairNodeStorageUnits(self, node, storage_type, name):
1338
    """Repairs a storage unit on the node.
1339

1340
    @type node: str
1341
    @param node: node whose storage units to repair
1342
    @type storage_type: str
1343
    @param storage_type: storage type to repair
1344
    @type name: str
1345
    @param name: name of the storage unit to repair
1346

1347
    @rtype: int
1348
    @return: job id
1349

1350
    """
1351
    query = [
1352
      ("storage_type", storage_type),
1353
      ("name", name),
1354
      ]
1355

    
1356
    return self._SendRequest(HTTP_PUT,
1357
                             ("/%s/nodes/%s/storage/repair" %
1358
                              (GANETI_RAPI_VERSION, node)), query, None)
1359

    
1360
  def GetNodeTags(self, node):
1361
    """Gets the tags for a node.
1362

1363
    @type node: str
1364
    @param node: node whose tags to return
1365

1366
    @rtype: list of str
1367
    @return: tags for the node
1368

1369
    """
1370
    return self._SendRequest(HTTP_GET,
1371
                             ("/%s/nodes/%s/tags" %
1372
                              (GANETI_RAPI_VERSION, node)), None, None)
1373

    
1374
  def AddNodeTags(self, node, tags, dry_run=False):
1375
    """Adds tags to a node.
1376

1377
    @type node: str
1378
    @param node: node to add tags to
1379
    @type tags: list of str
1380
    @param tags: tags to add to the node
1381
    @type dry_run: bool
1382
    @param dry_run: whether to perform a dry run
1383

1384
    @rtype: int
1385
    @return: job id
1386

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

    
1392
    return self._SendRequest(HTTP_PUT,
1393
                             ("/%s/nodes/%s/tags" %
1394
                              (GANETI_RAPI_VERSION, node)), query, tags)
1395

    
1396
  def DeleteNodeTags(self, node, tags, dry_run=False):
1397
    """Delete tags from a node.
1398

1399
    @type node: str
1400
    @param node: node to remove tags from
1401
    @type tags: list of str
1402
    @param tags: tags to remove from the node
1403
    @type dry_run: bool
1404
    @param dry_run: whether to perform a dry run
1405

1406
    @rtype: int
1407
    @return: job id
1408

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

    
1414
    return self._SendRequest(HTTP_DELETE,
1415
                             ("/%s/nodes/%s/tags" %
1416
                              (GANETI_RAPI_VERSION, node)), query, None)
1417

    
1418
  def GetGroups(self, bulk=False):
1419
    """Gets all node groups in the cluster.
1420

1421
    @type bulk: bool
1422
    @param bulk: whether to return all information about the groups
1423

1424
    @rtype: list of dict or str
1425
    @return: if bulk is true, a list of dictionaries with info about all node
1426
        groups in the cluster, else a list of names of those node groups
1427

1428
    """
1429
    query = []
1430
    if bulk:
1431
      query.append(("bulk", 1))
1432

    
1433
    groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1434
                               query, None)
1435
    if bulk:
1436
      return groups
1437
    else:
1438
      return [g["name"] for g in groups]
1439

    
1440
  def GetGroup(self, group):
1441
    """Gets information about a node group.
1442

1443
    @type group: str
1444
    @param group: name of the node group whose info to return
1445

1446
    @rtype: dict
1447
    @return: info about the node group
1448

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

    
1454
  def CreateGroup(self, name, alloc_policy=None, dry_run=False):
1455
    """Creates a new node group.
1456

1457
    @type name: str
1458
    @param name: the name of node group to create
1459
    @type alloc_policy: str
1460
    @param alloc_policy: the desired allocation policy for the group, if any
1461
    @type dry_run: bool
1462
    @param dry_run: whether to peform a dry run
1463

1464
    @rtype: int
1465
    @return: job id
1466

1467
    """
1468
    query = []
1469
    if dry_run:
1470
      query.append(("dry-run", 1))
1471

    
1472
    body = {
1473
      "name": name,
1474
      "alloc_policy": alloc_policy
1475
      }
1476

    
1477
    return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1478
                             query, body)
1479

    
1480
  def ModifyGroup(self, group, **kwargs):
1481
    """Modifies a node group.
1482

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

1485
    @type group: string
1486
    @param group: Node group name
1487
    @rtype: int
1488
    @return: job id
1489

1490
    """
1491
    return self._SendRequest(HTTP_PUT,
1492
                             ("/%s/groups/%s/modify" %
1493
                              (GANETI_RAPI_VERSION, group)), None, kwargs)
1494

    
1495
  def DeleteGroup(self, group, dry_run=False):
1496
    """Deletes a node group.
1497

1498
    @type group: str
1499
    @param group: the node group to delete
1500
    @type dry_run: bool
1501
    @param dry_run: whether to peform a dry run
1502

1503
    @rtype: int
1504
    @return: job id
1505

1506
    """
1507
    query = []
1508
    if dry_run:
1509
      query.append(("dry-run", 1))
1510

    
1511
    return self._SendRequest(HTTP_DELETE,
1512
                             ("/%s/groups/%s" %
1513
                              (GANETI_RAPI_VERSION, group)), query, None)
1514

    
1515
  def RenameGroup(self, group, new_name):
1516
    """Changes the name of a node group.
1517

1518
    @type group: string
1519
    @param group: Node group name
1520
    @type new_name: string
1521
    @param new_name: New node group name
1522

1523
    @rtype: int
1524
    @return: job id
1525

1526
    """
1527
    body = {
1528
      "new_name": new_name,
1529
      }
1530

    
1531
    return self._SendRequest(HTTP_PUT,
1532
                             ("/%s/groups/%s/rename" %
1533
                              (GANETI_RAPI_VERSION, group)), None, body)