Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ 2e5c33db

History | View | Annotate | Download (53.3 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=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 RecreateInstanceDisks(self, instance, disks=None, nodes=None):
757
    """Recreate an instance's disks.
758

759
    @type instance: string
760
    @param instance: Instance name
761
    @type disks: list of int
762
    @param disks: List of disk indexes
763
    @type nodes: list of string
764
    @param nodes: New instance nodes, if relocation is desired
765
    @rtype: string
766
    @return: job id
767

768
    """
769
    body = {}
770

    
771
    if disks is not None:
772
      body["disks"] = disks
773

    
774
    if nodes is not None:
775
      body["nodes"] = nodes
776

    
777
    return self._SendRequest(HTTP_POST,
778
                             ("/%s/instances/%s/recreate-disks" %
779
                              (GANETI_RAPI_VERSION, instance)), None, body)
780

    
781
  def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
782
    """Grows a disk of an instance.
783

784
    More details for parameters can be found in the RAPI documentation.
785

786
    @type instance: string
787
    @param instance: Instance name
788
    @type disk: integer
789
    @param disk: Disk index
790
    @type amount: integer
791
    @param amount: Grow disk by this amount (MiB)
792
    @type wait_for_sync: bool
793
    @param wait_for_sync: Wait for disk to synchronize
794
    @rtype: string
795
    @return: job id
796

797
    """
798
    body = {
799
      "amount": amount,
800
      }
801

    
802
    if wait_for_sync is not None:
803
      body["wait_for_sync"] = wait_for_sync
804

    
805
    return self._SendRequest(HTTP_POST,
806
                             ("/%s/instances/%s/disk/%s/grow" %
807
                              (GANETI_RAPI_VERSION, instance, disk)),
808
                             None, body)
809

    
810
  def GetInstanceTags(self, instance):
811
    """Gets tags for an instance.
812

813
    @type instance: str
814
    @param instance: instance whose tags to return
815

816
    @rtype: list of str
817
    @return: tags for the instance
818

819
    """
820
    return self._SendRequest(HTTP_GET,
821
                             ("/%s/instances/%s/tags" %
822
                              (GANETI_RAPI_VERSION, instance)), None, None)
823

    
824
  def AddInstanceTags(self, instance, tags, dry_run=False):
825
    """Adds tags to an instance.
826

827
    @type instance: str
828
    @param instance: instance to add tags to
829
    @type tags: list of str
830
    @param tags: tags to add to the instance
831
    @type dry_run: bool
832
    @param dry_run: whether to perform a dry run
833

834
    @rtype: string
835
    @return: job id
836

837
    """
838
    query = [("tag", t) for t in tags]
839
    if dry_run:
840
      query.append(("dry-run", 1))
841

    
842
    return self._SendRequest(HTTP_PUT,
843
                             ("/%s/instances/%s/tags" %
844
                              (GANETI_RAPI_VERSION, instance)), query, None)
845

    
846
  def DeleteInstanceTags(self, instance, tags, dry_run=False):
847
    """Deletes tags from an instance.
848

849
    @type instance: str
850
    @param instance: instance to delete tags from
851
    @type tags: list of str
852
    @param tags: tags to delete
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 = [("tag", t) for t in tags]
860
    if dry_run:
861
      query.append(("dry-run", 1))
862

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

    
867
  def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
868
                     dry_run=False):
869
    """Reboots an instance.
870

871
    @type instance: str
872
    @param instance: instance to rebot
873
    @type reboot_type: str
874
    @param reboot_type: one of: hard, soft, full
875
    @type ignore_secondaries: bool
876
    @param ignore_secondaries: if True, ignores errors for the secondary node
877
        while re-assembling disks (in hard-reboot mode only)
878
    @type dry_run: bool
879
    @param dry_run: whether to perform a dry run
880
    @rtype: string
881
    @return: job id
882

883
    """
884
    query = []
885
    if reboot_type:
886
      query.append(("type", reboot_type))
887
    if ignore_secondaries is not None:
888
      query.append(("ignore_secondaries", ignore_secondaries))
889
    if dry_run:
890
      query.append(("dry-run", 1))
891

    
892
    return self._SendRequest(HTTP_POST,
893
                             ("/%s/instances/%s/reboot" %
894
                              (GANETI_RAPI_VERSION, instance)), query, None)
895

    
896
  def ShutdownInstance(self, instance, dry_run=False, no_remember=False):
897
    """Shuts down an instance.
898

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

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

    
915
    return self._SendRequest(HTTP_PUT,
916
                             ("/%s/instances/%s/shutdown" %
917
                              (GANETI_RAPI_VERSION, instance)), query, None)
918

    
919
  def StartupInstance(self, instance, dry_run=False, no_remember=False):
920
    """Starts up an instance.
921

922
    @type instance: str
923
    @param instance: the instance to start up
924
    @type dry_run: bool
925
    @param dry_run: whether to perform a dry run
926
    @type no_remember: bool
927
    @param no_remember: if true, will not record the state change
928
    @rtype: string
929
    @return: job id
930

931
    """
932
    query = []
933
    if dry_run:
934
      query.append(("dry-run", 1))
935
    if no_remember:
936
      query.append(("no-remember", 1))
937

    
938
    return self._SendRequest(HTTP_PUT,
939
                             ("/%s/instances/%s/startup" %
940
                              (GANETI_RAPI_VERSION, instance)), query, None)
941

    
942
  def ReinstallInstance(self, instance, os=None, no_startup=False,
943
                        osparams=None):
944
    """Reinstalls an instance.
945

946
    @type instance: str
947
    @param instance: The instance to reinstall
948
    @type os: str or None
949
    @param os: The operating system to reinstall. If None, the instance's
950
        current operating system will be installed again
951
    @type no_startup: bool
952
    @param no_startup: Whether to start the instance automatically
953
    @rtype: string
954
    @return: job id
955

956
    """
957
    if _INST_REINSTALL_REQV1 in self.GetFeatures():
958
      body = {
959
        "start": not no_startup,
960
        }
961
      if os is not None:
962
        body["os"] = os
963
      if osparams is not None:
964
        body["osparams"] = osparams
965
      return self._SendRequest(HTTP_POST,
966
                               ("/%s/instances/%s/reinstall" %
967
                                (GANETI_RAPI_VERSION, instance)), None, body)
968

    
969
    # Use old request format
970
    if osparams:
971
      raise GanetiApiError("Server does not support specifying OS parameters"
972
                           " for instance reinstallation")
973

    
974
    query = []
975
    if os:
976
      query.append(("os", os))
977
    if no_startup:
978
      query.append(("nostartup", 1))
979
    return self._SendRequest(HTTP_POST,
980
                             ("/%s/instances/%s/reinstall" %
981
                              (GANETI_RAPI_VERSION, instance)), query, None)
982

    
983
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
984
                           remote_node=None, iallocator=None, dry_run=False):
985
    """Replaces disks on an instance.
986

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

1002
    @rtype: string
1003
    @return: job id
1004

1005
    """
1006
    query = [
1007
      ("mode", mode),
1008
      ]
1009

    
1010
    if disks:
1011
      query.append(("disks", ",".join(str(idx) for idx in disks)))
1012

    
1013
    if remote_node:
1014
      query.append(("remote_node", remote_node))
1015

    
1016
    if iallocator:
1017
      query.append(("iallocator", iallocator))
1018

    
1019
    if dry_run:
1020
      query.append(("dry-run", 1))
1021

    
1022
    return self._SendRequest(HTTP_POST,
1023
                             ("/%s/instances/%s/replace-disks" %
1024
                              (GANETI_RAPI_VERSION, instance)), query, None)
1025

    
1026
  def PrepareExport(self, instance, mode):
1027
    """Prepares an instance for an export.
1028

1029
    @type instance: string
1030
    @param instance: Instance name
1031
    @type mode: string
1032
    @param mode: Export mode
1033
    @rtype: string
1034
    @return: Job ID
1035

1036
    """
1037
    query = [("mode", mode)]
1038
    return self._SendRequest(HTTP_PUT,
1039
                             ("/%s/instances/%s/prepare-export" %
1040
                              (GANETI_RAPI_VERSION, instance)), query, None)
1041

    
1042
  def ExportInstance(self, instance, mode, destination, shutdown=None,
1043
                     remove_instance=None,
1044
                     x509_key_name=None, destination_x509_ca=None):
1045
    """Exports an instance.
1046

1047
    @type instance: string
1048
    @param instance: Instance name
1049
    @type mode: string
1050
    @param mode: Export mode
1051
    @rtype: string
1052
    @return: Job ID
1053

1054
    """
1055
    body = {
1056
      "destination": destination,
1057
      "mode": mode,
1058
      }
1059

    
1060
    if shutdown is not None:
1061
      body["shutdown"] = shutdown
1062

    
1063
    if remove_instance is not None:
1064
      body["remove_instance"] = remove_instance
1065

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

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

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

    
1076
  def MigrateInstance(self, instance, mode=None, cleanup=None):
1077
    """Migrates an instance.
1078

1079
    @type instance: string
1080
    @param instance: Instance name
1081
    @type mode: string
1082
    @param mode: Migration mode
1083
    @type cleanup: bool
1084
    @param cleanup: Whether to clean up a previously failed migration
1085
    @rtype: string
1086
    @return: job id
1087

1088
    """
1089
    body = {}
1090

    
1091
    if mode is not None:
1092
      body["mode"] = mode
1093

    
1094
    if cleanup is not None:
1095
      body["cleanup"] = cleanup
1096

    
1097
    return self._SendRequest(HTTP_PUT,
1098
                             ("/%s/instances/%s/migrate" %
1099
                              (GANETI_RAPI_VERSION, instance)), None, body)
1100

    
1101
  def FailoverInstance(self, instance, iallocator=None,
1102
                       ignore_consistency=None, target_node=None):
1103
    """Does a failover of an instance.
1104

1105
    @type instance: string
1106
    @param instance: Instance name
1107
    @type iallocator: string
1108
    @param iallocator: Iallocator for deciding the target node for
1109
      shared-storage instances
1110
    @type ignore_consistency: bool
1111
    @param ignore_consistency: Whether to ignore disk consistency
1112
    @type target_node: string
1113
    @param target_node: Target node for shared-storage instances
1114
    @rtype: string
1115
    @return: job id
1116

1117
    """
1118
    body = {}
1119

    
1120
    if iallocator is not None:
1121
      body["iallocator"] = iallocator
1122

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

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

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

    
1133
  def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
1134
    """Changes the name of an instance.
1135

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

1147
    """
1148
    body = {
1149
      "new_name": new_name,
1150
      }
1151

    
1152
    if ip_check is not None:
1153
      body["ip_check"] = ip_check
1154

    
1155
    if name_check is not None:
1156
      body["name_check"] = name_check
1157

    
1158
    return self._SendRequest(HTTP_PUT,
1159
                             ("/%s/instances/%s/rename" %
1160
                              (GANETI_RAPI_VERSION, instance)), None, body)
1161

    
1162
  def GetInstanceConsole(self, instance):
1163
    """Request information for connecting to instance's console.
1164

1165
    @type instance: string
1166
    @param instance: Instance name
1167
    @rtype: dict
1168
    @return: dictionary containing information about instance's console
1169

1170
    """
1171
    return self._SendRequest(HTTP_GET,
1172
                             ("/%s/instances/%s/console" %
1173
                              (GANETI_RAPI_VERSION, instance)), None, None)
1174

    
1175
  def GetJobs(self):
1176
    """Gets all jobs for the cluster.
1177

1178
    @rtype: list of int
1179
    @return: job ids for the cluster
1180

1181
    """
1182
    return [int(j["id"])
1183
            for j in self._SendRequest(HTTP_GET,
1184
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1185
                                       None, None)]
1186

    
1187
  def GetJobStatus(self, job_id):
1188
    """Gets the status of a job.
1189

1190
    @type job_id: string
1191
    @param job_id: job id whose status to query
1192

1193
    @rtype: dict
1194
    @return: job status
1195

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

    
1201
  def WaitForJobCompletion(self, job_id, period=5, retries=-1):
1202
    """Polls cluster for job status until completion.
1203

1204
    Completion is defined as any of the following states listed in
1205
    L{JOB_STATUS_FINALIZED}.
1206

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

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

1221
    """
1222
    while retries != 0:
1223
      job_result = self.GetJobStatus(job_id)
1224

    
1225
      if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
1226
        return True
1227
      elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
1228
        return False
1229

    
1230
      if period:
1231
        time.sleep(period)
1232

    
1233
      if retries > 0:
1234
        retries -= 1
1235

    
1236
    return False
1237

    
1238
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1239
    """Waits for job changes.
1240

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

1247
    """
1248
    body = {
1249
      "fields": fields,
1250
      "previous_job_info": prev_job_info,
1251
      "previous_log_serial": prev_log_serial,
1252
      }
1253

    
1254
    return self._SendRequest(HTTP_GET,
1255
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1256
                             None, body)
1257

    
1258
  def CancelJob(self, job_id, dry_run=False):
1259
    """Cancels a job.
1260

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

1268
    """
1269
    query = []
1270
    if dry_run:
1271
      query.append(("dry-run", 1))
1272

    
1273
    return self._SendRequest(HTTP_DELETE,
1274
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1275
                             query, None)
1276

    
1277
  def GetNodes(self, bulk=False):
1278
    """Gets all nodes in the cluster.
1279

1280
    @type bulk: bool
1281
    @param bulk: whether to return all information about all instances
1282

1283
    @rtype: list of dict or str
1284
    @return: if bulk is true, info about nodes in the cluster,
1285
        else list of nodes in the cluster
1286

1287
    """
1288
    query = []
1289
    if bulk:
1290
      query.append(("bulk", 1))
1291

    
1292
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1293
                              query, None)
1294
    if bulk:
1295
      return nodes
1296
    else:
1297
      return [n["id"] for n in nodes]
1298

    
1299
  def GetNode(self, node):
1300
    """Gets information about a node.
1301

1302
    @type node: str
1303
    @param node: node whose info to return
1304

1305
    @rtype: dict
1306
    @return: info about the node
1307

1308
    """
1309
    return self._SendRequest(HTTP_GET,
1310
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1311
                             None, None)
1312

    
1313
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1314
                   dry_run=False, early_release=None,
1315
                   primary=None, secondary=None, accept_old=False):
1316
    """Evacuates instances from a Ganeti node.
1317

1318
    @type node: str
1319
    @param node: node to evacuate
1320
    @type iallocator: str or None
1321
    @param iallocator: instance allocator to use
1322
    @type remote_node: str
1323
    @param remote_node: node to evaucate to
1324
    @type dry_run: bool
1325
    @param dry_run: whether to perform a dry run
1326
    @type early_release: bool
1327
    @param early_release: whether to enable parallelization
1328
    @type primary: bool
1329
    @param primary: Whether to evacuate primary instances
1330
    @type secondary: bool
1331
    @param secondary: Whether to evacuate secondary instances
1332
    @type accept_old: bool
1333
    @param accept_old: Whether caller is ready to accept old-style (pre-2.5)
1334
        results
1335

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

1342
    @raises GanetiApiError: if an iallocator and remote_node are both
1343
        specified
1344

1345
    """
1346
    if iallocator and remote_node:
1347
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1348

    
1349
    query = []
1350
    if dry_run:
1351
      query.append(("dry-run", 1))
1352

    
1353
    if _NODE_EVAC_RES1 in self.GetFeatures():
1354
      body = {}
1355

    
1356
      if iallocator is not None:
1357
        body["iallocator"] = iallocator
1358
      if remote_node is not None:
1359
        body["remote_node"] = remote_node
1360
      if early_release is not None:
1361
        body["early_release"] = early_release
1362
      if primary is not None:
1363
        body["primary"] = primary
1364
      if secondary is not None:
1365
        body["secondary"] = secondary
1366
    else:
1367
      # Pre-2.5 request format
1368
      body = None
1369

    
1370
      if not accept_old:
1371
        raise GanetiApiError("Server is version 2.4 or earlier and caller does"
1372
                             " not accept old-style results (parameter"
1373
                             " accept_old)")
1374

    
1375
      if primary or primary is None or not (secondary is None or secondary):
1376
        raise GanetiApiError("Server can only evacuate secondary instances")
1377

    
1378
      if iallocator:
1379
        query.append(("iallocator", iallocator))
1380
      if remote_node:
1381
        query.append(("remote_node", remote_node))
1382
      if early_release:
1383
        query.append(("early_release", 1))
1384

    
1385
    return self._SendRequest(HTTP_POST,
1386
                             ("/%s/nodes/%s/evacuate" %
1387
                              (GANETI_RAPI_VERSION, node)), query, body)
1388

    
1389
  def MigrateNode(self, node, mode=None, dry_run=False, iallocator=None,
1390
                  target_node=None):
1391
    """Migrates all primary instances from a node.
1392

1393
    @type node: str
1394
    @param node: node to migrate
1395
    @type mode: string
1396
    @param mode: if passed, it will overwrite the live migration type,
1397
        otherwise the hypervisor default will be used
1398
    @type dry_run: bool
1399
    @param dry_run: whether to perform a dry run
1400
    @type iallocator: string
1401
    @param iallocator: instance allocator to use
1402
    @type target_node: string
1403
    @param target_node: Target node for shared-storage instances
1404

1405
    @rtype: string
1406
    @return: job id
1407

1408
    """
1409
    query = []
1410
    if dry_run:
1411
      query.append(("dry-run", 1))
1412

    
1413
    if _NODE_MIGRATE_REQV1 in self.GetFeatures():
1414
      body = {}
1415

    
1416
      if mode is not None:
1417
        body["mode"] = mode
1418
      if iallocator is not None:
1419
        body["iallocator"] = iallocator
1420
      if target_node is not None:
1421
        body["target_node"] = target_node
1422

    
1423
      assert len(query) <= 1
1424

    
1425
      return self._SendRequest(HTTP_POST,
1426
                               ("/%s/nodes/%s/migrate" %
1427
                                (GANETI_RAPI_VERSION, node)), query, body)
1428
    else:
1429
      # Use old request format
1430
      if target_node is not None:
1431
        raise GanetiApiError("Server does not support specifying target node"
1432
                             " for node migration")
1433

    
1434
      if mode is not None:
1435
        query.append(("mode", mode))
1436

    
1437
      return self._SendRequest(HTTP_POST,
1438
                               ("/%s/nodes/%s/migrate" %
1439
                                (GANETI_RAPI_VERSION, node)), query, None)
1440

    
1441
  def GetNodeRole(self, node):
1442
    """Gets the current role for a node.
1443

1444
    @type node: str
1445
    @param node: node whose role to return
1446

1447
    @rtype: str
1448
    @return: the current role for a node
1449

1450
    """
1451
    return self._SendRequest(HTTP_GET,
1452
                             ("/%s/nodes/%s/role" %
1453
                              (GANETI_RAPI_VERSION, node)), None, None)
1454

    
1455
  def SetNodeRole(self, node, role, force=False):
1456
    """Sets the role for a node.
1457

1458
    @type node: str
1459
    @param node: the node whose role to set
1460
    @type role: str
1461
    @param role: the role to set for the node
1462
    @type force: bool
1463
    @param force: whether to force the role change
1464

1465
    @rtype: string
1466
    @return: job id
1467

1468
    """
1469
    query = [
1470
      ("force", force),
1471
      ]
1472

    
1473
    return self._SendRequest(HTTP_PUT,
1474
                             ("/%s/nodes/%s/role" %
1475
                              (GANETI_RAPI_VERSION, node)), query, role)
1476

    
1477
  def PowercycleNode(self, node, force=False):
1478
    """Powercycles a node.
1479

1480
    @type node: string
1481
    @param node: Node name
1482
    @type force: bool
1483
    @param force: Whether to force the operation
1484

1485
    @rtype: string
1486
    @return: job id
1487

1488
    """
1489
    query = [
1490
      ("force", force),
1491
      ]
1492

    
1493
    return self._SendRequest(HTTP_POST,
1494
                             ("/%s/nodes/%s/powercycle" %
1495
                              (GANETI_RAPI_VERSION, node)), query, None)
1496

    
1497
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1498
    """Gets the storage units for a node.
1499

1500
    @type node: str
1501
    @param node: the node whose storage units to return
1502
    @type storage_type: str
1503
    @param storage_type: storage type whose units to return
1504
    @type output_fields: str
1505
    @param output_fields: storage type fields to return
1506

1507
    @rtype: string
1508
    @return: job id where results can be retrieved
1509

1510
    """
1511
    query = [
1512
      ("storage_type", storage_type),
1513
      ("output_fields", output_fields),
1514
      ]
1515

    
1516
    return self._SendRequest(HTTP_GET,
1517
                             ("/%s/nodes/%s/storage" %
1518
                              (GANETI_RAPI_VERSION, node)), query, None)
1519

    
1520
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1521
    """Modifies parameters of storage units on the node.
1522

1523
    @type node: str
1524
    @param node: node whose storage units to modify
1525
    @type storage_type: str
1526
    @param storage_type: storage type whose units to modify
1527
    @type name: str
1528
    @param name: name of the storage unit
1529
    @type allocatable: bool or None
1530
    @param allocatable: Whether to set the "allocatable" flag on the storage
1531
                        unit (None=no modification, True=set, False=unset)
1532

1533
    @rtype: string
1534
    @return: job id
1535

1536
    """
1537
    query = [
1538
      ("storage_type", storage_type),
1539
      ("name", name),
1540
      ]
1541

    
1542
    if allocatable is not None:
1543
      query.append(("allocatable", allocatable))
1544

    
1545
    return self._SendRequest(HTTP_PUT,
1546
                             ("/%s/nodes/%s/storage/modify" %
1547
                              (GANETI_RAPI_VERSION, node)), query, None)
1548

    
1549
  def RepairNodeStorageUnits(self, node, storage_type, name):
1550
    """Repairs a storage unit on the node.
1551

1552
    @type node: str
1553
    @param node: node whose storage units to repair
1554
    @type storage_type: str
1555
    @param storage_type: storage type to repair
1556
    @type name: str
1557
    @param name: name of the storage unit to repair
1558

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

1562
    """
1563
    query = [
1564
      ("storage_type", storage_type),
1565
      ("name", name),
1566
      ]
1567

    
1568
    return self._SendRequest(HTTP_PUT,
1569
                             ("/%s/nodes/%s/storage/repair" %
1570
                              (GANETI_RAPI_VERSION, node)), query, None)
1571

    
1572
  def GetNodeTags(self, node):
1573
    """Gets the tags for a node.
1574

1575
    @type node: str
1576
    @param node: node whose tags to return
1577

1578
    @rtype: list of str
1579
    @return: tags for the node
1580

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

    
1586
  def AddNodeTags(self, node, tags, dry_run=False):
1587
    """Adds tags to a node.
1588

1589
    @type node: str
1590
    @param node: node to add tags to
1591
    @type tags: list of str
1592
    @param tags: tags to add to the node
1593
    @type dry_run: bool
1594
    @param dry_run: whether to perform a dry run
1595

1596
    @rtype: string
1597
    @return: job id
1598

1599
    """
1600
    query = [("tag", t) for t in tags]
1601
    if dry_run:
1602
      query.append(("dry-run", 1))
1603

    
1604
    return self._SendRequest(HTTP_PUT,
1605
                             ("/%s/nodes/%s/tags" %
1606
                              (GANETI_RAPI_VERSION, node)), query, tags)
1607

    
1608
  def DeleteNodeTags(self, node, tags, dry_run=False):
1609
    """Delete tags from a node.
1610

1611
    @type node: str
1612
    @param node: node to remove tags from
1613
    @type tags: list of str
1614
    @param tags: tags to remove from the node
1615
    @type dry_run: bool
1616
    @param dry_run: whether to perform a dry run
1617

1618
    @rtype: string
1619
    @return: job id
1620

1621
    """
1622
    query = [("tag", t) for t in tags]
1623
    if dry_run:
1624
      query.append(("dry-run", 1))
1625

    
1626
    return self._SendRequest(HTTP_DELETE,
1627
                             ("/%s/nodes/%s/tags" %
1628
                              (GANETI_RAPI_VERSION, node)), query, None)
1629

    
1630
  def GetGroups(self, bulk=False):
1631
    """Gets all node groups in the cluster.
1632

1633
    @type bulk: bool
1634
    @param bulk: whether to return all information about the groups
1635

1636
    @rtype: list of dict or str
1637
    @return: if bulk is true, a list of dictionaries with info about all node
1638
        groups in the cluster, else a list of names of those node groups
1639

1640
    """
1641
    query = []
1642
    if bulk:
1643
      query.append(("bulk", 1))
1644

    
1645
    groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1646
                               query, None)
1647
    if bulk:
1648
      return groups
1649
    else:
1650
      return [g["name"] for g in groups]
1651

    
1652
  def GetGroup(self, group):
1653
    """Gets information about a node group.
1654

1655
    @type group: str
1656
    @param group: name of the node group whose info to return
1657

1658
    @rtype: dict
1659
    @return: info about the node group
1660

1661
    """
1662
    return self._SendRequest(HTTP_GET,
1663
                             "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
1664
                             None, None)
1665

    
1666
  def CreateGroup(self, name, alloc_policy=None, dry_run=False):
1667
    """Creates a new node group.
1668

1669
    @type name: str
1670
    @param name: the name of node group to create
1671
    @type alloc_policy: str
1672
    @param alloc_policy: the desired allocation policy for the group, if any
1673
    @type dry_run: bool
1674
    @param dry_run: whether to peform a dry run
1675

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

1679
    """
1680
    query = []
1681
    if dry_run:
1682
      query.append(("dry-run", 1))
1683

    
1684
    body = {
1685
      "name": name,
1686
      "alloc_policy": alloc_policy
1687
      }
1688

    
1689
    return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1690
                             query, body)
1691

    
1692
  def ModifyGroup(self, group, **kwargs):
1693
    """Modifies a node group.
1694

1695
    More details for parameters can be found in the RAPI documentation.
1696

1697
    @type group: string
1698
    @param group: Node group name
1699
    @rtype: string
1700
    @return: job id
1701

1702
    """
1703
    return self._SendRequest(HTTP_PUT,
1704
                             ("/%s/groups/%s/modify" %
1705
                              (GANETI_RAPI_VERSION, group)), None, kwargs)
1706

    
1707
  def DeleteGroup(self, group, dry_run=False):
1708
    """Deletes a node group.
1709

1710
    @type group: str
1711
    @param group: the node group to delete
1712
    @type dry_run: bool
1713
    @param dry_run: whether to peform a dry run
1714

1715
    @rtype: string
1716
    @return: job id
1717

1718
    """
1719
    query = []
1720
    if dry_run:
1721
      query.append(("dry-run", 1))
1722

    
1723
    return self._SendRequest(HTTP_DELETE,
1724
                             ("/%s/groups/%s" %
1725
                              (GANETI_RAPI_VERSION, group)), query, None)
1726

    
1727
  def RenameGroup(self, group, new_name):
1728
    """Changes the name of a node group.
1729

1730
    @type group: string
1731
    @param group: Node group name
1732
    @type new_name: string
1733
    @param new_name: New node group name
1734

1735
    @rtype: string
1736
    @return: job id
1737

1738
    """
1739
    body = {
1740
      "new_name": new_name,
1741
      }
1742

    
1743
    return self._SendRequest(HTTP_PUT,
1744
                             ("/%s/groups/%s/rename" %
1745
                              (GANETI_RAPI_VERSION, group)), None, body)
1746

    
1747
  def AssignGroupNodes(self, group, nodes, force=False, dry_run=False):
1748
    """Assigns nodes to a group.
1749

1750
    @type group: string
1751
    @param group: Node gropu name
1752
    @type nodes: list of strings
1753
    @param nodes: List of nodes to assign to the group
1754

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

1758
    """
1759
    query = []
1760

    
1761
    if force:
1762
      query.append(("force", 1))
1763

    
1764
    if dry_run:
1765
      query.append(("dry-run", 1))
1766

    
1767
    body = {
1768
      "nodes": nodes,
1769
      }
1770

    
1771
    return self._SendRequest(HTTP_PUT,
1772
                             ("/%s/groups/%s/assign-nodes" %
1773
                             (GANETI_RAPI_VERSION, group)), query, body)
1774

    
1775
  def GetGroupTags(self, group):
1776
    """Gets tags for a node group.
1777

1778
    @type group: string
1779
    @param group: Node group whose tags to return
1780

1781
    @rtype: list of strings
1782
    @return: tags for the group
1783

1784
    """
1785
    return self._SendRequest(HTTP_GET,
1786
                             ("/%s/groups/%s/tags" %
1787
                              (GANETI_RAPI_VERSION, group)), None, None)
1788

    
1789
  def AddGroupTags(self, group, tags, dry_run=False):
1790
    """Adds tags to a node group.
1791

1792
    @type group: str
1793
    @param group: group to add tags to
1794
    @type tags: list of string
1795
    @param tags: tags to add to the group
1796
    @type dry_run: bool
1797
    @param dry_run: whether to perform a dry run
1798

1799
    @rtype: string
1800
    @return: job id
1801

1802
    """
1803
    query = [("tag", t) for t in tags]
1804
    if dry_run:
1805
      query.append(("dry-run", 1))
1806

    
1807
    return self._SendRequest(HTTP_PUT,
1808
                             ("/%s/groups/%s/tags" %
1809
                              (GANETI_RAPI_VERSION, group)), query, None)
1810

    
1811
  def DeleteGroupTags(self, group, tags, dry_run=False):
1812
    """Deletes tags from a node group.
1813

1814
    @type group: str
1815
    @param group: group to delete tags from
1816
    @type tags: list of string
1817
    @param tags: tags to delete
1818
    @type dry_run: bool
1819
    @param dry_run: whether to perform a dry run
1820
    @rtype: string
1821
    @return: job id
1822

1823
    """
1824
    query = [("tag", t) for t in tags]
1825
    if dry_run:
1826
      query.append(("dry-run", 1))
1827

    
1828
    return self._SendRequest(HTTP_DELETE,
1829
                             ("/%s/groups/%s/tags" %
1830
                              (GANETI_RAPI_VERSION, group)), query, None)
1831

    
1832
  def Query(self, what, fields, qfilter=None):
1833
    """Retrieves information about resources.
1834

1835
    @type what: string
1836
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1837
    @type fields: list of string
1838
    @param fields: Requested fields
1839
    @type qfilter: None or list
1840
    @param qfilter: Query filter
1841

1842
    @rtype: string
1843
    @return: job id
1844

1845
    """
1846
    body = {
1847
      "fields": fields,
1848
      }
1849

    
1850
    if qfilter is not None:
1851
      body["qfilter"] = qfilter
1852
      # TODO: remove this after 2.7
1853
      body["filter"] = qfilter
1854

    
1855
    return self._SendRequest(HTTP_PUT,
1856
                             ("/%s/query/%s" %
1857
                              (GANETI_RAPI_VERSION, what)), None, body)
1858

    
1859
  def QueryFields(self, what, fields=None):
1860
    """Retrieves available fields for a resource.
1861

1862
    @type what: string
1863
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1864
    @type fields: list of string
1865
    @param fields: Requested fields
1866

1867
    @rtype: string
1868
    @return: job id
1869

1870
    """
1871
    query = []
1872

    
1873
    if fields is not None:
1874
      query.append(("fields", ",".join(fields)))
1875

    
1876
    return self._SendRequest(HTTP_GET,
1877
                             ("/%s/query/%s/fields" %
1878
                              (GANETI_RAPI_VERSION, what)), query, None)