Statistics
| Branch: | Tag: | Revision:

root / util / rapi.py @ 3481786b

History | View | Annotate | Download (46.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 socket
38
import urllib
39
import threading
40
import pycurl
41

    
42
try:
43
  import simplejson as json
44
except ImportError:
45
  import json
46

    
47
try:
48
  from cStringIO import StringIO
49
except ImportError:
50
  from StringIO import StringIO
51

    
52

    
53
GANETI_RAPI_PORT = 5080
54
GANETI_RAPI_VERSION = 2
55

    
56
HTTP_DELETE = "DELETE"
57
HTTP_GET = "GET"
58
HTTP_PUT = "PUT"
59
HTTP_POST = "POST"
60
HTTP_OK = 200
61
HTTP_NOT_FOUND = 404
62
HTTP_APP_JSON = "application/json"
63

    
64
REPLACE_DISK_PRI = "replace_on_primary"
65
REPLACE_DISK_SECONDARY = "replace_on_secondary"
66
REPLACE_DISK_CHG = "replace_new_secondary"
67
REPLACE_DISK_AUTO = "replace_auto"
68

    
69
NODE_ROLE_DRAINED = "drained"
70
NODE_ROLE_MASTER_CANDIATE = "master-candidate"
71
NODE_ROLE_MASTER = "master"
72
NODE_ROLE_OFFLINE = "offline"
73
NODE_ROLE_REGULAR = "regular"
74

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

    
87
# Older pycURL versions don't have all error constants
88
try:
89
  _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
90
  _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
91
except AttributeError:
92
  _CURLE_SSL_CACERT = 60
93
  _CURLE_SSL_CACERT_BADFILE = 77
94

    
95
_CURL_SSL_CERT_ERRORS = frozenset([
96
  _CURLE_SSL_CACERT,
97
  _CURLE_SSL_CACERT_BADFILE,
98
  ])
99

    
100

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

104
  """
105
  pass
106

    
107

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

111
  """
112
  pass
113

    
114

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

118
  """
119
  def __init__(self, msg, code=None):
120
    Error.__init__(self, msg)
121
    self.code = code
122

    
123

    
124
def UsesRapiClient(fn):
125
  """Decorator for code using RAPI client to initialize pycURL.
126

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

    
135
    pycurl.global_init(pycurl.GLOBAL_ALL)
136
    try:
137
      return fn(*args, **kwargs)
138
    finally:
139
      pycurl.global_cleanup()
140

    
141
  return wrapper
142

    
143

    
144
def GenericCurlConfig(verbose=False, use_signal=False,
145
                      use_curl_cabundle=False, cafile=None, capath=None,
146
                      proxy=None, verify_hostname=False,
147
                      connect_timeout=None, timeout=None,
148
                      _pycurl_version_fn=pycurl.version_info):
149
  """Curl configuration function generator.
150

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

173
  """
174
  if use_curl_cabundle and (cafile or capath):
175
    raise Error("Can not use default CA bundle when CA file or path is set")
176

    
177
  def _ConfigCurl(curl, logger):
178
    """Configures a cURL object
179

180
    @type curl: pycurl.Curl
181
    @param curl: cURL object
182

183
    """
184
    logger.debug("Using cURL version %s", pycurl.version)
185

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

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

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

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

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

    
231
    if proxy is not None:
232
      curl.setopt(pycurl.PROXY, str(proxy))
233

    
234
    # Timeouts
235
    if connect_timeout is not None:
236
      curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
237
    if timeout is not None:
238
      curl.setopt(pycurl.TIMEOUT, timeout)
239

    
240
  return _ConfigCurl
241

    
242

    
243
class GanetiRapiClient(object): # pylint: disable-msg=R0904
244
  """Ganeti RAPI client.
245

246
  """
247
  USER_AGENT = "Ganeti RAPI Client"
248
  _json_encoder = simplejson.JSONEncoder(sort_keys=True)
249

    
250
  def __init__(self, host, port=GANETI_RAPI_PORT,
251
               username=None, password=None, logger=logging,
252
               curl_config_fn=None, curl_factory=None):
253
    """Initializes this class.
254

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

267
    """
268
    self._username = username
269
    self._password = password
270
    self._logger = logger
271
    self._curl_config_fn = curl_config_fn
272
    self._curl_factory = curl_factory
273

    
274
    try:
275
      socket.inet_pton(socket.AF_INET6, host)
276
      address = "[%s]:%s" % (host, port)
277
    except socket.error:
278
      address = "%s:%s" % (host, port)
279

    
280
    self._base_url = "https://%s" % address
281

    
282
    if username is not None:
283
      if password is None:
284
        raise Error("Password not specified")
285
    elif password:
286
      raise Error("Specified password without username")
287

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

291
    """
292
    # Create pycURL object if no factory is provided
293
    if self._curl_factory:
294
      curl = self._curl_factory()
295
    else:
296
      curl = pycurl.Curl()
297

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

    
311
    assert ((self._username is None and self._password is None) ^
312
            (self._username is not None and self._password is not None))
313

    
314
    if self._username:
315
      # Setup authentication
316
      curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
317
      curl.setopt(pycurl.USERPWD,
318
                  str("%s:%s" % (self._username, self._password)))
319

    
320
    # Call external configuration function
321
    if self._curl_config_fn:
322
      self._curl_config_fn(curl, self._logger)
323

    
324
    return curl
325

    
326
  @staticmethod
327
  def _EncodeQuery(query):
328
    """Encode query values for RAPI URL.
329

330
    @type query: list of two-tuples
331
    @param query: Query arguments
332
    @rtype: list
333
    @return: Query list with encoded values
334

335
    """
336
    result = []
337

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

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

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

    
349
      else:
350
        result.append((name, value))
351

    
352
    return result
353

    
354
  def _SendRequest(self, method, path, query, content):
355
    """Sends an HTTP request.
356

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

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

369
    @rtype: str
370
    @return: JSON-Decoded response
371

372
    @raises CertificateError: If an invalid SSL certificate is found
373
    @raises GanetiApiError: If an invalid response is returned
374

375
    """
376
    assert path.startswith("/")
377

    
378
    curl = self._CreateCurl()
379

    
380
    if content is not None:
381
      encoded_content = self._json_encoder.encode(content)
382
    else:
383
      encoded_content = ""
384

    
385
    # Build URL
386
    urlparts = [self._base_url, path]
387
    if query:
388
      urlparts.append("?")
389
      urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
390

    
391
    url = "".join(urlparts)
392

    
393
    self._logger.debug("Sending request %s %s (content=%r)",
394
                       method, url, encoded_content)
395

    
396
    # Buffer for response
397
    encoded_resp_body = StringIO()
398

    
399
    # Configure cURL
400
    curl.setopt(pycurl.CUSTOMREQUEST, str(method))
401
    curl.setopt(pycurl.URL, str(url))
402
    curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
403
    curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
404

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

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

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

    
423
    # Was anything written to the response buffer?
424
    if encoded_resp_body.tell():
425
      response_content = simplejson.loads(encoded_resp_body.getvalue())
426
    else:
427
      response_content = None
428

    
429
    if http_code != HTTP_OK:
430
      if isinstance(response_content, dict):
431
        msg = ("%s %s: %s" %
432
               (response_content["code"],
433
                response_content["message"],
434
                response_content["explain"]))
435
      else:
436
        msg = str(response_content)
437

    
438
      raise GanetiApiError(msg, code=http_code)
439

    
440
    return response_content
441

    
442
  def GetVersion(self):
443
    """Gets the Remote API version running on the cluster.
444

445
    @rtype: int
446
    @return: Ganeti Remote API version
447

448
    """
449
    return self._SendRequest(HTTP_GET, "/version", None, None)
450

    
451
  def GetFeatures(self):
452
    """Gets the list of optional features supported by RAPI server.
453

454
    @rtype: list
455
    @return: List of optional features
456

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

    
466
      raise
467

    
468
  def GetOperatingSystems(self):
469
    """Gets the Operating Systems running in the Ganeti cluster.
470

471
    @rtype: list of str
472
    @return: operating systems
473

474
    """
475
    return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
476
                             None, None)
477

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

481
    @rtype: dict
482
    @return: information about the cluster
483

484
    """
485
    return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
486
                             None, None)
487

    
488
  def RedistributeConfig(self):
489
    """Tells the cluster to redistribute its configuration files.
490

491
    @return: job id
492

493
    """
494
    return self._SendRequest(HTTP_PUT,
495
                             "/%s/redistribute-config" % GANETI_RAPI_VERSION,
496
                             None, None)
497

    
498
  def ModifyCluster(self, **kwargs):
499
    """Modifies cluster parameters.
500

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

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

506
    """
507
    body = kwargs
508

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

    
512
  def GetClusterTags(self):
513
    """Gets the cluster tags.
514

515
    @rtype: list of str
516
    @return: cluster tags
517

518
    """
519
    return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
520
                             None, None)
521

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

525
    @type tags: list of str
526
    @param tags: tags to add to the cluster
527
    @type dry_run: bool
528
    @param dry_run: whether to perform a dry run
529

530
    @rtype: int
531
    @return: job id
532

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

    
538
    return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
539
                             query, None)
540

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

544
    @type tags: list of str
545
    @param tags: tags to delete
546
    @type dry_run: bool
547
    @param dry_run: whether to perform a dry run
548

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

    
554
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
555
                             query, None)
556

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

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

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

566
    """
567
    query = []
568
    if bulk:
569
      query.append(("bulk", 1))
570

    
571
    instances = self._SendRequest(HTTP_GET,
572
                                  "/%s/instances" % GANETI_RAPI_VERSION,
573
                                  query, None)
574
    if bulk:
575
      return instances
576
    else:
577
      return [i["id"] for i in instances]
578

    
579
  def GetInstance(self, instance):
580
    """Gets information about an instance.
581

582
    @type instance: str
583
    @param instance: instance whose info to return
584

585
    @rtype: dict
586
    @return: info about the instance
587

588
    """
589
    return self._SendRequest(HTTP_GET,
590
                             ("/%s/instances/%s" %
591
                              (GANETI_RAPI_VERSION, instance)), None, None)
592

    
593
  def GetInstanceInfo(self, instance, static=None):
594
    """Gets information about an instance.
595

596
    @type instance: string
597
    @param instance: Instance name
598
    @rtype: string
599
    @return: Job ID
600

601
    """
602
    if static is not None:
603
      query = [("static", static)]
604
    else:
605
      query = None
606

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

    
611
  def CreateInstance(self, mode, name, disk_template, disks, nics,
612
                     **kwargs):
613
    """Creates a new instance.
614

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

617
    @type mode: string
618
    @param mode: Instance creation mode
619
    @type name: string
620
    @param name: Hostname of the instance to create
621
    @type disk_template: string
622
    @param disk_template: Disk template for instance (e.g. plain, diskless,
623
                          file, or drbd)
624
    @type disks: list of dicts
625
    @param disks: List of disk definitions
626
    @type nics: list of dicts
627
    @param nics: List of NIC definitions
628
    @type dry_run: bool
629
    @keyword dry_run: whether to perform a dry run
630

631
    @rtype: int
632
    @return: job id
633

634
    """
635
    query = []
636

    
637
    if kwargs.get("dry_run"):
638
      query.append(("dry-run", 1))
639

    
640
    if _INST_CREATE_REQV1 in self.GetFeatures():
641
      # All required fields for request data version 1
642
      body = {
643
        _REQ_DATA_VERSION_FIELD: 1,
644
        "mode": mode,
645
        "name": name,
646
        "disk_template": disk_template,
647
        "disks": disks,
648
        "nics": nics,
649
        }
650

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

    
656
      body.update((key, value) for key, value in kwargs.iteritems()
657
                  if key != "dry_run")
658
    else:
659
      # Old request format (version 0)
660

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

    
667
      # Validate disks
668
      for idx, disk in enumerate(disks):
669
        unsupported = set(disk.keys()) - _INST_CREATE_V0_DISK_PARAMS
670
        if unsupported:
671
          raise GanetiApiError("Server supports request version 0 only, but"
672
                               " disk %s specifies the unsupported parameters"
673
                               " %s, allowed are %s" %
674
                               (idx, unsupported,
675
                                list(_INST_CREATE_V0_DISK_PARAMS)))
676

    
677
      assert (len(_INST_CREATE_V0_DISK_PARAMS) == 1 and
678
              "size" in _INST_CREATE_V0_DISK_PARAMS)
679
      disk_sizes = [disk["size"] for disk in disks]
680

    
681
      # Validate NICs
682
      if not nics:
683
        raise GanetiApiError("Server supports request version 0 only, but"
684
                             " no NIC specified")
685
      elif len(nics) > 1:
686
        raise GanetiApiError("Server supports request version 0 only, but"
687
                             " more than one NIC specified")
688

    
689
      assert len(nics) == 1
690

    
691
      unsupported = set(nics[0].keys()) - _INST_NIC_PARAMS
692
      if unsupported:
693
        raise GanetiApiError("Server supports request version 0 only, but"
694
                             " NIC 0 specifies the unsupported parameters %s,"
695
                             " allowed are %s" %
696
                             (unsupported, list(_INST_NIC_PARAMS)))
697

    
698
      # Validate other parameters
699
      unsupported = (set(kwargs.keys()) - _INST_CREATE_V0_PARAMS -
700
                     _INST_CREATE_V0_DPARAMS)
701
      if unsupported:
702
        allowed = _INST_CREATE_V0_PARAMS.union(_INST_CREATE_V0_DPARAMS)
703
        raise GanetiApiError("Server supports request version 0 only, but"
704
                             " the following unsupported parameters are"
705
                             " specified: %s, allowed are %s" %
706
                             (unsupported, list(allowed)))
707

    
708
      # All required fields for request data version 0
709
      body = {
710
        _REQ_DATA_VERSION_FIELD: 0,
711
        "name": name,
712
        "disk_template": disk_template,
713
        "disks": disk_sizes,
714
        }
715

    
716
      # NIC fields
717
      assert len(nics) == 1
718
      assert not (set(body.keys()) & set(nics[0].keys()))
719
      body.update(nics[0])
720

    
721
      # Copy supported fields
722
      assert not (set(body.keys()) & set(kwargs.keys()))
723
      body.update(dict((key, value) for key, value in kwargs.items()
724
                       if key in _INST_CREATE_V0_PARAMS))
725

    
726
      # Merge dictionaries
727
      for i in (value for key, value in kwargs.items()
728
                if key in _INST_CREATE_V0_DPARAMS):
729
        assert not (set(body.keys()) & set(i.keys()))
730
        body.update(i)
731

    
732
      assert not (set(kwargs.keys()) -
733
                  (_INST_CREATE_V0_PARAMS | _INST_CREATE_V0_DPARAMS))
734
      assert not (set(body.keys()) & _INST_CREATE_V0_DPARAMS)
735

    
736
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
737
                             query, body)
738

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

742
    @type instance: str
743
    @param instance: the instance to delete
744

745
    @rtype: int
746
    @return: job id
747

748
    """
749
    query = []
750
    if dry_run:
751
      query.append(("dry-run", 1))
752

    
753
    return self._SendRequest(HTTP_DELETE,
754
                             ("/%s/instances/%s" %
755
                              (GANETI_RAPI_VERSION, instance)), query, None)
756

    
757
  def ModifyInstance(self, instance, **kwargs):
758
    """Modifies an instance.
759

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

762
    @type instance: string
763
    @param instance: Instance name
764
    @rtype: int
765
    @return: job id
766

767
    """
768
    body = kwargs
769

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

    
774
  def ActivateInstanceDisks(self, instance, ignore_size=None):
775
    """Activates an instance's disks.
776

777
    @type instance: string
778
    @param instance: Instance name
779
    @type ignore_size: bool
780
    @param ignore_size: Whether to ignore recorded size
781
    @return: job id
782

783
    """
784
    query = []
785
    if ignore_size:
786
      query.append(("ignore_size", 1))
787

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

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

795
    @type instance: string
796
    @param instance: Instance name
797
    @return: job id
798

799
    """
800
    return self._SendRequest(HTTP_PUT,
801
                             ("/%s/instances/%s/deactivate-disks" %
802
                              (GANETI_RAPI_VERSION, instance)), None, None)
803

    
804
  def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
805
    """Grows a disk of an instance.
806

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

809
    @type instance: string
810
    @param instance: Instance name
811
    @type disk: integer
812
    @param disk: Disk index
813
    @type amount: integer
814
    @param amount: Grow disk by this amount (MiB)
815
    @type wait_for_sync: bool
816
    @param wait_for_sync: Wait for disk to synchronize
817
    @rtype: int
818
    @return: job id
819

820
    """
821
    body = {
822
      "amount": amount,
823
      }
824

    
825
    if wait_for_sync is not None:
826
      body["wait_for_sync"] = wait_for_sync
827

    
828
    return self._SendRequest(HTTP_POST,
829
                             ("/%s/instances/%s/disk/%s/grow" %
830
                              (GANETI_RAPI_VERSION, instance, disk)),
831
                             None, body)
832

    
833
  def GetInstanceTags(self, instance):
834
    """Gets tags for an instance.
835

836
    @type instance: str
837
    @param instance: instance whose tags to return
838

839
    @rtype: list of str
840
    @return: tags for the instance
841

842
    """
843
    return self._SendRequest(HTTP_GET,
844
                             ("/%s/instances/%s/tags" %
845
                              (GANETI_RAPI_VERSION, instance)), None, None)
846

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

850
    @type instance: str
851
    @param instance: instance to add tags to
852
    @type tags: list of str
853
    @param tags: tags to add to the instance
854
    @type dry_run: bool
855
    @param dry_run: whether to perform a dry run
856

857
    @rtype: int
858
    @return: job id
859

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

    
865
    return self._SendRequest(HTTP_PUT,
866
                             ("/%s/instances/%s/tags" %
867
                              (GANETI_RAPI_VERSION, instance)), query, None)
868

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

872
    @type instance: str
873
    @param instance: instance to delete tags from
874
    @type tags: list of str
875
    @param tags: tags to delete
876
    @type dry_run: bool
877
    @param dry_run: whether to perform a dry run
878

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

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

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

892
    @type instance: str
893
    @param instance: instance to rebot
894
    @type reboot_type: str
895
    @param reboot_type: one of: hard, soft, full
896
    @type ignore_secondaries: bool
897
    @param ignore_secondaries: if True, ignores errors for the secondary node
898
        while re-assembling disks (in hard-reboot mode only)
899
    @type dry_run: bool
900
    @param dry_run: whether to perform a dry run
901

902
    """
903
    query = []
904
    if reboot_type:
905
      query.append(("type", reboot_type))
906
    if ignore_secondaries is not None:
907
      query.append(("ignore_secondaries", ignore_secondaries))
908
    if dry_run:
909
      query.append(("dry-run", 1))
910

    
911
    return self._SendRequest(HTTP_POST,
912
                             ("/%s/instances/%s/reboot" %
913
                              (GANETI_RAPI_VERSION, instance)), query, None)
914

    
915
  def ShutdownInstance(self, instance, dry_run=False):
916
    """Shuts down an instance.
917

918
    @type instance: str
919
    @param instance: the instance to shut down
920
    @type dry_run: bool
921
    @param dry_run: whether to perform a dry run
922

923
    """
924
    query = []
925
    if dry_run:
926
      query.append(("dry-run", 1))
927

    
928
    return self._SendRequest(HTTP_PUT,
929
                             ("/%s/instances/%s/shutdown" %
930
                              (GANETI_RAPI_VERSION, instance)), query, None)
931

    
932
  def StartupInstance(self, instance, dry_run=False):
933
    """Starts up an instance.
934

935
    @type instance: str
936
    @param instance: the instance to start up
937
    @type dry_run: bool
938
    @param dry_run: whether to perform a dry run
939

940
    """
941
    query = []
942
    if dry_run:
943
      query.append(("dry-run", 1))
944

    
945
    return self._SendRequest(HTTP_PUT,
946
                             ("/%s/instances/%s/startup" %
947
                              (GANETI_RAPI_VERSION, instance)), query, None)
948

    
949
  def ReinstallInstance(self, instance, os=None, no_startup=False,
950
                        osparams=None):
951
    """Reinstalls an instance.
952

953
    @type instance: str
954
    @param instance: The instance to reinstall
955
    @type os: str or None
956
    @param os: The operating system to reinstall. If None, the instance's
957
        current operating system will be installed again
958
    @type no_startup: bool
959
    @param no_startup: Whether to start the instance automatically
960

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

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

    
979
    query = []
980
    if os:
981
      query.append(("os", os))
982
    if no_startup:
983
      query.append(("nostartup", 1))
984
    return self._SendRequest(HTTP_POST,
985
                             ("/%s/instances/%s/reinstall" %
986
                              (GANETI_RAPI_VERSION, instance)), query, None)
987

    
988
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
989
                           remote_node=None, iallocator=None, dry_run=False):
990
    """Replaces disks on an instance.
991

992
    @type instance: str
993
    @param instance: instance whose disks to replace
994
    @type disks: list of ints
995
    @param disks: Indexes of disks to replace
996
    @type mode: str
997
    @param mode: replacement mode to use (defaults to replace_auto)
998
    @type remote_node: str or None
999
    @param remote_node: new secondary node to use (for use with
1000
        replace_new_secondary mode)
1001
    @type iallocator: str or None
1002
    @param iallocator: instance allocator plugin to use (for use with
1003
                       replace_auto mode)
1004
    @type dry_run: bool
1005
    @param dry_run: whether to perform a dry run
1006

1007
    @rtype: int
1008
    @return: job id
1009

1010
    """
1011
    query = [
1012
      ("mode", mode),
1013
      ]
1014

    
1015
    if disks:
1016
      query.append(("disks", ",".join(str(idx) for idx in disks)))
1017

    
1018
    if remote_node:
1019
      query.append(("remote_node", remote_node))
1020

    
1021
    if iallocator:
1022
      query.append(("iallocator", iallocator))
1023

    
1024
    if dry_run:
1025
      query.append(("dry-run", 1))
1026

    
1027
    return self._SendRequest(HTTP_POST,
1028
                             ("/%s/instances/%s/replace-disks" %
1029
                              (GANETI_RAPI_VERSION, instance)), query, None)
1030

    
1031
  def PrepareExport(self, instance, mode):
1032
    """Prepares an instance for an export.
1033

1034
    @type instance: string
1035
    @param instance: Instance name
1036
    @type mode: string
1037
    @param mode: Export mode
1038
    @rtype: string
1039
    @return: Job ID
1040

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

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

1052
    @type instance: string
1053
    @param instance: Instance name
1054
    @type mode: string
1055
    @param mode: Export mode
1056
    @rtype: string
1057
    @return: Job ID
1058

1059
    """
1060
    body = {
1061
      "destination": destination,
1062
      "mode": mode,
1063
      }
1064

    
1065
    if shutdown is not None:
1066
      body["shutdown"] = shutdown
1067

    
1068
    if remove_instance is not None:
1069
      body["remove_instance"] = remove_instance
1070

    
1071
    if x509_key_name is not None:
1072
      body["x509_key_name"] = x509_key_name
1073

    
1074
    if destination_x509_ca is not None:
1075
      body["destination_x509_ca"] = destination_x509_ca
1076

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

    
1081
  def MigrateInstance(self, instance, mode=None, cleanup=None):
1082
    """Migrates an instance.
1083

1084
    @type instance: string
1085
    @param instance: Instance name
1086
    @type mode: string
1087
    @param mode: Migration mode
1088
    @type cleanup: bool
1089
    @param cleanup: Whether to clean up a previously failed migration
1090

1091
    """
1092
    body = {}
1093

    
1094
    if mode is not None:
1095
      body["mode"] = mode
1096

    
1097
    if cleanup is not None:
1098
      body["cleanup"] = cleanup
1099

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

    
1104
  def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
1105
    """Changes the name of an instance.
1106

1107
    @type instance: string
1108
    @param instance: Instance name
1109
    @type new_name: string
1110
    @param new_name: New instance name
1111
    @type ip_check: bool
1112
    @param ip_check: Whether to ensure instance's IP address is inactive
1113
    @type name_check: bool
1114
    @param name_check: Whether to ensure instance's name is resolvable
1115

1116
    """
1117
    body = {
1118
      "new_name": new_name,
1119
      }
1120

    
1121
    if ip_check is not None:
1122
      body["ip_check"] = ip_check
1123

    
1124
    if name_check is not None:
1125
      body["name_check"] = name_check
1126

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

    
1131
  def GetInstanceConsole(self, instance):
1132
    """Request information for connecting to instance's console.
1133

1134
    @type instance: string
1135
    @param instance: Instance name
1136

1137
    """
1138
    return self._SendRequest(HTTP_GET,
1139
                             ("/%s/instances/%s/console" %
1140
                              (GANETI_RAPI_VERSION, instance)), None, None)
1141

    
1142
  def GetJobs(self):
1143
    """Gets all jobs for the cluster.
1144

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

1148
    """
1149
    return [int(j["id"])
1150
            for j in self._SendRequest(HTTP_GET,
1151
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1152
                                       None, None)]
1153

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

1157
    @type job_id: int
1158
    @param job_id: job id whose status to query
1159

1160
    @rtype: dict
1161
    @return: job status
1162

1163
    """
1164
    return self._SendRequest(HTTP_GET,
1165
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1166
                             None, None)
1167

    
1168
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1169
    """Waits for job changes.
1170

1171
    @type job_id: int
1172
    @param job_id: Job ID for which to wait
1173

1174
    """
1175
    body = {
1176
      "fields": fields,
1177
      "previous_job_info": prev_job_info,
1178
      "previous_log_serial": prev_log_serial,
1179
      }
1180

    
1181
    return self._SendRequest(HTTP_GET,
1182
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1183
                             None, body)
1184

    
1185
  def CancelJob(self, job_id, dry_run=False):
1186
    """Cancels a job.
1187

1188
    @type job_id: int
1189
    @param job_id: id of the job to delete
1190
    @type dry_run: bool
1191
    @param dry_run: whether to perform a dry run
1192

1193
    """
1194
    query = []
1195
    if dry_run:
1196
      query.append(("dry-run", 1))
1197

    
1198
    return self._SendRequest(HTTP_DELETE,
1199
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1200
                             query, None)
1201

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

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

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

1212
    """
1213
    query = []
1214
    if bulk:
1215
      query.append(("bulk", 1))
1216

    
1217
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1218
                              query, None)
1219
    if bulk:
1220
      return nodes
1221
    else:
1222
      return [n["id"] for n in nodes]
1223

    
1224
  def GetNode(self, node):
1225
    """Gets information about a node.
1226

1227
    @type node: str
1228
    @param node: node whose info to return
1229

1230
    @rtype: dict
1231
    @return: info about the node
1232

1233
    """
1234
    return self._SendRequest(HTTP_GET,
1235
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1236
                             None, None)
1237

    
1238
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1239
                   dry_run=False, early_release=False):
1240
    """Evacuates instances from a Ganeti node.
1241

1242
    @type node: str
1243
    @param node: node to evacuate
1244
    @type iallocator: str or None
1245
    @param iallocator: instance allocator to use
1246
    @type remote_node: str
1247
    @param remote_node: node to evaucate to
1248
    @type dry_run: bool
1249
    @param dry_run: whether to perform a dry run
1250
    @type early_release: bool
1251
    @param early_release: whether to enable parallelization
1252

1253
    @rtype: list
1254
    @return: list of (job ID, instance name, new secondary node); if
1255
        dry_run was specified, then the actual move jobs were not
1256
        submitted and the job IDs will be C{None}
1257

1258
    @raises GanetiApiError: if an iallocator and remote_node are both
1259
        specified
1260

1261
    """
1262
    if iallocator and remote_node:
1263
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1264

    
1265
    query = []
1266
    if iallocator:
1267
      query.append(("iallocator", iallocator))
1268
    if remote_node:
1269
      query.append(("remote_node", remote_node))
1270
    if dry_run:
1271
      query.append(("dry-run", 1))
1272
    if early_release:
1273
      query.append(("early_release", 1))
1274

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

    
1279
  def MigrateNode(self, node, mode=None, dry_run=False):
1280
    """Migrates all primary instances from a node.
1281

1282
    @type node: str
1283
    @param node: node to migrate
1284
    @type mode: string
1285
    @param mode: if passed, it will overwrite the live migration type,
1286
        otherwise the hypervisor default will be used
1287
    @type dry_run: bool
1288
    @param dry_run: whether to perform a dry run
1289

1290
    @rtype: int
1291
    @return: job id
1292

1293
    """
1294
    query = []
1295
    if mode is not None:
1296
      query.append(("mode", mode))
1297
    if dry_run:
1298
      query.append(("dry-run", 1))
1299

    
1300
    return self._SendRequest(HTTP_POST,
1301
                             ("/%s/nodes/%s/migrate" %
1302
                              (GANETI_RAPI_VERSION, node)), query, None)
1303

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

1307
    @type node: str
1308
    @param node: node whose role to return
1309

1310
    @rtype: str
1311
    @return: the current role for a node
1312

1313
    """
1314
    return self._SendRequest(HTTP_GET,
1315
                             ("/%s/nodes/%s/role" %
1316
                              (GANETI_RAPI_VERSION, node)), None, None)
1317

    
1318
  def SetNodeRole(self, node, role, force=False):
1319
    """Sets the role for a node.
1320

1321
    @type node: str
1322
    @param node: the node whose role to set
1323
    @type role: str
1324
    @param role: the role to set for the node
1325
    @type force: bool
1326
    @param force: whether to force the role change
1327

1328
    @rtype: int
1329
    @return: job id
1330

1331
    """
1332
    query = [
1333
      ("force", force),
1334
      ]
1335

    
1336
    return self._SendRequest(HTTP_PUT,
1337
                             ("/%s/nodes/%s/role" %
1338
                              (GANETI_RAPI_VERSION, node)), query, role)
1339

    
1340
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1341
    """Gets the storage units for a node.
1342

1343
    @type node: str
1344
    @param node: the node whose storage units to return
1345
    @type storage_type: str
1346
    @param storage_type: storage type whose units to return
1347
    @type output_fields: str
1348
    @param output_fields: storage type fields to return
1349

1350
    @rtype: int
1351
    @return: job id where results can be retrieved
1352

1353
    """
1354
    query = [
1355
      ("storage_type", storage_type),
1356
      ("output_fields", output_fields),
1357
      ]
1358

    
1359
    return self._SendRequest(HTTP_GET,
1360
                             ("/%s/nodes/%s/storage" %
1361
                              (GANETI_RAPI_VERSION, node)), query, None)
1362

    
1363
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1364
    """Modifies parameters of storage units on the node.
1365

1366
    @type node: str
1367
    @param node: node whose storage units to modify
1368
    @type storage_type: str
1369
    @param storage_type: storage type whose units to modify
1370
    @type name: str
1371
    @param name: name of the storage unit
1372
    @type allocatable: bool or None
1373
    @param allocatable: Whether to set the "allocatable" flag on the storage
1374
                        unit (None=no modification, True=set, False=unset)
1375

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

1379
    """
1380
    query = [
1381
      ("storage_type", storage_type),
1382
      ("name", name),
1383
      ]
1384

    
1385
    if allocatable is not None:
1386
      query.append(("allocatable", allocatable))
1387

    
1388
    return self._SendRequest(HTTP_PUT,
1389
                             ("/%s/nodes/%s/storage/modify" %
1390
                              (GANETI_RAPI_VERSION, node)), query, None)
1391

    
1392
  def RepairNodeStorageUnits(self, node, storage_type, name):
1393
    """Repairs a storage unit on the node.
1394

1395
    @type node: str
1396
    @param node: node whose storage units to repair
1397
    @type storage_type: str
1398
    @param storage_type: storage type to repair
1399
    @type name: str
1400
    @param name: name of the storage unit to repair
1401

1402
    @rtype: int
1403
    @return: job id
1404

1405
    """
1406
    query = [
1407
      ("storage_type", storage_type),
1408
      ("name", name),
1409
      ]
1410

    
1411
    return self._SendRequest(HTTP_PUT,
1412
                             ("/%s/nodes/%s/storage/repair" %
1413
                              (GANETI_RAPI_VERSION, node)), query, None)
1414

    
1415
  def GetNodeTags(self, node):
1416
    """Gets the tags for a node.
1417

1418
    @type node: str
1419
    @param node: node whose tags to return
1420

1421
    @rtype: list of str
1422
    @return: tags for the node
1423

1424
    """
1425
    return self._SendRequest(HTTP_GET,
1426
                             ("/%s/nodes/%s/tags" %
1427
                              (GANETI_RAPI_VERSION, node)), None, None)
1428

    
1429
  def AddNodeTags(self, node, tags, dry_run=False):
1430
    """Adds tags to a node.
1431

1432
    @type node: str
1433
    @param node: node to add tags to
1434
    @type tags: list of str
1435
    @param tags: tags to add to the node
1436
    @type dry_run: bool
1437
    @param dry_run: whether to perform a dry run
1438

1439
    @rtype: int
1440
    @return: job id
1441

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

    
1447
    return self._SendRequest(HTTP_PUT,
1448
                             ("/%s/nodes/%s/tags" %
1449
                              (GANETI_RAPI_VERSION, node)), query, tags)
1450

    
1451
  def DeleteNodeTags(self, node, tags, dry_run=False):
1452
    """Delete tags from a node.
1453

1454
    @type node: str
1455
    @param node: node to remove tags from
1456
    @type tags: list of str
1457
    @param tags: tags to remove from the node
1458
    @type dry_run: bool
1459
    @param dry_run: whether to perform a dry run
1460

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

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

    
1469
    return self._SendRequest(HTTP_DELETE,
1470
                             ("/%s/nodes/%s/tags" %
1471
                              (GANETI_RAPI_VERSION, node)), query, None)
1472

    
1473
  def GetGroups(self, bulk=False):
1474
    """Gets all node groups in the cluster.
1475

1476
    @type bulk: bool
1477
    @param bulk: whether to return all information about the groups
1478

1479
    @rtype: list of dict or str
1480
    @return: if bulk is true, a list of dictionaries with info about all node
1481
        groups in the cluster, else a list of names of those node groups
1482

1483
    """
1484
    query = []
1485
    if bulk:
1486
      query.append(("bulk", 1))
1487

    
1488
    groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1489
                               query, None)
1490
    if bulk:
1491
      return groups
1492
    else:
1493
      return [g["name"] for g in groups]
1494

    
1495
  def GetGroup(self, group):
1496
    """Gets information about a node group.
1497

1498
    @type group: str
1499
    @param group: name of the node group whose info to return
1500

1501
    @rtype: dict
1502
    @return: info about the node group
1503

1504
    """
1505
    return self._SendRequest(HTTP_GET,
1506
                             "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
1507
                             None, None)
1508

    
1509
  def CreateGroup(self, name, alloc_policy=None, dry_run=False):
1510
    """Creates a new node group.
1511

1512
    @type name: str
1513
    @param name: the name of node group to create
1514
    @type alloc_policy: str
1515
    @param alloc_policy: the desired allocation policy for the group, if any
1516
    @type dry_run: bool
1517
    @param dry_run: whether to peform a dry run
1518

1519
    @rtype: int
1520
    @return: job id
1521

1522
    """
1523
    query = []
1524
    if dry_run:
1525
      query.append(("dry-run", 1))
1526

    
1527
    body = {
1528
      "name": name,
1529
      "alloc_policy": alloc_policy
1530
      }
1531

    
1532
    return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1533
                             query, body)
1534

    
1535
  def ModifyGroup(self, group, **kwargs):
1536
    """Modifies a node group.
1537

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

1540
    @type group: string
1541
    @param group: Node group name
1542
    @rtype: int
1543
    @return: job id
1544

1545
    """
1546
    return self._SendRequest(HTTP_PUT,
1547
                             ("/%s/groups/%s/modify" %
1548
                              (GANETI_RAPI_VERSION, group)), None, kwargs)
1549

    
1550
  def DeleteGroup(self, group, dry_run=False):
1551
    """Deletes a node group.
1552

1553
    @type group: str
1554
    @param group: the node group to delete
1555
    @type dry_run: bool
1556
    @param dry_run: whether to peform a dry run
1557

1558
    @rtype: int
1559
    @return: job id
1560

1561
    """
1562
    query = []
1563
    if dry_run:
1564
      query.append(("dry-run", 1))
1565

    
1566
    return self._SendRequest(HTTP_DELETE,
1567
                             ("/%s/groups/%s" %
1568
                              (GANETI_RAPI_VERSION, group)), query, None)
1569

    
1570
  def RenameGroup(self, group, new_name):
1571
    """Changes the name of a node group.
1572

1573
    @type group: string
1574
    @param group: Node group name
1575
    @type new_name: string
1576
    @param new_name: New node group name
1577

1578
    @rtype: int
1579
    @return: job id
1580

1581
    """
1582
    body = {
1583
      "new_name": new_name,
1584
      }
1585

    
1586
    return self._SendRequest(HTTP_PUT,
1587
                             ("/%s/groups/%s/rename" %
1588
                              (GANETI_RAPI_VERSION, group)), None, body)
1589

    
1590

    
1591
  def AssignGroupNodes(self, group, nodes, force=False, dry_run=False):
1592
    """Assigns nodes to a group.
1593

1594
    @type group: string
1595
    @param group: Node gropu name
1596
    @type nodes: list of strings
1597
    @param nodes: List of nodes to assign to the group
1598

1599
    @rtype: int
1600
    @return: job id
1601

1602
    """
1603
    query = []
1604

    
1605
    if force:
1606
      query.append(("force", 1))
1607

    
1608
    if dry_run:
1609
      query.append(("dry-run", 1))
1610

    
1611
    body = {
1612
      "nodes": nodes,
1613
      }
1614

    
1615
    return self._SendRequest(HTTP_PUT,
1616
                             ("/%s/groups/%s/assign-nodes" %
1617
                             (GANETI_RAPI_VERSION, group)), query, body)