Statistics
| Branch: | Tag: | Revision:

root / util / rapi.py @ ee66adf0

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
from synnefo.logic import log
37

    
38
import socket
39
import urllib
40
import threading
41
import pycurl
42

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

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

    
53

    
54
GANETI_RAPI_PORT = 5080
55
GANETI_RAPI_VERSION = 2
56

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

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

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

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

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

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

    
101

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

105
  """
106
  pass
107

    
108

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

112
  """
113
  pass
114

    
115

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

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

    
124

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

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

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

    
142
  return wrapper
143

    
144

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

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

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

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

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

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

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

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

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

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

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

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

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

    
241
  return _ConfigCurl
242

    
243

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

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

    
251
  def __init__(self, host, port=GANETI_RAPI_PORT,
252
               username=None, password=None,
253
               logger=log.get_logger("rapi"),
254
               curl_config_fn=None, curl_factory=None):
255
    """Initializes this class.
256

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

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

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

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

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

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

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

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

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

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

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

    
326
    return curl
327

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

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

337
    """
338
    result = []
339

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

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

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

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

    
354
    return result
355

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

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

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

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

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

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

    
380
    curl = self._CreateCurl()
381

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

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

    
393
    url = "".join(urlparts)
394

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

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

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

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

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

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

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

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

    
440
      raise GanetiApiError(msg, code=http_code)
441

    
442
    return response_content
443

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

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

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

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

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

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

    
468
      raise
469

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

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

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

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

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

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

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

493
    @return: job id
494

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

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

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

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

508
    """
509
    body = kwargs
510

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

636
    """
637
    query = []
638

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

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

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

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

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

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

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

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

    
691
      assert len(nics) == 1
692

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

769
    """
770
    body = kwargs
771

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1093
    """
1094
    body = {}
1095

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1592

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

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

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

1604
    """
1605
    query = []
1606

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

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

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

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