Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ 47099cd1

History | View | Annotate | Download (51.1 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_WAITING = "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_WAITING,
87
  JOB_STATUS_CANCELING,
88
  JOB_STATUS_RUNNING,
89
  ]) | JOB_STATUS_FINALIZED
90

    
91
# Legacy name
92
JOB_STATUS_WAITLOCK = JOB_STATUS_WAITING
93

    
94
# Internal constants
95
_REQ_DATA_VERSION_FIELD = "__version__"
96
_INST_CREATE_REQV1 = "instance-create-reqv1"
97
_INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
98
_NODE_MIGRATE_REQV1 = "node-migrate-reqv1"
99
_NODE_EVAC_RES1 = "node-evac-res1"
100
_INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link"])
101
_INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
102
_INST_CREATE_V0_PARAMS = frozenset([
103
  "os", "pnode", "snode", "iallocator", "start", "ip_check", "name_check",
104
  "hypervisor", "file_storage_dir", "file_driver", "dry_run",
105
  ])
106
_INST_CREATE_V0_DPARAMS = frozenset(["beparams", "hvparams"])
107

    
108
# Older pycURL versions don't have all error constants
109
try:
110
  _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
111
  _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
112
except AttributeError:
113
  _CURLE_SSL_CACERT = 60
114
  _CURLE_SSL_CACERT_BADFILE = 77
115

    
116
_CURL_SSL_CERT_ERRORS = frozenset([
117
  _CURLE_SSL_CACERT,
118
  _CURLE_SSL_CACERT_BADFILE,
119
  ])
120

    
121

    
122
class Error(Exception):
123
  """Base error class for this module.
124

125
  """
126
  pass
127

    
128

    
129
class CertificateError(Error):
130
  """Raised when a problem is found with the SSL certificate.
131

132
  """
133
  pass
134

    
135

    
136
class GanetiApiError(Error):
137
  """Generic error raised from Ganeti API.
138

139
  """
140
  def __init__(self, msg, code=None):
141
    Error.__init__(self, msg)
142
    self.code = code
143

    
144

    
145
def UsesRapiClient(fn):
146
  """Decorator for code using RAPI client to initialize pycURL.
147

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

    
156
    pycurl.global_init(pycurl.GLOBAL_ALL)
157
    try:
158
      return fn(*args, **kwargs)
159
    finally:
160
      pycurl.global_cleanup()
161

    
162
  return wrapper
163

    
164

    
165
def GenericCurlConfig(verbose=False, use_signal=False,
166
                      use_curl_cabundle=False, cafile=None, capath=None,
167
                      proxy=None, verify_hostname=False,
168
                      connect_timeout=None, timeout=None,
169
                      _pycurl_version_fn=pycurl.version_info):
170
  """Curl configuration function generator.
171

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

194
  """
195
  if use_curl_cabundle and (cafile or capath):
196
    raise Error("Can not use default CA bundle when CA file or path is set")
197

    
198
  def _ConfigCurl(curl, logger):
199
    """Configures a cURL object
200

201
    @type curl: pycurl.Curl
202
    @param curl: cURL object
203

204
    """
205
    logger.debug("Using cURL version %s", pycurl.version)
206

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

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

    
226
    curl.setopt(pycurl.VERBOSE, verbose)
227
    curl.setopt(pycurl.NOSIGNAL, not use_signal)
228

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

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

    
252
    if proxy is not None:
253
      curl.setopt(pycurl.PROXY, str(proxy))
254

    
255
    # Timeouts
256
    if connect_timeout is not None:
257
      curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
258
    if timeout is not None:
259
      curl.setopt(pycurl.TIMEOUT, timeout)
260

    
261
  return _ConfigCurl
262

    
263

    
264
class GanetiRapiClient(object): # pylint: disable-msg=R0904
265
  """Ganeti RAPI client.
266

267
  """
268
  USER_AGENT = "Ganeti RAPI Client"
269
  _json_encoder = simplejson.JSONEncoder(sort_keys=True)
270

    
271
  def __init__(self, host, port=GANETI_RAPI_PORT,
272
               username=None, password=None, logger=logging,
273
               curl_config_fn=None, curl_factory=None):
274
    """Initializes this class.
275

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

288
    """
289
    self._username = username
290
    self._password = password
291
    self._logger = logger
292
    self._curl_config_fn = curl_config_fn
293
    self._curl_factory = curl_factory
294

    
295
    try:
296
      socket.inet_pton(socket.AF_INET6, host)
297
      address = "[%s]:%s" % (host, port)
298
    except socket.error:
299
      address = "%s:%s" % (host, port)
300

    
301
    self._base_url = "https://%s" % address
302

    
303
    if username is not None:
304
      if password is None:
305
        raise Error("Password not specified")
306
    elif password:
307
      raise Error("Specified password without username")
308

    
309
  def _CreateCurl(self):
310
    """Creates a cURL object.
311

312
    """
313
    # Create pycURL object if no factory is provided
314
    if self._curl_factory:
315
      curl = self._curl_factory()
316
    else:
317
      curl = pycurl.Curl()
318

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

    
332
    assert ((self._username is None and self._password is None) ^
333
            (self._username is not None and self._password is not None))
334

    
335
    if self._username:
336
      # Setup authentication
337
      curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
338
      curl.setopt(pycurl.USERPWD,
339
                  str("%s:%s" % (self._username, self._password)))
340

    
341
    # Call external configuration function
342
    if self._curl_config_fn:
343
      self._curl_config_fn(curl, self._logger)
344

    
345
    return curl
346

    
347
  @staticmethod
348
  def _EncodeQuery(query):
349
    """Encode query values for RAPI URL.
350

351
    @type query: list of two-tuples
352
    @param query: Query arguments
353
    @rtype: list
354
    @return: Query list with encoded values
355

356
    """
357
    result = []
358

    
359
    for name, value in query:
360
      if value is None:
361
        result.append((name, ""))
362

    
363
      elif isinstance(value, bool):
364
        # Boolean values must be encoded as 0 or 1
365
        result.append((name, int(value)))
366

    
367
      elif isinstance(value, (list, tuple, dict)):
368
        raise ValueError("Invalid query data type %r" % type(value).__name__)
369

    
370
      else:
371
        result.append((name, value))
372

    
373
    return result
374

    
375
  def _SendRequest(self, method, path, query, content):
376
    """Sends an HTTP request.
377

378
    This constructs a full URL, encodes and decodes HTTP bodies, and
379
    handles invalid responses in a pythonic way.
380

381
    @type method: string
382
    @param method: HTTP method to use
383
    @type path: string
384
    @param path: HTTP URL path
385
    @type query: list of two-tuples
386
    @param query: query arguments to pass to urllib.urlencode
387
    @type content: str or None
388
    @param content: HTTP body content
389

390
    @rtype: str
391
    @return: JSON-Decoded response
392

393
    @raises CertificateError: If an invalid SSL certificate is found
394
    @raises GanetiApiError: If an invalid response is returned
395

396
    """
397
    assert path.startswith("/")
398

    
399
    curl = self._CreateCurl()
400

    
401
    if content is not None:
402
      encoded_content = self._json_encoder.encode(content)
403
    else:
404
      encoded_content = ""
405

    
406
    # Build URL
407
    urlparts = [self._base_url, path]
408
    if query:
409
      urlparts.append("?")
410
      urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
411

    
412
    url = "".join(urlparts)
413

    
414
    self._logger.debug("Sending request %s %s (content=%r)",
415
                       method, url, encoded_content)
416

    
417
    # Buffer for response
418
    encoded_resp_body = StringIO()
419

    
420
    # Configure cURL
421
    curl.setopt(pycurl.CUSTOMREQUEST, str(method))
422
    curl.setopt(pycurl.URL, str(url))
423
    curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
424
    curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
425

    
426
    try:
427
      # Send request and wait for response
428
      try:
429
        curl.perform()
430
      except pycurl.error, err:
431
        if err.args[0] in _CURL_SSL_CERT_ERRORS:
432
          raise CertificateError("SSL certificate error %s" % err)
433

    
434
        raise GanetiApiError(str(err))
435
    finally:
436
      # Reset settings to not keep references to large objects in memory
437
      # between requests
438
      curl.setopt(pycurl.POSTFIELDS, "")
439
      curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)
440

    
441
    # Get HTTP response code
442
    http_code = curl.getinfo(pycurl.RESPONSE_CODE)
443

    
444
    # Was anything written to the response buffer?
445
    if encoded_resp_body.tell():
446
      response_content = simplejson.loads(encoded_resp_body.getvalue())
447
    else:
448
      response_content = None
449

    
450
    if http_code != HTTP_OK:
451
      if isinstance(response_content, dict):
452
        msg = ("%s %s: %s" %
453
               (response_content["code"],
454
                response_content["message"],
455
                response_content["explain"]))
456
      else:
457
        msg = str(response_content)
458

    
459
      raise GanetiApiError(msg, code=http_code)
460

    
461
    return response_content
462

    
463
  def GetVersion(self):
464
    """Gets the Remote API version running on the cluster.
465

466
    @rtype: int
467
    @return: Ganeti Remote API version
468

469
    """
470
    return self._SendRequest(HTTP_GET, "/version", None, None)
471

    
472
  def GetFeatures(self):
473
    """Gets the list of optional features supported by RAPI server.
474

475
    @rtype: list
476
    @return: List of optional features
477

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

    
487
      raise
488

    
489
  def GetOperatingSystems(self):
490
    """Gets the Operating Systems running in the Ganeti cluster.
491

492
    @rtype: list of str
493
    @return: operating systems
494

495
    """
496
    return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
497
                             None, None)
498

    
499
  def GetInfo(self):
500
    """Gets info about the cluster.
501

502
    @rtype: dict
503
    @return: information about the cluster
504

505
    """
506
    return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
507
                             None, None)
508

    
509
  def RedistributeConfig(self):
510
    """Tells the cluster to redistribute its configuration files.
511

512
    @rtype: string
513
    @return: job id
514

515
    """
516
    return self._SendRequest(HTTP_PUT,
517
                             "/%s/redistribute-config" % GANETI_RAPI_VERSION,
518
                             None, None)
519

    
520
  def ModifyCluster(self, **kwargs):
521
    """Modifies cluster parameters.
522

523
    More details for parameters can be found in the RAPI documentation.
524

525
    @rtype: string
526
    @return: job id
527

528
    """
529
    body = kwargs
530

    
531
    return self._SendRequest(HTTP_PUT,
532
                             "/%s/modify" % GANETI_RAPI_VERSION, None, body)
533

    
534
  def GetClusterTags(self):
535
    """Gets the cluster tags.
536

537
    @rtype: list of str
538
    @return: cluster tags
539

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

    
544
  def AddClusterTags(self, tags, dry_run=False):
545
    """Adds tags to the cluster.
546

547
    @type tags: list of str
548
    @param tags: tags to add to the cluster
549
    @type dry_run: bool
550
    @param dry_run: whether to perform a dry run
551

552
    @rtype: string
553
    @return: job id
554

555
    """
556
    query = [("tag", t) for t in tags]
557
    if dry_run:
558
      query.append(("dry-run", 1))
559

    
560
    return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
561
                             query, None)
562

    
563
  def DeleteClusterTags(self, tags, dry_run=False):
564
    """Deletes tags from the cluster.
565

566
    @type tags: list of str
567
    @param tags: tags to delete
568
    @type dry_run: bool
569
    @param dry_run: whether to perform a dry run
570
    @rtype: string
571
    @return: job id
572

573
    """
574
    query = [("tag", t) for t in tags]
575
    if dry_run:
576
      query.append(("dry-run", 1))
577

    
578
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
579
                             query, None)
580

    
581
  def GetInstances(self, bulk=False):
582
    """Gets information about instances on the cluster.
583

584
    @type bulk: bool
585
    @param bulk: whether to return all information about all instances
586

587
    @rtype: list of dict or list of str
588
    @return: if bulk is True, info about the instances, else a list of instances
589

590
    """
591
    query = []
592
    if bulk:
593
      query.append(("bulk", 1))
594

    
595
    instances = self._SendRequest(HTTP_GET,
596
                                  "/%s/instances" % GANETI_RAPI_VERSION,
597
                                  query, None)
598
    if bulk:
599
      return instances
600
    else:
601
      return [i["id"] for i in instances]
602

    
603
  def GetInstance(self, instance):
604
    """Gets information about an instance.
605

606
    @type instance: str
607
    @param instance: instance whose info to return
608

609
    @rtype: dict
610
    @return: info about the instance
611

612
    """
613
    return self._SendRequest(HTTP_GET,
614
                             ("/%s/instances/%s" %
615
                              (GANETI_RAPI_VERSION, instance)), None, None)
616

    
617
  def GetInstanceInfo(self, instance, static=None):
618
    """Gets information about an instance.
619

620
    @type instance: string
621
    @param instance: Instance name
622
    @rtype: string
623
    @return: Job ID
624

625
    """
626
    if static is not None:
627
      query = [("static", static)]
628
    else:
629
      query = None
630

    
631
    return self._SendRequest(HTTP_GET,
632
                             ("/%s/instances/%s/info" %
633
                              (GANETI_RAPI_VERSION, instance)), query, None)
634

    
635
  def CreateInstance(self, mode, name, disk_template, disks, nics,
636
                     **kwargs):
637
    """Creates a new instance.
638

639
    More details for parameters can be found in the RAPI documentation.
640

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

655
    @rtype: string
656
    @return: job id
657

658
    """
659
    query = []
660

    
661
    if kwargs.get("dry_run"):
662
      query.append(("dry-run", 1))
663

    
664
    if _INST_CREATE_REQV1 in self.GetFeatures():
665
      # All required fields for request data version 1
666
      body = {
667
        _REQ_DATA_VERSION_FIELD: 1,
668
        "mode": mode,
669
        "name": name,
670
        "disk_template": disk_template,
671
        "disks": disks,
672
        "nics": nics,
673
        }
674

    
675
      conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
676
      if conflicts:
677
        raise GanetiApiError("Required fields can not be specified as"
678
                             " keywords: %s" % ", ".join(conflicts))
679

    
680
      body.update((key, value) for key, value in kwargs.iteritems()
681
                  if key != "dry_run")
682
    else:
683
      raise GanetiApiError("Server does not support new-style (version 1)"
684
                           " instance creation requests")
685

    
686
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
687
                             query, body)
688

    
689
  def DeleteInstance(self, instance, dry_run=False):
690
    """Deletes an instance.
691

692
    @type instance: str
693
    @param instance: the instance to delete
694

695
    @rtype: string
696
    @return: job id
697

698
    """
699
    query = []
700
    if dry_run:
701
      query.append(("dry-run", 1))
702

    
703
    return self._SendRequest(HTTP_DELETE,
704
                             ("/%s/instances/%s" %
705
                              (GANETI_RAPI_VERSION, instance)), query, None)
706

    
707
  def ModifyInstance(self, instance, **kwargs):
708
    """Modifies an instance.
709

710
    More details for parameters can be found in the RAPI documentation.
711

712
    @type instance: string
713
    @param instance: Instance name
714
    @rtype: string
715
    @return: job id
716

717
    """
718
    body = kwargs
719

    
720
    return self._SendRequest(HTTP_PUT,
721
                             ("/%s/instances/%s/modify" %
722
                              (GANETI_RAPI_VERSION, instance)), None, body)
723

    
724
  def ActivateInstanceDisks(self, instance, ignore_size=None):
725
    """Activates an instance's disks.
726

727
    @type instance: string
728
    @param instance: Instance name
729
    @type ignore_size: bool
730
    @param ignore_size: Whether to ignore recorded size
731
    @rtype: string
732
    @return: job id
733

734
    """
735
    query = []
736
    if ignore_size:
737
      query.append(("ignore_size", 1))
738

    
739
    return self._SendRequest(HTTP_PUT,
740
                             ("/%s/instances/%s/activate-disks" %
741
                              (GANETI_RAPI_VERSION, instance)), query, None)
742

    
743
  def DeactivateInstanceDisks(self, instance):
744
    """Deactivates an instance's disks.
745

746
    @type instance: string
747
    @param instance: Instance name
748
    @rtype: string
749
    @return: job id
750

751
    """
752
    return self._SendRequest(HTTP_PUT,
753
                             ("/%s/instances/%s/deactivate-disks" %
754
                              (GANETI_RAPI_VERSION, instance)), None, None)
755

    
756
  def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
757
    """Grows a disk of an instance.
758

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

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

772
    """
773
    body = {
774
      "amount": amount,
775
      }
776

    
777
    if wait_for_sync is not None:
778
      body["wait_for_sync"] = wait_for_sync
779

    
780
    return self._SendRequest(HTTP_POST,
781
                             ("/%s/instances/%s/disk/%s/grow" %
782
                              (GANETI_RAPI_VERSION, instance, disk)),
783
                             None, body)
784

    
785
  def GetInstanceTags(self, instance):
786
    """Gets tags for an instance.
787

788
    @type instance: str
789
    @param instance: instance whose tags to return
790

791
    @rtype: list of str
792
    @return: tags for the instance
793

794
    """
795
    return self._SendRequest(HTTP_GET,
796
                             ("/%s/instances/%s/tags" %
797
                              (GANETI_RAPI_VERSION, instance)), None, None)
798

    
799
  def AddInstanceTags(self, instance, tags, dry_run=False):
800
    """Adds tags to an instance.
801

802
    @type instance: str
803
    @param instance: instance to add tags to
804
    @type tags: list of str
805
    @param tags: tags to add to the instance
806
    @type dry_run: bool
807
    @param dry_run: whether to perform a dry run
808

809
    @rtype: string
810
    @return: job id
811

812
    """
813
    query = [("tag", t) for t in tags]
814
    if dry_run:
815
      query.append(("dry-run", 1))
816

    
817
    return self._SendRequest(HTTP_PUT,
818
                             ("/%s/instances/%s/tags" %
819
                              (GANETI_RAPI_VERSION, instance)), query, None)
820

    
821
  def DeleteInstanceTags(self, instance, tags, dry_run=False):
822
    """Deletes tags from an instance.
823

824
    @type instance: str
825
    @param instance: instance to delete tags from
826
    @type tags: list of str
827
    @param tags: tags to delete
828
    @type dry_run: bool
829
    @param dry_run: whether to perform a dry run
830
    @rtype: string
831
    @return: job id
832

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

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

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

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

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

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

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

874
    @type instance: str
875
    @param instance: the instance to shut down
876
    @type dry_run: bool
877
    @param dry_run: whether to perform a dry run
878
    @type no_remember: bool
879
    @param no_remember: if true, will not record the state change
880
    @rtype: string
881
    @return: job id
882

883
    """
884
    query = []
885
    if dry_run:
886
      query.append(("dry-run", 1))
887
    if no_remember:
888
      query.append(("no-remember", 1))
889

    
890
    return self._SendRequest(HTTP_PUT,
891
                             ("/%s/instances/%s/shutdown" %
892
                              (GANETI_RAPI_VERSION, instance)), query, None)
893

    
894
  def StartupInstance(self, instance, dry_run=False, no_remember=False):
895
    """Starts up an instance.
896

897
    @type instance: str
898
    @param instance: the instance to start up
899
    @type dry_run: bool
900
    @param dry_run: whether to perform a dry run
901
    @type no_remember: bool
902
    @param no_remember: if true, will not record the state change
903
    @rtype: string
904
    @return: job id
905

906
    """
907
    query = []
908
    if dry_run:
909
      query.append(("dry-run", 1))
910
    if no_remember:
911
      query.append(("no-remember", 1))
912

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

    
917
  def ReinstallInstance(self, instance, os=None, no_startup=False,
918
                        osparams=None):
919
    """Reinstalls an instance.
920

921
    @type instance: str
922
    @param instance: The instance to reinstall
923
    @type os: str or None
924
    @param os: The operating system to reinstall. If None, the instance's
925
        current operating system will be installed again
926
    @type no_startup: bool
927
    @param no_startup: Whether to start the instance automatically
928
    @rtype: string
929
    @return: job id
930

931
    """
932
    if _INST_REINSTALL_REQV1 in self.GetFeatures():
933
      body = {
934
        "start": not no_startup,
935
        }
936
      if os is not None:
937
        body["os"] = os
938
      if osparams is not None:
939
        body["osparams"] = osparams
940
      return self._SendRequest(HTTP_POST,
941
                               ("/%s/instances/%s/reinstall" %
942
                                (GANETI_RAPI_VERSION, instance)), None, body)
943

    
944
    # Use old request format
945
    if osparams:
946
      raise GanetiApiError("Server does not support specifying OS parameters"
947
                           " for instance reinstallation")
948

    
949
    query = []
950
    if os:
951
      query.append(("os", os))
952
    if no_startup:
953
      query.append(("nostartup", 1))
954
    return self._SendRequest(HTTP_POST,
955
                             ("/%s/instances/%s/reinstall" %
956
                              (GANETI_RAPI_VERSION, instance)), query, None)
957

    
958
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
959
                           remote_node=None, iallocator=None, dry_run=False):
960
    """Replaces disks on an instance.
961

962
    @type instance: str
963
    @param instance: instance whose disks to replace
964
    @type disks: list of ints
965
    @param disks: Indexes of disks to replace
966
    @type mode: str
967
    @param mode: replacement mode to use (defaults to replace_auto)
968
    @type remote_node: str or None
969
    @param remote_node: new secondary node to use (for use with
970
        replace_new_secondary mode)
971
    @type iallocator: str or None
972
    @param iallocator: instance allocator plugin to use (for use with
973
                       replace_auto mode)
974
    @type dry_run: bool
975
    @param dry_run: whether to perform a dry run
976

977
    @rtype: string
978
    @return: job id
979

980
    """
981
    query = [
982
      ("mode", mode),
983
      ]
984

    
985
    if disks:
986
      query.append(("disks", ",".join(str(idx) for idx in disks)))
987

    
988
    if remote_node:
989
      query.append(("remote_node", remote_node))
990

    
991
    if iallocator:
992
      query.append(("iallocator", iallocator))
993

    
994
    if dry_run:
995
      query.append(("dry-run", 1))
996

    
997
    return self._SendRequest(HTTP_POST,
998
                             ("/%s/instances/%s/replace-disks" %
999
                              (GANETI_RAPI_VERSION, instance)), query, None)
1000

    
1001
  def PrepareExport(self, instance, mode):
1002
    """Prepares an instance for an export.
1003

1004
    @type instance: string
1005
    @param instance: Instance name
1006
    @type mode: string
1007
    @param mode: Export mode
1008
    @rtype: string
1009
    @return: Job ID
1010

1011
    """
1012
    query = [("mode", mode)]
1013
    return self._SendRequest(HTTP_PUT,
1014
                             ("/%s/instances/%s/prepare-export" %
1015
                              (GANETI_RAPI_VERSION, instance)), query, None)
1016

    
1017
  def ExportInstance(self, instance, mode, destination, shutdown=None,
1018
                     remove_instance=None,
1019
                     x509_key_name=None, destination_x509_ca=None):
1020
    """Exports an instance.
1021

1022
    @type instance: string
1023
    @param instance: Instance name
1024
    @type mode: string
1025
    @param mode: Export mode
1026
    @rtype: string
1027
    @return: Job ID
1028

1029
    """
1030
    body = {
1031
      "destination": destination,
1032
      "mode": mode,
1033
      }
1034

    
1035
    if shutdown is not None:
1036
      body["shutdown"] = shutdown
1037

    
1038
    if remove_instance is not None:
1039
      body["remove_instance"] = remove_instance
1040

    
1041
    if x509_key_name is not None:
1042
      body["x509_key_name"] = x509_key_name
1043

    
1044
    if destination_x509_ca is not None:
1045
      body["destination_x509_ca"] = destination_x509_ca
1046

    
1047
    return self._SendRequest(HTTP_PUT,
1048
                             ("/%s/instances/%s/export" %
1049
                              (GANETI_RAPI_VERSION, instance)), None, body)
1050

    
1051
  def MigrateInstance(self, instance, mode=None, cleanup=None):
1052
    """Migrates an instance.
1053

1054
    @type instance: string
1055
    @param instance: Instance name
1056
    @type mode: string
1057
    @param mode: Migration mode
1058
    @type cleanup: bool
1059
    @param cleanup: Whether to clean up a previously failed migration
1060
    @rtype: string
1061
    @return: job id
1062

1063
    """
1064
    body = {}
1065

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

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

    
1072
    return self._SendRequest(HTTP_PUT,
1073
                             ("/%s/instances/%s/migrate" %
1074
                              (GANETI_RAPI_VERSION, instance)), None, body)
1075

    
1076
  def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
1077
    """Changes the name of an instance.
1078

1079
    @type instance: string
1080
    @param instance: Instance name
1081
    @type new_name: string
1082
    @param new_name: New instance name
1083
    @type ip_check: bool
1084
    @param ip_check: Whether to ensure instance's IP address is inactive
1085
    @type name_check: bool
1086
    @param name_check: Whether to ensure instance's name is resolvable
1087
    @rtype: string
1088
    @return: job id
1089

1090
    """
1091
    body = {
1092
      "new_name": new_name,
1093
      }
1094

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

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

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

    
1105
  def GetInstanceConsole(self, instance):
1106
    """Request information for connecting to instance's console.
1107

1108
    @type instance: string
1109
    @param instance: Instance name
1110
    @rtype: dict
1111
    @return: dictionary containing information about instance's console
1112

1113
    """
1114
    return self._SendRequest(HTTP_GET,
1115
                             ("/%s/instances/%s/console" %
1116
                              (GANETI_RAPI_VERSION, instance)), None, None)
1117

    
1118
  def GetJobs(self):
1119
    """Gets all jobs for the cluster.
1120

1121
    @rtype: list of int
1122
    @return: job ids for the cluster
1123

1124
    """
1125
    return [int(j["id"])
1126
            for j in self._SendRequest(HTTP_GET,
1127
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1128
                                       None, None)]
1129

    
1130
  def GetJobStatus(self, job_id):
1131
    """Gets the status of a job.
1132

1133
    @type job_id: string
1134
    @param job_id: job id whose status to query
1135

1136
    @rtype: dict
1137
    @return: job status
1138

1139
    """
1140
    return self._SendRequest(HTTP_GET,
1141
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1142
                             None, None)
1143

    
1144
  def WaitForJobCompletion(self, job_id, period=5, retries=-1):
1145
    """Polls cluster for job status until completion.
1146

1147
    Completion is defined as any of the following states listed in
1148
    L{JOB_STATUS_FINALIZED}.
1149

1150
    @type job_id: string
1151
    @param job_id: job id to watch
1152
    @type period: int
1153
    @param period: how often to poll for status (optional, default 5s)
1154
    @type retries: int
1155
    @param retries: how many time to poll before giving up
1156
                    (optional, default -1 means unlimited)
1157

1158
    @rtype: bool
1159
    @return: C{True} if job succeeded or C{False} if failed/status timeout
1160
    @deprecated: It is recommended to use L{WaitForJobChange} wherever
1161
      possible; L{WaitForJobChange} returns immediately after a job changed and
1162
      does not use polling
1163

1164
    """
1165
    while retries != 0:
1166
      job_result = self.GetJobStatus(job_id)
1167

    
1168
      if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
1169
        return True
1170
      elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
1171
        return False
1172

    
1173
      if period:
1174
        time.sleep(period)
1175

    
1176
      if retries > 0:
1177
        retries -= 1
1178

    
1179
    return False
1180

    
1181
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1182
    """Waits for job changes.
1183

1184
    @type job_id: string
1185
    @param job_id: Job ID for which to wait
1186
    @return: C{None} if no changes have been detected and a dict with two keys,
1187
      C{job_info} and C{log_entries} otherwise.
1188
    @rtype: dict
1189

1190
    """
1191
    body = {
1192
      "fields": fields,
1193
      "previous_job_info": prev_job_info,
1194
      "previous_log_serial": prev_log_serial,
1195
      }
1196

    
1197
    return self._SendRequest(HTTP_GET,
1198
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1199
                             None, body)
1200

    
1201
  def CancelJob(self, job_id, dry_run=False):
1202
    """Cancels a job.
1203

1204
    @type job_id: string
1205
    @param job_id: id of the job to delete
1206
    @type dry_run: bool
1207
    @param dry_run: whether to perform a dry run
1208
    @rtype: tuple
1209
    @return: tuple containing the result, and a message (bool, string)
1210

1211
    """
1212
    query = []
1213
    if dry_run:
1214
      query.append(("dry-run", 1))
1215

    
1216
    return self._SendRequest(HTTP_DELETE,
1217
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1218
                             query, None)
1219

    
1220
  def GetNodes(self, bulk=False):
1221
    """Gets all nodes in the cluster.
1222

1223
    @type bulk: bool
1224
    @param bulk: whether to return all information about all instances
1225

1226
    @rtype: list of dict or str
1227
    @return: if bulk is true, info about nodes in the cluster,
1228
        else list of nodes in the cluster
1229

1230
    """
1231
    query = []
1232
    if bulk:
1233
      query.append(("bulk", 1))
1234

    
1235
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1236
                              query, None)
1237
    if bulk:
1238
      return nodes
1239
    else:
1240
      return [n["id"] for n in nodes]
1241

    
1242
  def GetNode(self, node):
1243
    """Gets information about a node.
1244

1245
    @type node: str
1246
    @param node: node whose info to return
1247

1248
    @rtype: dict
1249
    @return: info about the node
1250

1251
    """
1252
    return self._SendRequest(HTTP_GET,
1253
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1254
                             None, None)
1255

    
1256
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1257
                   dry_run=False, early_release=None,
1258
                   primary=None, secondary=None, accept_old=False):
1259
    """Evacuates instances from a Ganeti node.
1260

1261
    @type node: str
1262
    @param node: node to evacuate
1263
    @type iallocator: str or None
1264
    @param iallocator: instance allocator to use
1265
    @type remote_node: str
1266
    @param remote_node: node to evaucate to
1267
    @type dry_run: bool
1268
    @param dry_run: whether to perform a dry run
1269
    @type early_release: bool
1270
    @param early_release: whether to enable parallelization
1271
    @type primary: bool
1272
    @param primary: Whether to evacuate primary instances
1273
    @type secondary: bool
1274
    @param secondary: Whether to evacuate secondary instances
1275
    @type accept_old: bool
1276
    @param accept_old: Whether caller is ready to accept old-style (pre-2.5)
1277
        results
1278

1279
    @rtype: string, or a list for pre-2.5 results
1280
    @return: Job ID or, if C{accept_old} is set and server is pre-2.5,
1281
      list of (job ID, instance name, new secondary node); if dry_run was
1282
      specified, then the actual move jobs were not submitted and the job IDs
1283
      will be C{None}
1284

1285
    @raises GanetiApiError: if an iallocator and remote_node are both
1286
        specified
1287

1288
    """
1289
    if iallocator and remote_node:
1290
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1291

    
1292
    query = []
1293
    if dry_run:
1294
      query.append(("dry-run", 1))
1295

    
1296
    if _NODE_EVAC_RES1 in self.GetFeatures():
1297
      body = {}
1298

    
1299
      if iallocator is not None:
1300
        body["iallocator"] = iallocator
1301
      if remote_node is not None:
1302
        body["remote_node"] = remote_node
1303
      if early_release is not None:
1304
        body["early_release"] = early_release
1305
      if primary is not None:
1306
        body["primary"] = primary
1307
      if secondary is not None:
1308
        body["secondary"] = secondary
1309
    else:
1310
      # Pre-2.5 request format
1311
      body = None
1312

    
1313
      if not accept_old:
1314
        raise GanetiApiError("Server is version 2.4 or earlier and caller does"
1315
                             " not accept old-style results (parameter"
1316
                             " accept_old)")
1317

    
1318
      if primary or primary is None or not (secondary is None or secondary):
1319
        raise GanetiApiError("Server can only evacuate secondary instances")
1320

    
1321
      if iallocator:
1322
        query.append(("iallocator", iallocator))
1323
      if remote_node:
1324
        query.append(("remote_node", remote_node))
1325
      if early_release:
1326
        query.append(("early_release", 1))
1327

    
1328
    return self._SendRequest(HTTP_POST,
1329
                             ("/%s/nodes/%s/evacuate" %
1330
                              (GANETI_RAPI_VERSION, node)), query, body)
1331

    
1332
  def MigrateNode(self, node, mode=None, dry_run=False, iallocator=None,
1333
                  target_node=None):
1334
    """Migrates all primary instances from a node.
1335

1336
    @type node: str
1337
    @param node: node to migrate
1338
    @type mode: string
1339
    @param mode: if passed, it will overwrite the live migration type,
1340
        otherwise the hypervisor default will be used
1341
    @type dry_run: bool
1342
    @param dry_run: whether to perform a dry run
1343
    @type iallocator: string
1344
    @param iallocator: instance allocator to use
1345
    @type target_node: string
1346
    @param target_node: Target node for shared-storage instances
1347

1348
    @rtype: string
1349
    @return: job id
1350

1351
    """
1352
    query = []
1353
    if dry_run:
1354
      query.append(("dry-run", 1))
1355

    
1356
    if _NODE_MIGRATE_REQV1 in self.GetFeatures():
1357
      body = {}
1358

    
1359
      if mode is not None:
1360
        body["mode"] = mode
1361
      if iallocator is not None:
1362
        body["iallocator"] = iallocator
1363
      if target_node is not None:
1364
        body["target_node"] = target_node
1365

    
1366
      assert len(query) <= 1
1367

    
1368
      return self._SendRequest(HTTP_POST,
1369
                               ("/%s/nodes/%s/migrate" %
1370
                                (GANETI_RAPI_VERSION, node)), query, body)
1371
    else:
1372
      # Use old request format
1373
      if target_node is not None:
1374
        raise GanetiApiError("Server does not support specifying target node"
1375
                             " for node migration")
1376

    
1377
      if mode is not None:
1378
        query.append(("mode", mode))
1379

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1681
    """
1682
    query = []
1683

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

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

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

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

    
1698
  def GetGroupTags(self, group):
1699
    """Gets tags for a node group.
1700

1701
    @type group: string
1702
    @param group: Node group whose tags to return
1703

1704
    @rtype: list of strings
1705
    @return: tags for the group
1706

1707
    """
1708
    return self._SendRequest(HTTP_GET,
1709
                             ("/%s/groups/%s/tags" %
1710
                              (GANETI_RAPI_VERSION, group)), None, None)
1711

    
1712
  def AddGroupTags(self, group, tags, dry_run=False):
1713
    """Adds tags to a node group.
1714

1715
    @type group: str
1716
    @param group: group to add tags to
1717
    @type tags: list of string
1718
    @param tags: tags to add to the group
1719
    @type dry_run: bool
1720
    @param dry_run: whether to perform a dry run
1721

1722
    @rtype: string
1723
    @return: job id
1724

1725
    """
1726
    query = [("tag", t) for t in tags]
1727
    if dry_run:
1728
      query.append(("dry-run", 1))
1729

    
1730
    return self._SendRequest(HTTP_PUT,
1731
                             ("/%s/groups/%s/tags" %
1732
                              (GANETI_RAPI_VERSION, group)), query, None)
1733

    
1734
  def DeleteGroupTags(self, group, tags, dry_run=False):
1735
    """Deletes tags from a node group.
1736

1737
    @type group: str
1738
    @param group: group to delete tags from
1739
    @type tags: list of string
1740
    @param tags: tags to delete
1741
    @type dry_run: bool
1742
    @param dry_run: whether to perform a dry run
1743
    @rtype: string
1744
    @return: job id
1745

1746
    """
1747
    query = [("tag", t) for t in tags]
1748
    if dry_run:
1749
      query.append(("dry-run", 1))
1750

    
1751
    return self._SendRequest(HTTP_DELETE,
1752
                             ("/%s/groups/%s/tags" %
1753
                              (GANETI_RAPI_VERSION, group)), query, None)
1754

    
1755
  def Query(self, what, fields, filter_=None):
1756
    """Retrieves information about resources.
1757

1758
    @type what: string
1759
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1760
    @type fields: list of string
1761
    @param fields: Requested fields
1762
    @type filter_: None or list
1763
    @param filter_: Query filter
1764

1765
    @rtype: string
1766
    @return: job id
1767

1768
    """
1769
    body = {
1770
      "fields": fields,
1771
      }
1772

    
1773
    if filter_ is not None:
1774
      body["filter"] = filter_
1775

    
1776
    return self._SendRequest(HTTP_PUT,
1777
                             ("/%s/query/%s" %
1778
                              (GANETI_RAPI_VERSION, what)), None, body)
1779

    
1780
  def QueryFields(self, what, fields=None):
1781
    """Retrieves available fields for a resource.
1782

1783
    @type what: string
1784
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1785
    @type fields: list of string
1786
    @param fields: Requested fields
1787

1788
    @rtype: string
1789
    @return: job id
1790

1791
    """
1792
    query = []
1793

    
1794
    if fields is not None:
1795
      query.append(("fields", ",".join(fields)))
1796

    
1797
    return self._SendRequest(HTTP_GET,
1798
                             ("/%s/query/%s/fields" %
1799
                              (GANETI_RAPI_VERSION, what)), query, None)