Statistics
| Branch: | Tag: | Revision:

root / snf-common / synnefo / util / rapi.py @ 7fb619a0

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 = json.JSONEncoder(sort_keys=True)
249

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

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

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

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

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

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

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

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

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

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

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

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

    
325
    return curl
326

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

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

336
    """
337
    result = []
338

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

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

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

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

    
353
    return result
354

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

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

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

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

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

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

    
379
    curl = self._CreateCurl()
380

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

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

    
392
    url = "".join(urlparts)
393

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

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

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

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

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

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

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

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

    
439
      raise GanetiApiError(msg, code=http_code)
440

    
441
    return response_content
442

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

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

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

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

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

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

    
467
      raise
468

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

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

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

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

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

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

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

492
    @return: job id
493

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

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

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

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

507
    """
508
    body = kwargs
509

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

635
    """
636
    query = []
637

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

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

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

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

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

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

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

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

    
690
      assert len(nics) == 1
691

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

768
    """
769
    body = kwargs
770

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1092
    """
1093
    body = {}
1094

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1591

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

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

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

1603
    """
1604
    query = []
1605

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

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

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

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