Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ d914c76f

History | View | Annotate | Download (49.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2010, 2011 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Ganeti RAPI client.
23

24
@attention: To use the RAPI client, the application B{must} call
25
            C{pycurl.global_init} during initialization and
26
            C{pycurl.global_cleanup} before exiting the process. This is very
27
            important in multi-threaded programs. See curl_global_init(3) and
28
            curl_global_cleanup(3) for details. The decorator L{UsesRapiClient}
29
            can be used.
30

31
"""
32

    
33
# No Ganeti-specific modules should be imported. The RAPI client is supposed to
34
# be standalone.
35

    
36
import logging
37
import simplejson
38
import socket
39
import urllib
40
import threading
41
import pycurl
42
import time
43

    
44
try:
45
  from cStringIO import StringIO
46
except ImportError:
47
  from StringIO import StringIO
48

    
49

    
50
GANETI_RAPI_PORT = 5080
51
GANETI_RAPI_VERSION = 2
52

    
53
HTTP_DELETE = "DELETE"
54
HTTP_GET = "GET"
55
HTTP_PUT = "PUT"
56
HTTP_POST = "POST"
57
HTTP_OK = 200
58
HTTP_NOT_FOUND = 404
59
HTTP_APP_JSON = "application/json"
60

    
61
REPLACE_DISK_PRI = "replace_on_primary"
62
REPLACE_DISK_SECONDARY = "replace_on_secondary"
63
REPLACE_DISK_CHG = "replace_new_secondary"
64
REPLACE_DISK_AUTO = "replace_auto"
65

    
66
NODE_ROLE_DRAINED = "drained"
67
NODE_ROLE_MASTER_CANDIATE = "master-candidate"
68
NODE_ROLE_MASTER = "master"
69
NODE_ROLE_OFFLINE = "offline"
70
NODE_ROLE_REGULAR = "regular"
71

    
72
JOB_STATUS_QUEUED = "queued"
73
JOB_STATUS_WAITLOCK = "waiting"
74
JOB_STATUS_CANCELING = "canceling"
75
JOB_STATUS_RUNNING = "running"
76
JOB_STATUS_CANCELED = "canceled"
77
JOB_STATUS_SUCCESS = "success"
78
JOB_STATUS_ERROR = "error"
79
JOB_STATUS_FINALIZED = frozenset([
80
  JOB_STATUS_CANCELED,
81
  JOB_STATUS_SUCCESS,
82
  JOB_STATUS_ERROR,
83
  ])
84
JOB_STATUS_ALL = frozenset([
85
  JOB_STATUS_QUEUED,
86
  JOB_STATUS_WAITLOCK,
87
  JOB_STATUS_CANCELING,
88
  JOB_STATUS_RUNNING,
89
  ]) | JOB_STATUS_FINALIZED
90

    
91
# Internal constants
92
_REQ_DATA_VERSION_FIELD = "__version__"
93
_INST_CREATE_REQV1 = "instance-create-reqv1"
94
_INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
95
_INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link"])
96
_INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
97
_INST_CREATE_V0_PARAMS = frozenset([
98
  "os", "pnode", "snode", "iallocator", "start", "ip_check", "name_check",
99
  "hypervisor", "file_storage_dir", "file_driver", "dry_run",
100
  ])
101
_INST_CREATE_V0_DPARAMS = frozenset(["beparams", "hvparams"])
102

    
103
# Older pycURL versions don't have all error constants
104
try:
105
  _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
106
  _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
107
except AttributeError:
108
  _CURLE_SSL_CACERT = 60
109
  _CURLE_SSL_CACERT_BADFILE = 77
110

    
111
_CURL_SSL_CERT_ERRORS = frozenset([
112
  _CURLE_SSL_CACERT,
113
  _CURLE_SSL_CACERT_BADFILE,
114
  ])
115

    
116

    
117
class Error(Exception):
118
  """Base error class for this module.
119

120
  """
121
  pass
122

    
123

    
124
class CertificateError(Error):
125
  """Raised when a problem is found with the SSL certificate.
126

127
  """
128
  pass
129

    
130

    
131
class GanetiApiError(Error):
132
  """Generic error raised from Ganeti API.
133

134
  """
135
  def __init__(self, msg, code=None):
136
    Error.__init__(self, msg)
137
    self.code = code
138

    
139

    
140
def UsesRapiClient(fn):
141
  """Decorator for code using RAPI client to initialize pycURL.
142

143
  """
144
  def wrapper(*args, **kwargs):
145
    # curl_global_init(3) and curl_global_cleanup(3) must be called with only
146
    # one thread running. This check is just a safety measure -- it doesn't
147
    # cover all cases.
148
    assert threading.activeCount() == 1, \
149
           "Found active threads when initializing pycURL"
150

    
151
    pycurl.global_init(pycurl.GLOBAL_ALL)
152
    try:
153
      return fn(*args, **kwargs)
154
    finally:
155
      pycurl.global_cleanup()
156

    
157
  return wrapper
158

    
159

    
160
def GenericCurlConfig(verbose=False, use_signal=False,
161
                      use_curl_cabundle=False, cafile=None, capath=None,
162
                      proxy=None, verify_hostname=False,
163
                      connect_timeout=None, timeout=None,
164
                      _pycurl_version_fn=pycurl.version_info):
165
  """Curl configuration function generator.
166

167
  @type verbose: bool
168
  @param verbose: Whether to set cURL to verbose mode
169
  @type use_signal: bool
170
  @param use_signal: Whether to allow cURL to use signals
171
  @type use_curl_cabundle: bool
172
  @param use_curl_cabundle: Whether to use cURL's default CA bundle
173
  @type cafile: string
174
  @param cafile: In which file we can find the certificates
175
  @type capath: string
176
  @param capath: In which directory we can find the certificates
177
  @type proxy: string
178
  @param proxy: Proxy to use, None for default behaviour and empty string for
179
                disabling proxies (see curl_easy_setopt(3))
180
  @type verify_hostname: bool
181
  @param verify_hostname: Whether to verify the remote peer certificate's
182
                          commonName
183
  @type connect_timeout: number
184
  @param connect_timeout: Timeout for establishing connection in seconds
185
  @type timeout: number
186
  @param timeout: Timeout for complete transfer in seconds (see
187
                  curl_easy_setopt(3)).
188

189
  """
190
  if use_curl_cabundle and (cafile or capath):
191
    raise Error("Can not use default CA bundle when CA file or path is set")
192

    
193
  def _ConfigCurl(curl, logger):
194
    """Configures a cURL object
195

196
    @type curl: pycurl.Curl
197
    @param curl: cURL object
198

199
    """
200
    logger.debug("Using cURL version %s", pycurl.version)
201

    
202
    # pycurl.version_info returns a tuple with information about the used
203
    # version of libcurl. Item 5 is the SSL library linked to it.
204
    # e.g.: (3, '7.18.0', 463360, 'x86_64-pc-linux-gnu', 1581, 'GnuTLS/2.0.4',
205
    # 0, '1.2.3.3', ...)
206
    sslver = _pycurl_version_fn()[5]
207
    if not sslver:
208
      raise Error("No SSL support in cURL")
209

    
210
    lcsslver = sslver.lower()
211
    if lcsslver.startswith("openssl/"):
212
      pass
213
    elif lcsslver.startswith("gnutls/"):
214
      if capath:
215
        raise Error("cURL linked against GnuTLS has no support for a"
216
                    " CA path (%s)" % (pycurl.version, ))
217
    else:
218
      raise NotImplementedError("cURL uses unsupported SSL version '%s'" %
219
                                sslver)
220

    
221
    curl.setopt(pycurl.VERBOSE, verbose)
222
    curl.setopt(pycurl.NOSIGNAL, not use_signal)
223

    
224
    # Whether to verify remote peer's CN
225
    if verify_hostname:
226
      # curl_easy_setopt(3): "When CURLOPT_SSL_VERIFYHOST is 2, that
227
      # certificate must indicate that the server is the server to which you
228
      # meant to connect, or the connection fails. [...] When the value is 1,
229
      # the certificate must contain a Common Name field, but it doesn't matter
230
      # what name it says. [...]"
231
      curl.setopt(pycurl.SSL_VERIFYHOST, 2)
232
    else:
233
      curl.setopt(pycurl.SSL_VERIFYHOST, 0)
234

    
235
    if cafile or capath or use_curl_cabundle:
236
      # Require certificates to be checked
237
      curl.setopt(pycurl.SSL_VERIFYPEER, True)
238
      if cafile:
239
        curl.setopt(pycurl.CAINFO, str(cafile))
240
      if capath:
241
        curl.setopt(pycurl.CAPATH, str(capath))
242
      # Not changing anything for using default CA bundle
243
    else:
244
      # Disable SSL certificate verification
245
      curl.setopt(pycurl.SSL_VERIFYPEER, False)
246

    
247
    if proxy is not None:
248
      curl.setopt(pycurl.PROXY, str(proxy))
249

    
250
    # Timeouts
251
    if connect_timeout is not None:
252
      curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
253
    if timeout is not None:
254
      curl.setopt(pycurl.TIMEOUT, timeout)
255

    
256
  return _ConfigCurl
257

    
258

    
259
class GanetiRapiClient(object): # pylint: disable-msg=R0904
260
  """Ganeti RAPI client.
261

262
  """
263
  USER_AGENT = "Ganeti RAPI Client"
264
  _json_encoder = simplejson.JSONEncoder(sort_keys=True)
265

    
266
  def __init__(self, host, port=GANETI_RAPI_PORT,
267
               username=None, password=None, logger=logging,
268
               curl_config_fn=None, curl_factory=None):
269
    """Initializes this class.
270

271
    @type host: string
272
    @param host: the ganeti cluster master to interact with
273
    @type port: int
274
    @param port: the port on which the RAPI is running (default is 5080)
275
    @type username: string
276
    @param username: the username to connect with
277
    @type password: string
278
    @param password: the password to connect with
279
    @type curl_config_fn: callable
280
    @param curl_config_fn: Function to configure C{pycurl.Curl} object
281
    @param logger: Logging object
282

283
    """
284
    self._username = username
285
    self._password = password
286
    self._logger = logger
287
    self._curl_config_fn = curl_config_fn
288
    self._curl_factory = curl_factory
289

    
290
    try:
291
      socket.inet_pton(socket.AF_INET6, host)
292
      address = "[%s]:%s" % (host, port)
293
    except socket.error:
294
      address = "%s:%s" % (host, port)
295

    
296
    self._base_url = "https://%s" % address
297

    
298
    if username is not None:
299
      if password is None:
300
        raise Error("Password not specified")
301
    elif password:
302
      raise Error("Specified password without username")
303

    
304
  def _CreateCurl(self):
305
    """Creates a cURL object.
306

307
    """
308
    # Create pycURL object if no factory is provided
309
    if self._curl_factory:
310
      curl = self._curl_factory()
311
    else:
312
      curl = pycurl.Curl()
313

    
314
    # Default cURL settings
315
    curl.setopt(pycurl.VERBOSE, False)
316
    curl.setopt(pycurl.FOLLOWLOCATION, False)
317
    curl.setopt(pycurl.MAXREDIRS, 5)
318
    curl.setopt(pycurl.NOSIGNAL, True)
319
    curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
320
    curl.setopt(pycurl.SSL_VERIFYHOST, 0)
321
    curl.setopt(pycurl.SSL_VERIFYPEER, False)
322
    curl.setopt(pycurl.HTTPHEADER, [
323
      "Accept: %s" % HTTP_APP_JSON,
324
      "Content-type: %s" % HTTP_APP_JSON,
325
      ])
326

    
327
    assert ((self._username is None and self._password is None) ^
328
            (self._username is not None and self._password is not None))
329

    
330
    if self._username:
331
      # Setup authentication
332
      curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
333
      curl.setopt(pycurl.USERPWD,
334
                  str("%s:%s" % (self._username, self._password)))
335

    
336
    # Call external configuration function
337
    if self._curl_config_fn:
338
      self._curl_config_fn(curl, self._logger)
339

    
340
    return curl
341

    
342
  @staticmethod
343
  def _EncodeQuery(query):
344
    """Encode query values for RAPI URL.
345

346
    @type query: list of two-tuples
347
    @param query: Query arguments
348
    @rtype: list
349
    @return: Query list with encoded values
350

351
    """
352
    result = []
353

    
354
    for name, value in query:
355
      if value is None:
356
        result.append((name, ""))
357

    
358
      elif isinstance(value, bool):
359
        # Boolean values must be encoded as 0 or 1
360
        result.append((name, int(value)))
361

    
362
      elif isinstance(value, (list, tuple, dict)):
363
        raise ValueError("Invalid query data type %r" % type(value).__name__)
364

    
365
      else:
366
        result.append((name, value))
367

    
368
    return result
369

    
370
  def _SendRequest(self, method, path, query, content):
371
    """Sends an HTTP request.
372

373
    This constructs a full URL, encodes and decodes HTTP bodies, and
374
    handles invalid responses in a pythonic way.
375

376
    @type method: string
377
    @param method: HTTP method to use
378
    @type path: string
379
    @param path: HTTP URL path
380
    @type query: list of two-tuples
381
    @param query: query arguments to pass to urllib.urlencode
382
    @type content: str or None
383
    @param content: HTTP body content
384

385
    @rtype: str
386
    @return: JSON-Decoded response
387

388
    @raises CertificateError: If an invalid SSL certificate is found
389
    @raises GanetiApiError: If an invalid response is returned
390

391
    """
392
    assert path.startswith("/")
393

    
394
    curl = self._CreateCurl()
395

    
396
    if content is not None:
397
      encoded_content = self._json_encoder.encode(content)
398
    else:
399
      encoded_content = ""
400

    
401
    # Build URL
402
    urlparts = [self._base_url, path]
403
    if query:
404
      urlparts.append("?")
405
      urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
406

    
407
    url = "".join(urlparts)
408

    
409
    self._logger.debug("Sending request %s %s (content=%r)",
410
                       method, url, encoded_content)
411

    
412
    # Buffer for response
413
    encoded_resp_body = StringIO()
414

    
415
    # Configure cURL
416
    curl.setopt(pycurl.CUSTOMREQUEST, str(method))
417
    curl.setopt(pycurl.URL, str(url))
418
    curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
419
    curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
420

    
421
    try:
422
      # Send request and wait for response
423
      try:
424
        curl.perform()
425
      except pycurl.error, err:
426
        if err.args[0] in _CURL_SSL_CERT_ERRORS:
427
          raise CertificateError("SSL certificate error %s" % err)
428

    
429
        raise GanetiApiError(str(err))
430
    finally:
431
      # Reset settings to not keep references to large objects in memory
432
      # between requests
433
      curl.setopt(pycurl.POSTFIELDS, "")
434
      curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)
435

    
436
    # Get HTTP response code
437
    http_code = curl.getinfo(pycurl.RESPONSE_CODE)
438

    
439
    # Was anything written to the response buffer?
440
    if encoded_resp_body.tell():
441
      response_content = simplejson.loads(encoded_resp_body.getvalue())
442
    else:
443
      response_content = None
444

    
445
    if http_code != HTTP_OK:
446
      if isinstance(response_content, dict):
447
        msg = ("%s %s: %s" %
448
               (response_content["code"],
449
                response_content["message"],
450
                response_content["explain"]))
451
      else:
452
        msg = str(response_content)
453

    
454
      raise GanetiApiError(msg, code=http_code)
455

    
456
    return response_content
457

    
458
  def GetVersion(self):
459
    """Gets the Remote API version running on the cluster.
460

461
    @rtype: int
462
    @return: Ganeti Remote API version
463

464
    """
465
    return self._SendRequest(HTTP_GET, "/version", None, None)
466

    
467
  def GetFeatures(self):
468
    """Gets the list of optional features supported by RAPI server.
469

470
    @rtype: list
471
    @return: List of optional features
472

473
    """
474
    try:
475
      return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
476
                               None, None)
477
    except GanetiApiError, err:
478
      # Older RAPI servers don't support this resource
479
      if err.code == HTTP_NOT_FOUND:
480
        return []
481

    
482
      raise
483

    
484
  def GetOperatingSystems(self):
485
    """Gets the Operating Systems running in the Ganeti cluster.
486

487
    @rtype: list of str
488
    @return: operating systems
489

490
    """
491
    return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
492
                             None, None)
493

    
494
  def GetInfo(self):
495
    """Gets info about the cluster.
496

497
    @rtype: dict
498
    @return: information about the cluster
499

500
    """
501
    return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
502
                             None, None)
503

    
504
  def RedistributeConfig(self):
505
    """Tells the cluster to redistribute its configuration files.
506

507
    @rtype: string
508
    @return: job id
509

510
    """
511
    return self._SendRequest(HTTP_PUT,
512
                             "/%s/redistribute-config" % GANETI_RAPI_VERSION,
513
                             None, None)
514

    
515
  def ModifyCluster(self, **kwargs):
516
    """Modifies cluster parameters.
517

518
    More details for parameters can be found in the RAPI documentation.
519

520
    @rtype: string
521
    @return: job id
522

523
    """
524
    body = kwargs
525

    
526
    return self._SendRequest(HTTP_PUT,
527
                             "/%s/modify" % GANETI_RAPI_VERSION, None, body)
528

    
529
  def GetClusterTags(self):
530
    """Gets the cluster tags.
531

532
    @rtype: list of str
533
    @return: cluster tags
534

535
    """
536
    return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
537
                             None, None)
538

    
539
  def AddClusterTags(self, tags, dry_run=False):
540
    """Adds tags to the cluster.
541

542
    @type tags: list of str
543
    @param tags: tags to add to the cluster
544
    @type dry_run: bool
545
    @param dry_run: whether to perform a dry run
546

547
    @rtype: string
548
    @return: job id
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_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
556
                             query, None)
557

    
558
  def DeleteClusterTags(self, tags, dry_run=False):
559
    """Deletes tags from the cluster.
560

561
    @type tags: list of str
562
    @param tags: tags to delete
563
    @type dry_run: bool
564
    @param dry_run: whether to perform a dry run
565
    @rtype: string
566
    @return: job id
567

568
    """
569
    query = [("tag", t) for t in tags]
570
    if dry_run:
571
      query.append(("dry-run", 1))
572

    
573
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
574
                             query, None)
575

    
576
  def GetInstances(self, bulk=False):
577
    """Gets information about instances on the cluster.
578

579
    @type bulk: bool
580
    @param bulk: whether to return all information about all instances
581

582
    @rtype: list of dict or list of str
583
    @return: if bulk is True, info about the instances, else a list of instances
584

585
    """
586
    query = []
587
    if bulk:
588
      query.append(("bulk", 1))
589

    
590
    instances = self._SendRequest(HTTP_GET,
591
                                  "/%s/instances" % GANETI_RAPI_VERSION,
592
                                  query, None)
593
    if bulk:
594
      return instances
595
    else:
596
      return [i["id"] for i in instances]
597

    
598
  def GetInstance(self, instance):
599
    """Gets information about an instance.
600

601
    @type instance: str
602
    @param instance: instance whose info to return
603

604
    @rtype: dict
605
    @return: info about the instance
606

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

    
612
  def GetInstanceInfo(self, instance, static=None):
613
    """Gets information about an instance.
614

615
    @type instance: string
616
    @param instance: Instance name
617
    @rtype: string
618
    @return: Job ID
619

620
    """
621
    if static is not None:
622
      query = [("static", static)]
623
    else:
624
      query = None
625

    
626
    return self._SendRequest(HTTP_GET,
627
                             ("/%s/instances/%s/info" %
628
                              (GANETI_RAPI_VERSION, instance)), query, None)
629

    
630
  def CreateInstance(self, mode, name, disk_template, disks, nics,
631
                     **kwargs):
632
    """Creates a new instance.
633

634
    More details for parameters can be found in the RAPI documentation.
635

636
    @type mode: string
637
    @param mode: Instance creation mode
638
    @type name: string
639
    @param name: Hostname of the instance to create
640
    @type disk_template: string
641
    @param disk_template: Disk template for instance (e.g. plain, diskless,
642
                          file, or drbd)
643
    @type disks: list of dicts
644
    @param disks: List of disk definitions
645
    @type nics: list of dicts
646
    @param nics: List of NIC definitions
647
    @type dry_run: bool
648
    @keyword dry_run: whether to perform a dry run
649

650
    @rtype: string
651
    @return: job id
652

653
    """
654
    query = []
655

    
656
    if kwargs.get("dry_run"):
657
      query.append(("dry-run", 1))
658

    
659
    if _INST_CREATE_REQV1 in self.GetFeatures():
660
      # All required fields for request data version 1
661
      body = {
662
        _REQ_DATA_VERSION_FIELD: 1,
663
        "mode": mode,
664
        "name": name,
665
        "disk_template": disk_template,
666
        "disks": disks,
667
        "nics": nics,
668
        }
669

    
670
      conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
671
      if conflicts:
672
        raise GanetiApiError("Required fields can not be specified as"
673
                             " keywords: %s" % ", ".join(conflicts))
674

    
675
      body.update((key, value) for key, value in kwargs.iteritems()
676
                  if key != "dry_run")
677
    else:
678
      # Old request format (version 0)
679

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

    
686
      # Validate disks
687
      for idx, disk in enumerate(disks):
688
        unsupported = set(disk.keys()) - _INST_CREATE_V0_DISK_PARAMS
689
        if unsupported:
690
          raise GanetiApiError("Server supports request version 0 only, but"
691
                               " disk %s specifies the unsupported parameters"
692
                               " %s, allowed are %s" %
693
                               (idx, unsupported,
694
                                list(_INST_CREATE_V0_DISK_PARAMS)))
695

    
696
      assert (len(_INST_CREATE_V0_DISK_PARAMS) == 1 and
697
              "size" in _INST_CREATE_V0_DISK_PARAMS)
698
      disk_sizes = [disk["size"] for disk in disks]
699

    
700
      # Validate NICs
701
      if not nics:
702
        raise GanetiApiError("Server supports request version 0 only, but"
703
                             " no NIC specified")
704
      elif len(nics) > 1:
705
        raise GanetiApiError("Server supports request version 0 only, but"
706
                             " more than one NIC specified")
707

    
708
      assert len(nics) == 1
709

    
710
      unsupported = set(nics[0].keys()) - _INST_NIC_PARAMS
711
      if unsupported:
712
        raise GanetiApiError("Server supports request version 0 only, but"
713
                             " NIC 0 specifies the unsupported parameters %s,"
714
                             " allowed are %s" %
715
                             (unsupported, list(_INST_NIC_PARAMS)))
716

    
717
      # Validate other parameters
718
      unsupported = (set(kwargs.keys()) - _INST_CREATE_V0_PARAMS -
719
                     _INST_CREATE_V0_DPARAMS)
720
      if unsupported:
721
        allowed = _INST_CREATE_V0_PARAMS.union(_INST_CREATE_V0_DPARAMS)
722
        raise GanetiApiError("Server supports request version 0 only, but"
723
                             " the following unsupported parameters are"
724
                             " specified: %s, allowed are %s" %
725
                             (unsupported, list(allowed)))
726

    
727
      # All required fields for request data version 0
728
      body = {
729
        _REQ_DATA_VERSION_FIELD: 0,
730
        "name": name,
731
        "disk_template": disk_template,
732
        "disks": disk_sizes,
733
        }
734

    
735
      # NIC fields
736
      assert len(nics) == 1
737
      assert not (set(body.keys()) & set(nics[0].keys()))
738
      body.update(nics[0])
739

    
740
      # Copy supported fields
741
      assert not (set(body.keys()) & set(kwargs.keys()))
742
      body.update(dict((key, value) for key, value in kwargs.items()
743
                       if key in _INST_CREATE_V0_PARAMS))
744

    
745
      # Merge dictionaries
746
      for i in (value for key, value in kwargs.items()
747
                if key in _INST_CREATE_V0_DPARAMS):
748
        assert not (set(body.keys()) & set(i.keys()))
749
        body.update(i)
750

    
751
      assert not (set(kwargs.keys()) -
752
                  (_INST_CREATE_V0_PARAMS | _INST_CREATE_V0_DPARAMS))
753
      assert not (set(body.keys()) & _INST_CREATE_V0_DPARAMS)
754

    
755
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
756
                             query, body)
757

    
758
  def DeleteInstance(self, instance, dry_run=False):
759
    """Deletes an instance.
760

761
    @type instance: str
762
    @param instance: the instance to delete
763

764
    @rtype: string
765
    @return: job id
766

767
    """
768
    query = []
769
    if dry_run:
770
      query.append(("dry-run", 1))
771

    
772
    return self._SendRequest(HTTP_DELETE,
773
                             ("/%s/instances/%s" %
774
                              (GANETI_RAPI_VERSION, instance)), query, None)
775

    
776
  def ModifyInstance(self, instance, **kwargs):
777
    """Modifies an instance.
778

779
    More details for parameters can be found in the RAPI documentation.
780

781
    @type instance: string
782
    @param instance: Instance name
783
    @rtype: string
784
    @return: job id
785

786
    """
787
    body = kwargs
788

    
789
    return self._SendRequest(HTTP_PUT,
790
                             ("/%s/instances/%s/modify" %
791
                              (GANETI_RAPI_VERSION, instance)), None, body)
792

    
793
  def ActivateInstanceDisks(self, instance, ignore_size=None):
794
    """Activates an instance's disks.
795

796
    @type instance: string
797
    @param instance: Instance name
798
    @type ignore_size: bool
799
    @param ignore_size: Whether to ignore recorded size
800
    @rtype: string
801
    @return: job id
802

803
    """
804
    query = []
805
    if ignore_size:
806
      query.append(("ignore_size", 1))
807

    
808
    return self._SendRequest(HTTP_PUT,
809
                             ("/%s/instances/%s/activate-disks" %
810
                              (GANETI_RAPI_VERSION, instance)), query, None)
811

    
812
  def DeactivateInstanceDisks(self, instance):
813
    """Deactivates an instance's disks.
814

815
    @type instance: string
816
    @param instance: Instance name
817
    @rtype: string
818
    @return: job id
819

820
    """
821
    return self._SendRequest(HTTP_PUT,
822
                             ("/%s/instances/%s/deactivate-disks" %
823
                              (GANETI_RAPI_VERSION, instance)), None, None)
824

    
825
  def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
826
    """Grows a disk of an instance.
827

828
    More details for parameters can be found in the RAPI documentation.
829

830
    @type instance: string
831
    @param instance: Instance name
832
    @type disk: integer
833
    @param disk: Disk index
834
    @type amount: integer
835
    @param amount: Grow disk by this amount (MiB)
836
    @type wait_for_sync: bool
837
    @param wait_for_sync: Wait for disk to synchronize
838
    @rtype: string
839
    @return: job id
840

841
    """
842
    body = {
843
      "amount": amount,
844
      }
845

    
846
    if wait_for_sync is not None:
847
      body["wait_for_sync"] = wait_for_sync
848

    
849
    return self._SendRequest(HTTP_POST,
850
                             ("/%s/instances/%s/disk/%s/grow" %
851
                              (GANETI_RAPI_VERSION, instance, disk)),
852
                             None, body)
853

    
854
  def GetInstanceTags(self, instance):
855
    """Gets tags for an instance.
856

857
    @type instance: str
858
    @param instance: instance whose tags to return
859

860
    @rtype: list of str
861
    @return: tags for the instance
862

863
    """
864
    return self._SendRequest(HTTP_GET,
865
                             ("/%s/instances/%s/tags" %
866
                              (GANETI_RAPI_VERSION, instance)), None, None)
867

    
868
  def AddInstanceTags(self, instance, tags, dry_run=False):
869
    """Adds tags to an instance.
870

871
    @type instance: str
872
    @param instance: instance to add tags to
873
    @type tags: list of str
874
    @param tags: tags to add to the instance
875
    @type dry_run: bool
876
    @param dry_run: whether to perform a dry run
877

878
    @rtype: string
879
    @return: job id
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_PUT,
887
                             ("/%s/instances/%s/tags" %
888
                              (GANETI_RAPI_VERSION, instance)), query, None)
889

    
890
  def DeleteInstanceTags(self, instance, tags, dry_run=False):
891
    """Deletes tags from an instance.
892

893
    @type instance: str
894
    @param instance: instance to delete tags from
895
    @type tags: list of str
896
    @param tags: tags to delete
897
    @type dry_run: bool
898
    @param dry_run: whether to perform a dry run
899
    @rtype: string
900
    @return: job id
901

902
    """
903
    query = [("tag", t) for t in tags]
904
    if dry_run:
905
      query.append(("dry-run", 1))
906

    
907
    return self._SendRequest(HTTP_DELETE,
908
                             ("/%s/instances/%s/tags" %
909
                              (GANETI_RAPI_VERSION, instance)), query, None)
910

    
911
  def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
912
                     dry_run=False):
913
    """Reboots an instance.
914

915
    @type instance: str
916
    @param instance: instance to rebot
917
    @type reboot_type: str
918
    @param reboot_type: one of: hard, soft, full
919
    @type ignore_secondaries: bool
920
    @param ignore_secondaries: if True, ignores errors for the secondary node
921
        while re-assembling disks (in hard-reboot mode only)
922
    @type dry_run: bool
923
    @param dry_run: whether to perform a dry run
924
    @rtype: string
925
    @return: job id
926

927
    """
928
    query = []
929
    if reboot_type:
930
      query.append(("type", reboot_type))
931
    if ignore_secondaries is not None:
932
      query.append(("ignore_secondaries", ignore_secondaries))
933
    if dry_run:
934
      query.append(("dry-run", 1))
935

    
936
    return self._SendRequest(HTTP_POST,
937
                             ("/%s/instances/%s/reboot" %
938
                              (GANETI_RAPI_VERSION, instance)), query, None)
939

    
940
  def ShutdownInstance(self, instance, dry_run=False):
941
    """Shuts down an instance.
942

943
    @type instance: str
944
    @param instance: the instance to shut down
945
    @type dry_run: bool
946
    @param dry_run: whether to perform a dry run
947
    @rtype: string
948
    @return: job id
949

950
    """
951
    query = []
952
    if dry_run:
953
      query.append(("dry-run", 1))
954

    
955
    return self._SendRequest(HTTP_PUT,
956
                             ("/%s/instances/%s/shutdown" %
957
                              (GANETI_RAPI_VERSION, instance)), query, None)
958

    
959
  def StartupInstance(self, instance, dry_run=False):
960
    """Starts up an instance.
961

962
    @type instance: str
963
    @param instance: the instance to start up
964
    @type dry_run: bool
965
    @param dry_run: whether to perform a dry run
966
    @rtype: string
967
    @return: job id
968

969
    """
970
    query = []
971
    if dry_run:
972
      query.append(("dry-run", 1))
973

    
974
    return self._SendRequest(HTTP_PUT,
975
                             ("/%s/instances/%s/startup" %
976
                              (GANETI_RAPI_VERSION, instance)), query, None)
977

    
978
  def ReinstallInstance(self, instance, os=None, no_startup=False,
979
                        osparams=None):
980
    """Reinstalls an instance.
981

982
    @type instance: str
983
    @param instance: The instance to reinstall
984
    @type os: str or None
985
    @param os: The operating system to reinstall. If None, the instance's
986
        current operating system will be installed again
987
    @type no_startup: bool
988
    @param no_startup: Whether to start the instance automatically
989
    @rtype: string
990
    @return: job id
991

992
    """
993
    if _INST_REINSTALL_REQV1 in self.GetFeatures():
994
      body = {
995
        "start": not no_startup,
996
        }
997
      if os is not None:
998
        body["os"] = os
999
      if osparams is not None:
1000
        body["osparams"] = osparams
1001
      return self._SendRequest(HTTP_POST,
1002
                               ("/%s/instances/%s/reinstall" %
1003
                                (GANETI_RAPI_VERSION, instance)), None, body)
1004

    
1005
    # Use old request format
1006
    if osparams:
1007
      raise GanetiApiError("Server does not support specifying OS parameters"
1008
                           " for instance reinstallation")
1009

    
1010
    query = []
1011
    if os:
1012
      query.append(("os", os))
1013
    if no_startup:
1014
      query.append(("nostartup", 1))
1015
    return self._SendRequest(HTTP_POST,
1016
                             ("/%s/instances/%s/reinstall" %
1017
                              (GANETI_RAPI_VERSION, instance)), query, None)
1018

    
1019
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
1020
                           remote_node=None, iallocator=None, dry_run=False):
1021
    """Replaces disks on an instance.
1022

1023
    @type instance: str
1024
    @param instance: instance whose disks to replace
1025
    @type disks: list of ints
1026
    @param disks: Indexes of disks to replace
1027
    @type mode: str
1028
    @param mode: replacement mode to use (defaults to replace_auto)
1029
    @type remote_node: str or None
1030
    @param remote_node: new secondary node to use (for use with
1031
        replace_new_secondary mode)
1032
    @type iallocator: str or None
1033
    @param iallocator: instance allocator plugin to use (for use with
1034
                       replace_auto mode)
1035
    @type dry_run: bool
1036
    @param dry_run: whether to perform a dry run
1037

1038
    @rtype: string
1039
    @return: job id
1040

1041
    """
1042
    query = [
1043
      ("mode", mode),
1044
      ]
1045

    
1046
    if disks:
1047
      query.append(("disks", ",".join(str(idx) for idx in disks)))
1048

    
1049
    if remote_node:
1050
      query.append(("remote_node", remote_node))
1051

    
1052
    if iallocator:
1053
      query.append(("iallocator", iallocator))
1054

    
1055
    if dry_run:
1056
      query.append(("dry-run", 1))
1057

    
1058
    return self._SendRequest(HTTP_POST,
1059
                             ("/%s/instances/%s/replace-disks" %
1060
                              (GANETI_RAPI_VERSION, instance)), query, None)
1061

    
1062
  def PrepareExport(self, instance, mode):
1063
    """Prepares an instance for an export.
1064

1065
    @type instance: string
1066
    @param instance: Instance name
1067
    @type mode: string
1068
    @param mode: Export mode
1069
    @rtype: string
1070
    @return: Job ID
1071

1072
    """
1073
    query = [("mode", mode)]
1074
    return self._SendRequest(HTTP_PUT,
1075
                             ("/%s/instances/%s/prepare-export" %
1076
                              (GANETI_RAPI_VERSION, instance)), query, None)
1077

    
1078
  def ExportInstance(self, instance, mode, destination, shutdown=None,
1079
                     remove_instance=None,
1080
                     x509_key_name=None, destination_x509_ca=None):
1081
    """Exports an instance.
1082

1083
    @type instance: string
1084
    @param instance: Instance name
1085
    @type mode: string
1086
    @param mode: Export mode
1087
    @rtype: string
1088
    @return: Job ID
1089

1090
    """
1091
    body = {
1092
      "destination": destination,
1093
      "mode": mode,
1094
      }
1095

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

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

    
1102
    if x509_key_name is not None:
1103
      body["x509_key_name"] = x509_key_name
1104

    
1105
    if destination_x509_ca is not None:
1106
      body["destination_x509_ca"] = destination_x509_ca
1107

    
1108
    return self._SendRequest(HTTP_PUT,
1109
                             ("/%s/instances/%s/export" %
1110
                              (GANETI_RAPI_VERSION, instance)), None, body)
1111

    
1112
  def MigrateInstance(self, instance, mode=None, cleanup=None):
1113
    """Migrates an instance.
1114

1115
    @type instance: string
1116
    @param instance: Instance name
1117
    @type mode: string
1118
    @param mode: Migration mode
1119
    @type cleanup: bool
1120
    @param cleanup: Whether to clean up a previously failed migration
1121
    @rtype: string
1122
    @return: job id
1123

1124
    """
1125
    body = {}
1126

    
1127
    if mode is not None:
1128
      body["mode"] = mode
1129

    
1130
    if cleanup is not None:
1131
      body["cleanup"] = cleanup
1132

    
1133
    return self._SendRequest(HTTP_PUT,
1134
                             ("/%s/instances/%s/migrate" %
1135
                              (GANETI_RAPI_VERSION, instance)), None, body)
1136

    
1137
  def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
1138
    """Changes the name of an instance.
1139

1140
    @type instance: string
1141
    @param instance: Instance name
1142
    @type new_name: string
1143
    @param new_name: New instance name
1144
    @type ip_check: bool
1145
    @param ip_check: Whether to ensure instance's IP address is inactive
1146
    @type name_check: bool
1147
    @param name_check: Whether to ensure instance's name is resolvable
1148
    @rtype: string
1149
    @return: job id
1150

1151
    """
1152
    body = {
1153
      "new_name": new_name,
1154
      }
1155

    
1156
    if ip_check is not None:
1157
      body["ip_check"] = ip_check
1158

    
1159
    if name_check is not None:
1160
      body["name_check"] = name_check
1161

    
1162
    return self._SendRequest(HTTP_PUT,
1163
                             ("/%s/instances/%s/rename" %
1164
                              (GANETI_RAPI_VERSION, instance)), None, body)
1165

    
1166
  def GetInstanceConsole(self, instance):
1167
    """Request information for connecting to instance's console.
1168

1169
    @type instance: string
1170
    @param instance: Instance name
1171
    @rtype: dict
1172
    @return: dictionary containing information about instance's console
1173

1174
    """
1175
    return self._SendRequest(HTTP_GET,
1176
                             ("/%s/instances/%s/console" %
1177
                              (GANETI_RAPI_VERSION, instance)), None, None)
1178

    
1179
  def GetJobs(self):
1180
    """Gets all jobs for the cluster.
1181

1182
    @rtype: list of int
1183
    @return: job ids for the cluster
1184

1185
    """
1186
    return [int(j["id"])
1187
            for j in self._SendRequest(HTTP_GET,
1188
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1189
                                       None, None)]
1190

    
1191
  def GetJobStatus(self, job_id):
1192
    """Gets the status of a job.
1193

1194
    @type job_id: string
1195
    @param job_id: job id whose status to query
1196

1197
    @rtype: dict
1198
    @return: job status
1199

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

    
1205
  def WaitForJobCompletion(self, job_id, period=5, retries=-1):
1206
    """Polls cluster for job status until completion.
1207

1208
    Completion is defined as any of the following states listed in
1209
    L{JOB_STATUS_FINALIZED}.
1210

1211
    @type job_id: string
1212
    @param job_id: job id to watch
1213
    @type period: int
1214
    @param period: how often to poll for status (optional, default 5s)
1215
    @type retries: int
1216
    @param retries: how many time to poll before giving up
1217
                    (optional, default -1 means unlimited)
1218

1219
    @rtype: bool
1220
    @return: C{True} if job succeeded or C{False} if failed/status timeout
1221
    @deprecated: It is recommended to use L{WaitForJobChange} wherever
1222
      possible; L{WaitForJobChange} returns immediately after a job changed and
1223
      does not use polling
1224

1225
    """
1226
    while retries != 0:
1227
      job_result = self.GetJobStatus(job_id)
1228

    
1229
      if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
1230
        return True
1231
      elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
1232
        return False
1233

    
1234
      if period:
1235
        time.sleep(period)
1236

    
1237
      if retries > 0:
1238
        retries -= 1
1239

    
1240
    return False
1241

    
1242
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1243
    """Waits for job changes.
1244

1245
    @type job_id: string
1246
    @param job_id: Job ID for which to wait
1247
    @return: C{None} if no changes have been detected and a dict with two keys,
1248
      C{job_info} and C{log_entries} otherwise.
1249
    @rtype: dict
1250

1251
    """
1252
    body = {
1253
      "fields": fields,
1254
      "previous_job_info": prev_job_info,
1255
      "previous_log_serial": prev_log_serial,
1256
      }
1257

    
1258
    return self._SendRequest(HTTP_GET,
1259
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1260
                             None, body)
1261

    
1262
  def CancelJob(self, job_id, dry_run=False):
1263
    """Cancels a job.
1264

1265
    @type job_id: string
1266
    @param job_id: id of the job to delete
1267
    @type dry_run: bool
1268
    @param dry_run: whether to perform a dry run
1269
    @rtype: tuple
1270
    @return: tuple containing the result, and a message (bool, string)
1271

1272
    """
1273
    query = []
1274
    if dry_run:
1275
      query.append(("dry-run", 1))
1276

    
1277
    return self._SendRequest(HTTP_DELETE,
1278
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1279
                             query, None)
1280

    
1281
  def GetNodes(self, bulk=False):
1282
    """Gets all nodes in the cluster.
1283

1284
    @type bulk: bool
1285
    @param bulk: whether to return all information about all instances
1286

1287
    @rtype: list of dict or str
1288
    @return: if bulk is true, info about nodes in the cluster,
1289
        else list of nodes in the cluster
1290

1291
    """
1292
    query = []
1293
    if bulk:
1294
      query.append(("bulk", 1))
1295

    
1296
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1297
                              query, None)
1298
    if bulk:
1299
      return nodes
1300
    else:
1301
      return [n["id"] for n in nodes]
1302

    
1303
  def GetNode(self, node):
1304
    """Gets information about a node.
1305

1306
    @type node: str
1307
    @param node: node whose info to return
1308

1309
    @rtype: dict
1310
    @return: info about the node
1311

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

    
1317
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1318
                   dry_run=False, early_release=False):
1319
    """Evacuates instances from a Ganeti node.
1320

1321
    @type node: str
1322
    @param node: node to evacuate
1323
    @type iallocator: str or None
1324
    @param iallocator: instance allocator to use
1325
    @type remote_node: str
1326
    @param remote_node: node to evaucate to
1327
    @type dry_run: bool
1328
    @param dry_run: whether to perform a dry run
1329
    @type early_release: bool
1330
    @param early_release: whether to enable parallelization
1331

1332
    @rtype: list
1333
    @return: list of (job ID, instance name, new secondary node); if
1334
        dry_run was specified, then the actual move jobs were not
1335
        submitted and the job IDs will be C{None}
1336

1337
    @raises GanetiApiError: if an iallocator and remote_node are both
1338
        specified
1339

1340
    """
1341
    if iallocator and remote_node:
1342
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1343

    
1344
    query = []
1345
    if iallocator:
1346
      query.append(("iallocator", iallocator))
1347
    if remote_node:
1348
      query.append(("remote_node", remote_node))
1349
    if dry_run:
1350
      query.append(("dry-run", 1))
1351
    if early_release:
1352
      query.append(("early_release", 1))
1353

    
1354
    return self._SendRequest(HTTP_POST,
1355
                             ("/%s/nodes/%s/evacuate" %
1356
                              (GANETI_RAPI_VERSION, node)), query, None)
1357

    
1358
  def MigrateNode(self, node, mode=None, dry_run=False):
1359
    """Migrates all primary instances from a node.
1360

1361
    @type node: str
1362
    @param node: node to migrate
1363
    @type mode: string
1364
    @param mode: if passed, it will overwrite the live migration type,
1365
        otherwise the hypervisor default will be used
1366
    @type dry_run: bool
1367
    @param dry_run: whether to perform a dry run
1368

1369
    @rtype: string
1370
    @return: job id
1371

1372
    """
1373
    query = []
1374
    if mode is not None:
1375
      query.append(("mode", mode))
1376
    if dry_run:
1377
      query.append(("dry-run", 1))
1378

    
1379
    return self._SendRequest(HTTP_POST,
1380
                             ("/%s/nodes/%s/migrate" %
1381
                              (GANETI_RAPI_VERSION, node)), query, None)
1382

    
1383
  def GetNodeRole(self, node):
1384
    """Gets the current role for a node.
1385

1386
    @type node: str
1387
    @param node: node whose role to return
1388

1389
    @rtype: str
1390
    @return: the current role for a node
1391

1392
    """
1393
    return self._SendRequest(HTTP_GET,
1394
                             ("/%s/nodes/%s/role" %
1395
                              (GANETI_RAPI_VERSION, node)), None, None)
1396

    
1397
  def SetNodeRole(self, node, role, force=False):
1398
    """Sets the role for a node.
1399

1400
    @type node: str
1401
    @param node: the node whose role to set
1402
    @type role: str
1403
    @param role: the role to set for the node
1404
    @type force: bool
1405
    @param force: whether to force the role change
1406

1407
    @rtype: string
1408
    @return: job id
1409

1410
    """
1411
    query = [
1412
      ("force", force),
1413
      ]
1414

    
1415
    return self._SendRequest(HTTP_PUT,
1416
                             ("/%s/nodes/%s/role" %
1417
                              (GANETI_RAPI_VERSION, node)), query, role)
1418

    
1419
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1420
    """Gets the storage units for a node.
1421

1422
    @type node: str
1423
    @param node: the node whose storage units to return
1424
    @type storage_type: str
1425
    @param storage_type: storage type whose units to return
1426
    @type output_fields: str
1427
    @param output_fields: storage type fields to return
1428

1429
    @rtype: string
1430
    @return: job id where results can be retrieved
1431

1432
    """
1433
    query = [
1434
      ("storage_type", storage_type),
1435
      ("output_fields", output_fields),
1436
      ]
1437

    
1438
    return self._SendRequest(HTTP_GET,
1439
                             ("/%s/nodes/%s/storage" %
1440
                              (GANETI_RAPI_VERSION, node)), query, None)
1441

    
1442
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1443
    """Modifies parameters of storage units on the node.
1444

1445
    @type node: str
1446
    @param node: node whose storage units to modify
1447
    @type storage_type: str
1448
    @param storage_type: storage type whose units to modify
1449
    @type name: str
1450
    @param name: name of the storage unit
1451
    @type allocatable: bool or None
1452
    @param allocatable: Whether to set the "allocatable" flag on the storage
1453
                        unit (None=no modification, True=set, False=unset)
1454

1455
    @rtype: string
1456
    @return: job id
1457

1458
    """
1459
    query = [
1460
      ("storage_type", storage_type),
1461
      ("name", name),
1462
      ]
1463

    
1464
    if allocatable is not None:
1465
      query.append(("allocatable", allocatable))
1466

    
1467
    return self._SendRequest(HTTP_PUT,
1468
                             ("/%s/nodes/%s/storage/modify" %
1469
                              (GANETI_RAPI_VERSION, node)), query, None)
1470

    
1471
  def RepairNodeStorageUnits(self, node, storage_type, name):
1472
    """Repairs a storage unit on the node.
1473

1474
    @type node: str
1475
    @param node: node whose storage units to repair
1476
    @type storage_type: str
1477
    @param storage_type: storage type to repair
1478
    @type name: str
1479
    @param name: name of the storage unit to repair
1480

1481
    @rtype: string
1482
    @return: job id
1483

1484
    """
1485
    query = [
1486
      ("storage_type", storage_type),
1487
      ("name", name),
1488
      ]
1489

    
1490
    return self._SendRequest(HTTP_PUT,
1491
                             ("/%s/nodes/%s/storage/repair" %
1492
                              (GANETI_RAPI_VERSION, node)), query, None)
1493

    
1494
  def GetNodeTags(self, node):
1495
    """Gets the tags for a node.
1496

1497
    @type node: str
1498
    @param node: node whose tags to return
1499

1500
    @rtype: list of str
1501
    @return: tags for the node
1502

1503
    """
1504
    return self._SendRequest(HTTP_GET,
1505
                             ("/%s/nodes/%s/tags" %
1506
                              (GANETI_RAPI_VERSION, node)), None, None)
1507

    
1508
  def AddNodeTags(self, node, tags, dry_run=False):
1509
    """Adds tags to a node.
1510

1511
    @type node: str
1512
    @param node: node to add tags to
1513
    @type tags: list of str
1514
    @param tags: tags to add to the node
1515
    @type dry_run: bool
1516
    @param dry_run: whether to perform a dry run
1517

1518
    @rtype: string
1519
    @return: job id
1520

1521
    """
1522
    query = [("tag", t) for t in tags]
1523
    if dry_run:
1524
      query.append(("dry-run", 1))
1525

    
1526
    return self._SendRequest(HTTP_PUT,
1527
                             ("/%s/nodes/%s/tags" %
1528
                              (GANETI_RAPI_VERSION, node)), query, tags)
1529

    
1530
  def DeleteNodeTags(self, node, tags, dry_run=False):
1531
    """Delete tags from a node.
1532

1533
    @type node: str
1534
    @param node: node to remove tags from
1535
    @type tags: list of str
1536
    @param tags: tags to remove from the node
1537
    @type dry_run: bool
1538
    @param dry_run: whether to perform a dry run
1539

1540
    @rtype: string
1541
    @return: job id
1542

1543
    """
1544
    query = [("tag", t) for t in tags]
1545
    if dry_run:
1546
      query.append(("dry-run", 1))
1547

    
1548
    return self._SendRequest(HTTP_DELETE,
1549
                             ("/%s/nodes/%s/tags" %
1550
                              (GANETI_RAPI_VERSION, node)), query, None)
1551

    
1552
  def GetGroups(self, bulk=False):
1553
    """Gets all node groups in the cluster.
1554

1555
    @type bulk: bool
1556
    @param bulk: whether to return all information about the groups
1557

1558
    @rtype: list of dict or str
1559
    @return: if bulk is true, a list of dictionaries with info about all node
1560
        groups in the cluster, else a list of names of those node groups
1561

1562
    """
1563
    query = []
1564
    if bulk:
1565
      query.append(("bulk", 1))
1566

    
1567
    groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1568
                               query, None)
1569
    if bulk:
1570
      return groups
1571
    else:
1572
      return [g["name"] for g in groups]
1573

    
1574
  def GetGroup(self, group):
1575
    """Gets information about a node group.
1576

1577
    @type group: str
1578
    @param group: name of the node group whose info to return
1579

1580
    @rtype: dict
1581
    @return: info about the node group
1582

1583
    """
1584
    return self._SendRequest(HTTP_GET,
1585
                             "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
1586
                             None, None)
1587

    
1588
  def CreateGroup(self, name, alloc_policy=None, dry_run=False):
1589
    """Creates a new node group.
1590

1591
    @type name: str
1592
    @param name: the name of node group to create
1593
    @type alloc_policy: str
1594
    @param alloc_policy: the desired allocation policy for the group, if any
1595
    @type dry_run: bool
1596
    @param dry_run: whether to peform a dry run
1597

1598
    @rtype: string
1599
    @return: job id
1600

1601
    """
1602
    query = []
1603
    if dry_run:
1604
      query.append(("dry-run", 1))
1605

    
1606
    body = {
1607
      "name": name,
1608
      "alloc_policy": alloc_policy
1609
      }
1610

    
1611
    return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1612
                             query, body)
1613

    
1614
  def ModifyGroup(self, group, **kwargs):
1615
    """Modifies a node group.
1616

1617
    More details for parameters can be found in the RAPI documentation.
1618

1619
    @type group: string
1620
    @param group: Node group name
1621
    @rtype: string
1622
    @return: job id
1623

1624
    """
1625
    return self._SendRequest(HTTP_PUT,
1626
                             ("/%s/groups/%s/modify" %
1627
                              (GANETI_RAPI_VERSION, group)), None, kwargs)
1628

    
1629
  def DeleteGroup(self, group, dry_run=False):
1630
    """Deletes a node group.
1631

1632
    @type group: str
1633
    @param group: the node group to delete
1634
    @type dry_run: bool
1635
    @param dry_run: whether to peform a dry run
1636

1637
    @rtype: string
1638
    @return: job id
1639

1640
    """
1641
    query = []
1642
    if dry_run:
1643
      query.append(("dry-run", 1))
1644

    
1645
    return self._SendRequest(HTTP_DELETE,
1646
                             ("/%s/groups/%s" %
1647
                              (GANETI_RAPI_VERSION, group)), query, None)
1648

    
1649
  def RenameGroup(self, group, new_name):
1650
    """Changes the name of a node group.
1651

1652
    @type group: string
1653
    @param group: Node group name
1654
    @type new_name: string
1655
    @param new_name: New node group name
1656

1657
    @rtype: string
1658
    @return: job id
1659

1660
    """
1661
    body = {
1662
      "new_name": new_name,
1663
      }
1664

    
1665
    return self._SendRequest(HTTP_PUT,
1666
                             ("/%s/groups/%s/rename" %
1667
                              (GANETI_RAPI_VERSION, group)), None, body)
1668

    
1669
  def AssignGroupNodes(self, group, nodes, force=False, dry_run=False):
1670
    """Assigns nodes to a group.
1671

1672
    @type group: string
1673
    @param group: Node gropu name
1674
    @type nodes: list of strings
1675
    @param nodes: List of nodes to assign to the group
1676

1677
    @rtype: string
1678
    @return: job id
1679

1680
    """
1681
    query = []
1682

    
1683
    if force:
1684
      query.append(("force", 1))
1685

    
1686
    if dry_run:
1687
      query.append(("dry-run", 1))
1688

    
1689
    body = {
1690
      "nodes": nodes,
1691
      }
1692

    
1693
    return self._SendRequest(HTTP_PUT,
1694
                             ("/%s/groups/%s/assign-nodes" %
1695
                             (GANETI_RAPI_VERSION, group)), query, body)
1696

    
1697
  def Query(self, what, fields, filter_=None):
1698
    """Retrieves information about resources.
1699

1700
    @type what: string
1701
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1702
    @type fields: list of string
1703
    @param fields: Requested fields
1704
    @type filter_: None or list
1705
    @param filter_: Query filter
1706

1707
    @rtype: string
1708
    @return: job id
1709

1710
    """
1711
    body = {
1712
      "fields": fields,
1713
      }
1714

    
1715
    if filter_ is not None:
1716
      body["filter"] = filter_
1717

    
1718
    return self._SendRequest(HTTP_PUT,
1719
                             ("/%s/query/%s" %
1720
                              (GANETI_RAPI_VERSION, what)), None, body)
1721

    
1722
  def QueryFields(self, what, fields=None):
1723
    """Retrieves available fields for a resource.
1724

1725
    @type what: string
1726
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1727
    @type fields: list of string
1728
    @param fields: Requested fields
1729

1730
    @rtype: string
1731
    @return: job id
1732

1733
    """
1734
    query = []
1735

    
1736
    if fields is not None:
1737
      query.append(("fields", ",".join(fields)))
1738

    
1739
    return self._SendRequest(HTTP_GET,
1740
                             ("/%s/query/%s/fields" %
1741
                              (GANETI_RAPI_VERSION, what)), query, None)