Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ c0a146a1

History | View | Annotate | Download (52.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 FailoverInstance(self, instance, iallocator=None,
1077
                       ignore_consistency=None, target_node=None):
1078
    """Does a failover of an instance.
1079

1080
    @type instance: string
1081
    @param instance: Instance name
1082
    @type iallocator: string
1083
    @param iallocator: Iallocator for deciding the target node for
1084
      shared-storage instances
1085
    @type ignore_consistency: bool
1086
    @param ignore_consistency: Whether to ignore disk consistency
1087
    @type target_node: string
1088
    @param target_node: Target node for shared-storage instances
1089
    @rtype: string
1090
    @return: job id
1091

1092
    """
1093
    body = {}
1094

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

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

    
1101
    if target_node is not None:
1102
      body["target_node"] = target_node
1103

    
1104
    return self._SendRequest(HTTP_PUT,
1105
                             ("/%s/instances/%s/failover" %
1106
                              (GANETI_RAPI_VERSION, instance)), None, body)
1107

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

1111
    @type instance: string
1112
    @param instance: Instance name
1113
    @type new_name: string
1114
    @param new_name: New instance name
1115
    @type ip_check: bool
1116
    @param ip_check: Whether to ensure instance's IP address is inactive
1117
    @type name_check: bool
1118
    @param name_check: Whether to ensure instance's name is resolvable
1119
    @rtype: string
1120
    @return: job id
1121

1122
    """
1123
    body = {
1124
      "new_name": new_name,
1125
      }
1126

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

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

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

    
1137
  def GetInstanceConsole(self, instance):
1138
    """Request information for connecting to instance's console.
1139

1140
    @type instance: string
1141
    @param instance: Instance name
1142
    @rtype: dict
1143
    @return: dictionary containing information about instance's console
1144

1145
    """
1146
    return self._SendRequest(HTTP_GET,
1147
                             ("/%s/instances/%s/console" %
1148
                              (GANETI_RAPI_VERSION, instance)), None, None)
1149

    
1150
  def GetJobs(self):
1151
    """Gets all jobs for the cluster.
1152

1153
    @rtype: list of int
1154
    @return: job ids for the cluster
1155

1156
    """
1157
    return [int(j["id"])
1158
            for j in self._SendRequest(HTTP_GET,
1159
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1160
                                       None, None)]
1161

    
1162
  def GetJobStatus(self, job_id):
1163
    """Gets the status of a job.
1164

1165
    @type job_id: string
1166
    @param job_id: job id whose status to query
1167

1168
    @rtype: dict
1169
    @return: job status
1170

1171
    """
1172
    return self._SendRequest(HTTP_GET,
1173
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1174
                             None, None)
1175

    
1176
  def WaitForJobCompletion(self, job_id, period=5, retries=-1):
1177
    """Polls cluster for job status until completion.
1178

1179
    Completion is defined as any of the following states listed in
1180
    L{JOB_STATUS_FINALIZED}.
1181

1182
    @type job_id: string
1183
    @param job_id: job id to watch
1184
    @type period: int
1185
    @param period: how often to poll for status (optional, default 5s)
1186
    @type retries: int
1187
    @param retries: how many time to poll before giving up
1188
                    (optional, default -1 means unlimited)
1189

1190
    @rtype: bool
1191
    @return: C{True} if job succeeded or C{False} if failed/status timeout
1192
    @deprecated: It is recommended to use L{WaitForJobChange} wherever
1193
      possible; L{WaitForJobChange} returns immediately after a job changed and
1194
      does not use polling
1195

1196
    """
1197
    while retries != 0:
1198
      job_result = self.GetJobStatus(job_id)
1199

    
1200
      if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
1201
        return True
1202
      elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
1203
        return False
1204

    
1205
      if period:
1206
        time.sleep(period)
1207

    
1208
      if retries > 0:
1209
        retries -= 1
1210

    
1211
    return False
1212

    
1213
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1214
    """Waits for job changes.
1215

1216
    @type job_id: string
1217
    @param job_id: Job ID for which to wait
1218
    @return: C{None} if no changes have been detected and a dict with two keys,
1219
      C{job_info} and C{log_entries} otherwise.
1220
    @rtype: dict
1221

1222
    """
1223
    body = {
1224
      "fields": fields,
1225
      "previous_job_info": prev_job_info,
1226
      "previous_log_serial": prev_log_serial,
1227
      }
1228

    
1229
    return self._SendRequest(HTTP_GET,
1230
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1231
                             None, body)
1232

    
1233
  def CancelJob(self, job_id, dry_run=False):
1234
    """Cancels a job.
1235

1236
    @type job_id: string
1237
    @param job_id: id of the job to delete
1238
    @type dry_run: bool
1239
    @param dry_run: whether to perform a dry run
1240
    @rtype: tuple
1241
    @return: tuple containing the result, and a message (bool, string)
1242

1243
    """
1244
    query = []
1245
    if dry_run:
1246
      query.append(("dry-run", 1))
1247

    
1248
    return self._SendRequest(HTTP_DELETE,
1249
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1250
                             query, None)
1251

    
1252
  def GetNodes(self, bulk=False):
1253
    """Gets all nodes in the cluster.
1254

1255
    @type bulk: bool
1256
    @param bulk: whether to return all information about all instances
1257

1258
    @rtype: list of dict or str
1259
    @return: if bulk is true, info about nodes in the cluster,
1260
        else list of nodes in the cluster
1261

1262
    """
1263
    query = []
1264
    if bulk:
1265
      query.append(("bulk", 1))
1266

    
1267
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1268
                              query, None)
1269
    if bulk:
1270
      return nodes
1271
    else:
1272
      return [n["id"] for n in nodes]
1273

    
1274
  def GetNode(self, node):
1275
    """Gets information about a node.
1276

1277
    @type node: str
1278
    @param node: node whose info to return
1279

1280
    @rtype: dict
1281
    @return: info about the node
1282

1283
    """
1284
    return self._SendRequest(HTTP_GET,
1285
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1286
                             None, None)
1287

    
1288
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1289
                   dry_run=False, early_release=None,
1290
                   primary=None, secondary=None, accept_old=False):
1291
    """Evacuates instances from a Ganeti node.
1292

1293
    @type node: str
1294
    @param node: node to evacuate
1295
    @type iallocator: str or None
1296
    @param iallocator: instance allocator to use
1297
    @type remote_node: str
1298
    @param remote_node: node to evaucate to
1299
    @type dry_run: bool
1300
    @param dry_run: whether to perform a dry run
1301
    @type early_release: bool
1302
    @param early_release: whether to enable parallelization
1303
    @type primary: bool
1304
    @param primary: Whether to evacuate primary instances
1305
    @type secondary: bool
1306
    @param secondary: Whether to evacuate secondary instances
1307
    @type accept_old: bool
1308
    @param accept_old: Whether caller is ready to accept old-style (pre-2.5)
1309
        results
1310

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

1317
    @raises GanetiApiError: if an iallocator and remote_node are both
1318
        specified
1319

1320
    """
1321
    if iallocator and remote_node:
1322
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1323

    
1324
    query = []
1325
    if dry_run:
1326
      query.append(("dry-run", 1))
1327

    
1328
    if _NODE_EVAC_RES1 in self.GetFeatures():
1329
      body = {}
1330

    
1331
      if iallocator is not None:
1332
        body["iallocator"] = iallocator
1333
      if remote_node is not None:
1334
        body["remote_node"] = remote_node
1335
      if early_release is not None:
1336
        body["early_release"] = early_release
1337
      if primary is not None:
1338
        body["primary"] = primary
1339
      if secondary is not None:
1340
        body["secondary"] = secondary
1341
    else:
1342
      # Pre-2.5 request format
1343
      body = None
1344

    
1345
      if not accept_old:
1346
        raise GanetiApiError("Server is version 2.4 or earlier and caller does"
1347
                             " not accept old-style results (parameter"
1348
                             " accept_old)")
1349

    
1350
      if primary or primary is None or not (secondary is None or secondary):
1351
        raise GanetiApiError("Server can only evacuate secondary instances")
1352

    
1353
      if iallocator:
1354
        query.append(("iallocator", iallocator))
1355
      if remote_node:
1356
        query.append(("remote_node", remote_node))
1357
      if early_release:
1358
        query.append(("early_release", 1))
1359

    
1360
    return self._SendRequest(HTTP_POST,
1361
                             ("/%s/nodes/%s/evacuate" %
1362
                              (GANETI_RAPI_VERSION, node)), query, body)
1363

    
1364
  def MigrateNode(self, node, mode=None, dry_run=False, iallocator=None,
1365
                  target_node=None):
1366
    """Migrates all primary instances from a node.
1367

1368
    @type node: str
1369
    @param node: node to migrate
1370
    @type mode: string
1371
    @param mode: if passed, it will overwrite the live migration type,
1372
        otherwise the hypervisor default will be used
1373
    @type dry_run: bool
1374
    @param dry_run: whether to perform a dry run
1375
    @type iallocator: string
1376
    @param iallocator: instance allocator to use
1377
    @type target_node: string
1378
    @param target_node: Target node for shared-storage instances
1379

1380
    @rtype: string
1381
    @return: job id
1382

1383
    """
1384
    query = []
1385
    if dry_run:
1386
      query.append(("dry-run", 1))
1387

    
1388
    if _NODE_MIGRATE_REQV1 in self.GetFeatures():
1389
      body = {}
1390

    
1391
      if mode is not None:
1392
        body["mode"] = mode
1393
      if iallocator is not None:
1394
        body["iallocator"] = iallocator
1395
      if target_node is not None:
1396
        body["target_node"] = target_node
1397

    
1398
      assert len(query) <= 1
1399

    
1400
      return self._SendRequest(HTTP_POST,
1401
                               ("/%s/nodes/%s/migrate" %
1402
                                (GANETI_RAPI_VERSION, node)), query, body)
1403
    else:
1404
      # Use old request format
1405
      if target_node is not None:
1406
        raise GanetiApiError("Server does not support specifying target node"
1407
                             " for node migration")
1408

    
1409
      if mode is not None:
1410
        query.append(("mode", mode))
1411

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

    
1416
  def GetNodeRole(self, node):
1417
    """Gets the current role for a node.
1418

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

1422
    @rtype: str
1423
    @return: the current role for a node
1424

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

    
1430
  def SetNodeRole(self, node, role, force=False):
1431
    """Sets the role for a node.
1432

1433
    @type node: str
1434
    @param node: the node whose role to set
1435
    @type role: str
1436
    @param role: the role to set for the node
1437
    @type force: bool
1438
    @param force: whether to force the role change
1439

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

1443
    """
1444
    query = [
1445
      ("force", force),
1446
      ]
1447

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

    
1452
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1453
    """Gets the storage units for a node.
1454

1455
    @type node: str
1456
    @param node: the node whose storage units to return
1457
    @type storage_type: str
1458
    @param storage_type: storage type whose units to return
1459
    @type output_fields: str
1460
    @param output_fields: storage type fields to return
1461

1462
    @rtype: string
1463
    @return: job id where results can be retrieved
1464

1465
    """
1466
    query = [
1467
      ("storage_type", storage_type),
1468
      ("output_fields", output_fields),
1469
      ]
1470

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

    
1475
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1476
    """Modifies parameters of storage units on the node.
1477

1478
    @type node: str
1479
    @param node: node whose storage units to modify
1480
    @type storage_type: str
1481
    @param storage_type: storage type whose units to modify
1482
    @type name: str
1483
    @param name: name of the storage unit
1484
    @type allocatable: bool or None
1485
    @param allocatable: Whether to set the "allocatable" flag on the storage
1486
                        unit (None=no modification, True=set, False=unset)
1487

1488
    @rtype: string
1489
    @return: job id
1490

1491
    """
1492
    query = [
1493
      ("storage_type", storage_type),
1494
      ("name", name),
1495
      ]
1496

    
1497
    if allocatable is not None:
1498
      query.append(("allocatable", allocatable))
1499

    
1500
    return self._SendRequest(HTTP_PUT,
1501
                             ("/%s/nodes/%s/storage/modify" %
1502
                              (GANETI_RAPI_VERSION, node)), query, None)
1503

    
1504
  def RepairNodeStorageUnits(self, node, storage_type, name):
1505
    """Repairs a storage unit on the node.
1506

1507
    @type node: str
1508
    @param node: node whose storage units to repair
1509
    @type storage_type: str
1510
    @param storage_type: storage type to repair
1511
    @type name: str
1512
    @param name: name of the storage unit to repair
1513

1514
    @rtype: string
1515
    @return: job id
1516

1517
    """
1518
    query = [
1519
      ("storage_type", storage_type),
1520
      ("name", name),
1521
      ]
1522

    
1523
    return self._SendRequest(HTTP_PUT,
1524
                             ("/%s/nodes/%s/storage/repair" %
1525
                              (GANETI_RAPI_VERSION, node)), query, None)
1526

    
1527
  def GetNodeTags(self, node):
1528
    """Gets the tags for a node.
1529

1530
    @type node: str
1531
    @param node: node whose tags to return
1532

1533
    @rtype: list of str
1534
    @return: tags for the node
1535

1536
    """
1537
    return self._SendRequest(HTTP_GET,
1538
                             ("/%s/nodes/%s/tags" %
1539
                              (GANETI_RAPI_VERSION, node)), None, None)
1540

    
1541
  def AddNodeTags(self, node, tags, dry_run=False):
1542
    """Adds tags to a node.
1543

1544
    @type node: str
1545
    @param node: node to add tags to
1546
    @type tags: list of str
1547
    @param tags: tags to add to the node
1548
    @type dry_run: bool
1549
    @param dry_run: whether to perform a dry run
1550

1551
    @rtype: string
1552
    @return: job id
1553

1554
    """
1555
    query = [("tag", t) for t in tags]
1556
    if dry_run:
1557
      query.append(("dry-run", 1))
1558

    
1559
    return self._SendRequest(HTTP_PUT,
1560
                             ("/%s/nodes/%s/tags" %
1561
                              (GANETI_RAPI_VERSION, node)), query, tags)
1562

    
1563
  def DeleteNodeTags(self, node, tags, dry_run=False):
1564
    """Delete tags from a node.
1565

1566
    @type node: str
1567
    @param node: node to remove tags from
1568
    @type tags: list of str
1569
    @param tags: tags to remove from the node
1570
    @type dry_run: bool
1571
    @param dry_run: whether to perform a dry run
1572

1573
    @rtype: string
1574
    @return: job id
1575

1576
    """
1577
    query = [("tag", t) for t in tags]
1578
    if dry_run:
1579
      query.append(("dry-run", 1))
1580

    
1581
    return self._SendRequest(HTTP_DELETE,
1582
                             ("/%s/nodes/%s/tags" %
1583
                              (GANETI_RAPI_VERSION, node)), query, None)
1584

    
1585
  def GetGroups(self, bulk=False):
1586
    """Gets all node groups in the cluster.
1587

1588
    @type bulk: bool
1589
    @param bulk: whether to return all information about the groups
1590

1591
    @rtype: list of dict or str
1592
    @return: if bulk is true, a list of dictionaries with info about all node
1593
        groups in the cluster, else a list of names of those node groups
1594

1595
    """
1596
    query = []
1597
    if bulk:
1598
      query.append(("bulk", 1))
1599

    
1600
    groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1601
                               query, None)
1602
    if bulk:
1603
      return groups
1604
    else:
1605
      return [g["name"] for g in groups]
1606

    
1607
  def GetGroup(self, group):
1608
    """Gets information about a node group.
1609

1610
    @type group: str
1611
    @param group: name of the node group whose info to return
1612

1613
    @rtype: dict
1614
    @return: info about the node group
1615

1616
    """
1617
    return self._SendRequest(HTTP_GET,
1618
                             "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
1619
                             None, None)
1620

    
1621
  def CreateGroup(self, name, alloc_policy=None, dry_run=False):
1622
    """Creates a new node group.
1623

1624
    @type name: str
1625
    @param name: the name of node group to create
1626
    @type alloc_policy: str
1627
    @param alloc_policy: the desired allocation policy for the group, if any
1628
    @type dry_run: bool
1629
    @param dry_run: whether to peform a dry run
1630

1631
    @rtype: string
1632
    @return: job id
1633

1634
    """
1635
    query = []
1636
    if dry_run:
1637
      query.append(("dry-run", 1))
1638

    
1639
    body = {
1640
      "name": name,
1641
      "alloc_policy": alloc_policy
1642
      }
1643

    
1644
    return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1645
                             query, body)
1646

    
1647
  def ModifyGroup(self, group, **kwargs):
1648
    """Modifies a node group.
1649

1650
    More details for parameters can be found in the RAPI documentation.
1651

1652
    @type group: string
1653
    @param group: Node group name
1654
    @rtype: string
1655
    @return: job id
1656

1657
    """
1658
    return self._SendRequest(HTTP_PUT,
1659
                             ("/%s/groups/%s/modify" %
1660
                              (GANETI_RAPI_VERSION, group)), None, kwargs)
1661

    
1662
  def DeleteGroup(self, group, dry_run=False):
1663
    """Deletes a node group.
1664

1665
    @type group: str
1666
    @param group: the node group to delete
1667
    @type dry_run: bool
1668
    @param dry_run: whether to peform a dry run
1669

1670
    @rtype: string
1671
    @return: job id
1672

1673
    """
1674
    query = []
1675
    if dry_run:
1676
      query.append(("dry-run", 1))
1677

    
1678
    return self._SendRequest(HTTP_DELETE,
1679
                             ("/%s/groups/%s" %
1680
                              (GANETI_RAPI_VERSION, group)), query, None)
1681

    
1682
  def RenameGroup(self, group, new_name):
1683
    """Changes the name of a node group.
1684

1685
    @type group: string
1686
    @param group: Node group name
1687
    @type new_name: string
1688
    @param new_name: New node group name
1689

1690
    @rtype: string
1691
    @return: job id
1692

1693
    """
1694
    body = {
1695
      "new_name": new_name,
1696
      }
1697

    
1698
    return self._SendRequest(HTTP_PUT,
1699
                             ("/%s/groups/%s/rename" %
1700
                              (GANETI_RAPI_VERSION, group)), None, body)
1701

    
1702
  def AssignGroupNodes(self, group, nodes, force=False, dry_run=False):
1703
    """Assigns nodes to a group.
1704

1705
    @type group: string
1706
    @param group: Node gropu name
1707
    @type nodes: list of strings
1708
    @param nodes: List of nodes to assign to the group
1709

1710
    @rtype: string
1711
    @return: job id
1712

1713
    """
1714
    query = []
1715

    
1716
    if force:
1717
      query.append(("force", 1))
1718

    
1719
    if dry_run:
1720
      query.append(("dry-run", 1))
1721

    
1722
    body = {
1723
      "nodes": nodes,
1724
      }
1725

    
1726
    return self._SendRequest(HTTP_PUT,
1727
                             ("/%s/groups/%s/assign-nodes" %
1728
                             (GANETI_RAPI_VERSION, group)), query, body)
1729

    
1730
  def GetGroupTags(self, group):
1731
    """Gets tags for a node group.
1732

1733
    @type group: string
1734
    @param group: Node group whose tags to return
1735

1736
    @rtype: list of strings
1737
    @return: tags for the group
1738

1739
    """
1740
    return self._SendRequest(HTTP_GET,
1741
                             ("/%s/groups/%s/tags" %
1742
                              (GANETI_RAPI_VERSION, group)), None, None)
1743

    
1744
  def AddGroupTags(self, group, tags, dry_run=False):
1745
    """Adds tags to a node group.
1746

1747
    @type group: str
1748
    @param group: group to add tags to
1749
    @type tags: list of string
1750
    @param tags: tags to add to the group
1751
    @type dry_run: bool
1752
    @param dry_run: whether to perform a dry run
1753

1754
    @rtype: string
1755
    @return: job id
1756

1757
    """
1758
    query = [("tag", t) for t in tags]
1759
    if dry_run:
1760
      query.append(("dry-run", 1))
1761

    
1762
    return self._SendRequest(HTTP_PUT,
1763
                             ("/%s/groups/%s/tags" %
1764
                              (GANETI_RAPI_VERSION, group)), query, None)
1765

    
1766
  def DeleteGroupTags(self, group, tags, dry_run=False):
1767
    """Deletes tags from a node group.
1768

1769
    @type group: str
1770
    @param group: group to delete tags from
1771
    @type tags: list of string
1772
    @param tags: tags to delete
1773
    @type dry_run: bool
1774
    @param dry_run: whether to perform a dry run
1775
    @rtype: string
1776
    @return: job id
1777

1778
    """
1779
    query = [("tag", t) for t in tags]
1780
    if dry_run:
1781
      query.append(("dry-run", 1))
1782

    
1783
    return self._SendRequest(HTTP_DELETE,
1784
                             ("/%s/groups/%s/tags" %
1785
                              (GANETI_RAPI_VERSION, group)), query, None)
1786

    
1787
  def Query(self, what, fields, filter_=None):
1788
    """Retrieves information about resources.
1789

1790
    @type what: string
1791
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1792
    @type fields: list of string
1793
    @param fields: Requested fields
1794
    @type filter_: None or list
1795
    @param filter_: Query filter
1796

1797
    @rtype: string
1798
    @return: job id
1799

1800
    """
1801
    body = {
1802
      "fields": fields,
1803
      }
1804

    
1805
    if filter_ is not None:
1806
      body["filter"] = filter_
1807

    
1808
    return self._SendRequest(HTTP_PUT,
1809
                             ("/%s/query/%s" %
1810
                              (GANETI_RAPI_VERSION, what)), None, body)
1811

    
1812
  def QueryFields(self, what, fields=None):
1813
    """Retrieves available fields for a resource.
1814

1815
    @type what: string
1816
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1817
    @type fields: list of string
1818
    @param fields: Requested fields
1819

1820
    @rtype: string
1821
    @return: job id
1822

1823
    """
1824
    query = []
1825

    
1826
    if fields is not None:
1827
      query.append(("fields", ",".join(fields)))
1828

    
1829
    return self._SendRequest(HTTP_GET,
1830
                             ("/%s/query/%s/fields" %
1831
                              (GANETI_RAPI_VERSION, what)), query, None)