Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ 57d8e228

History | View | Annotate | Download (54.4 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_EVAC_PRI = "primary-only"
67
NODE_EVAC_SEC = "secondary-only"
68
NODE_EVAC_ALL = "all"
69

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

    
76
JOB_STATUS_QUEUED = "queued"
77
JOB_STATUS_WAITING = "waiting"
78
JOB_STATUS_CANCELING = "canceling"
79
JOB_STATUS_RUNNING = "running"
80
JOB_STATUS_CANCELED = "canceled"
81
JOB_STATUS_SUCCESS = "success"
82
JOB_STATUS_ERROR = "error"
83
JOB_STATUS_FINALIZED = frozenset([
84
  JOB_STATUS_CANCELED,
85
  JOB_STATUS_SUCCESS,
86
  JOB_STATUS_ERROR,
87
  ])
88
JOB_STATUS_ALL = frozenset([
89
  JOB_STATUS_QUEUED,
90
  JOB_STATUS_WAITING,
91
  JOB_STATUS_CANCELING,
92
  JOB_STATUS_RUNNING,
93
  ]) | JOB_STATUS_FINALIZED
94

    
95
# Legacy name
96
JOB_STATUS_WAITLOCK = JOB_STATUS_WAITING
97

    
98
# Internal constants
99
_REQ_DATA_VERSION_FIELD = "__version__"
100
_INST_CREATE_REQV1 = "instance-create-reqv1"
101
_INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
102
_NODE_MIGRATE_REQV1 = "node-migrate-reqv1"
103
_NODE_EVAC_RES1 = "node-evac-res1"
104
_INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link"])
105
_INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
106
_INST_CREATE_V0_PARAMS = frozenset([
107
  "os", "pnode", "snode", "iallocator", "start", "ip_check", "name_check",
108
  "hypervisor", "file_storage_dir", "file_driver", "dry_run",
109
  ])
110
_INST_CREATE_V0_DPARAMS = frozenset(["beparams", "hvparams"])
111
_QPARAM_DRY_RUN = "dry-run"
112
_QPARAM_FORCE = "force"
113

    
114
# Older pycURL versions don't have all error constants
115
try:
116
  _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
117
  _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
118
except AttributeError:
119
  _CURLE_SSL_CACERT = 60
120
  _CURLE_SSL_CACERT_BADFILE = 77
121

    
122
_CURL_SSL_CERT_ERRORS = frozenset([
123
  _CURLE_SSL_CACERT,
124
  _CURLE_SSL_CACERT_BADFILE,
125
  ])
126

    
127

    
128
class Error(Exception):
129
  """Base error class for this module.
130

131
  """
132
  pass
133

    
134

    
135
class CertificateError(Error):
136
  """Raised when a problem is found with the SSL certificate.
137

138
  """
139
  pass
140

    
141

    
142
class GanetiApiError(Error):
143
  """Generic error raised from Ganeti API.
144

145
  """
146
  def __init__(self, msg, code=None):
147
    Error.__init__(self, msg)
148
    self.code = code
149

    
150

    
151
def _AppendIf(container, condition, value):
152
  """Appends to a list if a condition evaluates to truth.
153

154
  """
155
  if condition:
156
    container.append(value)
157

    
158
  return condition
159

    
160

    
161
def _AppendDryRunIf(container, condition):
162
  """Appends a "dry-run" parameter if a condition evaluates to truth.
163

164
  """
165
  return _AppendIf(container, condition, (_QPARAM_DRY_RUN, 1))
166

    
167

    
168
def _AppendForceIf(container, condition):
169
  """Appends a "force" parameter if a condition evaluates to truth.
170

171
  """
172
  return _AppendIf(container, condition, (_QPARAM_FORCE, 1))
173

    
174

    
175
def _SetItemIf(container, condition, item, value):
176
  """Sets an item if a condition evaluates to truth.
177

178
  """
179
  if condition:
180
    container[item] = value
181

    
182
  return condition
183

    
184

    
185
def UsesRapiClient(fn):
186
  """Decorator for code using RAPI client to initialize pycURL.
187

188
  """
189
  def wrapper(*args, **kwargs):
190
    # curl_global_init(3) and curl_global_cleanup(3) must be called with only
191
    # one thread running. This check is just a safety measure -- it doesn't
192
    # cover all cases.
193
    assert threading.activeCount() == 1, \
194
           "Found active threads when initializing pycURL"
195

    
196
    pycurl.global_init(pycurl.GLOBAL_ALL)
197
    try:
198
      return fn(*args, **kwargs)
199
    finally:
200
      pycurl.global_cleanup()
201

    
202
  return wrapper
203

    
204

    
205
def GenericCurlConfig(verbose=False, use_signal=False,
206
                      use_curl_cabundle=False, cafile=None, capath=None,
207
                      proxy=None, verify_hostname=False,
208
                      connect_timeout=None, timeout=None,
209
                      _pycurl_version_fn=pycurl.version_info):
210
  """Curl configuration function generator.
211

212
  @type verbose: bool
213
  @param verbose: Whether to set cURL to verbose mode
214
  @type use_signal: bool
215
  @param use_signal: Whether to allow cURL to use signals
216
  @type use_curl_cabundle: bool
217
  @param use_curl_cabundle: Whether to use cURL's default CA bundle
218
  @type cafile: string
219
  @param cafile: In which file we can find the certificates
220
  @type capath: string
221
  @param capath: In which directory we can find the certificates
222
  @type proxy: string
223
  @param proxy: Proxy to use, None for default behaviour and empty string for
224
                disabling proxies (see curl_easy_setopt(3))
225
  @type verify_hostname: bool
226
  @param verify_hostname: Whether to verify the remote peer certificate's
227
                          commonName
228
  @type connect_timeout: number
229
  @param connect_timeout: Timeout for establishing connection in seconds
230
  @type timeout: number
231
  @param timeout: Timeout for complete transfer in seconds (see
232
                  curl_easy_setopt(3)).
233

234
  """
235
  if use_curl_cabundle and (cafile or capath):
236
    raise Error("Can not use default CA bundle when CA file or path is set")
237

    
238
  def _ConfigCurl(curl, logger):
239
    """Configures a cURL object
240

241
    @type curl: pycurl.Curl
242
    @param curl: cURL object
243

244
    """
245
    logger.debug("Using cURL version %s", pycurl.version)
246

    
247
    # pycurl.version_info returns a tuple with information about the used
248
    # version of libcurl. Item 5 is the SSL library linked to it.
249
    # e.g.: (3, '7.18.0', 463360, 'x86_64-pc-linux-gnu', 1581, 'GnuTLS/2.0.4',
250
    # 0, '1.2.3.3', ...)
251
    sslver = _pycurl_version_fn()[5]
252
    if not sslver:
253
      raise Error("No SSL support in cURL")
254

    
255
    lcsslver = sslver.lower()
256
    if lcsslver.startswith("openssl/"):
257
      pass
258
    elif lcsslver.startswith("gnutls/"):
259
      if capath:
260
        raise Error("cURL linked against GnuTLS has no support for a"
261
                    " CA path (%s)" % (pycurl.version, ))
262
    else:
263
      raise NotImplementedError("cURL uses unsupported SSL version '%s'" %
264
                                sslver)
265

    
266
    curl.setopt(pycurl.VERBOSE, verbose)
267
    curl.setopt(pycurl.NOSIGNAL, not use_signal)
268

    
269
    # Whether to verify remote peer's CN
270
    if verify_hostname:
271
      # curl_easy_setopt(3): "When CURLOPT_SSL_VERIFYHOST is 2, that
272
      # certificate must indicate that the server is the server to which you
273
      # meant to connect, or the connection fails. [...] When the value is 1,
274
      # the certificate must contain a Common Name field, but it doesn't matter
275
      # what name it says. [...]"
276
      curl.setopt(pycurl.SSL_VERIFYHOST, 2)
277
    else:
278
      curl.setopt(pycurl.SSL_VERIFYHOST, 0)
279

    
280
    if cafile or capath or use_curl_cabundle:
281
      # Require certificates to be checked
282
      curl.setopt(pycurl.SSL_VERIFYPEER, True)
283
      if cafile:
284
        curl.setopt(pycurl.CAINFO, str(cafile))
285
      if capath:
286
        curl.setopt(pycurl.CAPATH, str(capath))
287
      # Not changing anything for using default CA bundle
288
    else:
289
      # Disable SSL certificate verification
290
      curl.setopt(pycurl.SSL_VERIFYPEER, False)
291

    
292
    if proxy is not None:
293
      curl.setopt(pycurl.PROXY, str(proxy))
294

    
295
    # Timeouts
296
    if connect_timeout is not None:
297
      curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
298
    if timeout is not None:
299
      curl.setopt(pycurl.TIMEOUT, timeout)
300

    
301
  return _ConfigCurl
302

    
303

    
304
class GanetiRapiClient(object): # pylint: disable=R0904
305
  """Ganeti RAPI client.
306

307
  """
308
  USER_AGENT = "Ganeti RAPI Client"
309
  _json_encoder = simplejson.JSONEncoder(sort_keys=True)
310

    
311
  def __init__(self, host, port=GANETI_RAPI_PORT,
312
               username=None, password=None, logger=logging,
313
               curl_config_fn=None, curl_factory=None):
314
    """Initializes this class.
315

316
    @type host: string
317
    @param host: the ganeti cluster master to interact with
318
    @type port: int
319
    @param port: the port on which the RAPI is running (default is 5080)
320
    @type username: string
321
    @param username: the username to connect with
322
    @type password: string
323
    @param password: the password to connect with
324
    @type curl_config_fn: callable
325
    @param curl_config_fn: Function to configure C{pycurl.Curl} object
326
    @param logger: Logging object
327

328
    """
329
    self._username = username
330
    self._password = password
331
    self._logger = logger
332
    self._curl_config_fn = curl_config_fn
333
    self._curl_factory = curl_factory
334

    
335
    try:
336
      socket.inet_pton(socket.AF_INET6, host)
337
      address = "[%s]:%s" % (host, port)
338
    except socket.error:
339
      address = "%s:%s" % (host, port)
340

    
341
    self._base_url = "https://%s" % address
342

    
343
    if username is not None:
344
      if password is None:
345
        raise Error("Password not specified")
346
    elif password:
347
      raise Error("Specified password without username")
348

    
349
  def _CreateCurl(self):
350
    """Creates a cURL object.
351

352
    """
353
    # Create pycURL object if no factory is provided
354
    if self._curl_factory:
355
      curl = self._curl_factory()
356
    else:
357
      curl = pycurl.Curl()
358

    
359
    # Default cURL settings
360
    curl.setopt(pycurl.VERBOSE, False)
361
    curl.setopt(pycurl.FOLLOWLOCATION, False)
362
    curl.setopt(pycurl.MAXREDIRS, 5)
363
    curl.setopt(pycurl.NOSIGNAL, True)
364
    curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
365
    curl.setopt(pycurl.SSL_VERIFYHOST, 0)
366
    curl.setopt(pycurl.SSL_VERIFYPEER, False)
367
    curl.setopt(pycurl.HTTPHEADER, [
368
      "Accept: %s" % HTTP_APP_JSON,
369
      "Content-type: %s" % HTTP_APP_JSON,
370
      ])
371

    
372
    assert ((self._username is None and self._password is None) ^
373
            (self._username is not None and self._password is not None))
374

    
375
    if self._username:
376
      # Setup authentication
377
      curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
378
      curl.setopt(pycurl.USERPWD,
379
                  str("%s:%s" % (self._username, self._password)))
380

    
381
    # Call external configuration function
382
    if self._curl_config_fn:
383
      self._curl_config_fn(curl, self._logger)
384

    
385
    return curl
386

    
387
  @staticmethod
388
  def _EncodeQuery(query):
389
    """Encode query values for RAPI URL.
390

391
    @type query: list of two-tuples
392
    @param query: Query arguments
393
    @rtype: list
394
    @return: Query list with encoded values
395

396
    """
397
    result = []
398

    
399
    for name, value in query:
400
      if value is None:
401
        result.append((name, ""))
402

    
403
      elif isinstance(value, bool):
404
        # Boolean values must be encoded as 0 or 1
405
        result.append((name, int(value)))
406

    
407
      elif isinstance(value, (list, tuple, dict)):
408
        raise ValueError("Invalid query data type %r" % type(value).__name__)
409

    
410
      else:
411
        result.append((name, value))
412

    
413
    return result
414

    
415
  def _SendRequest(self, method, path, query, content):
416
    """Sends an HTTP request.
417

418
    This constructs a full URL, encodes and decodes HTTP bodies, and
419
    handles invalid responses in a pythonic way.
420

421
    @type method: string
422
    @param method: HTTP method to use
423
    @type path: string
424
    @param path: HTTP URL path
425
    @type query: list of two-tuples
426
    @param query: query arguments to pass to urllib.urlencode
427
    @type content: str or None
428
    @param content: HTTP body content
429

430
    @rtype: str
431
    @return: JSON-Decoded response
432

433
    @raises CertificateError: If an invalid SSL certificate is found
434
    @raises GanetiApiError: If an invalid response is returned
435

436
    """
437
    assert path.startswith("/")
438

    
439
    curl = self._CreateCurl()
440

    
441
    if content is not None:
442
      encoded_content = self._json_encoder.encode(content)
443
    else:
444
      encoded_content = ""
445

    
446
    # Build URL
447
    urlparts = [self._base_url, path]
448
    if query:
449
      urlparts.append("?")
450
      urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
451

    
452
    url = "".join(urlparts)
453

    
454
    self._logger.debug("Sending request %s %s (content=%r)",
455
                       method, url, encoded_content)
456

    
457
    # Buffer for response
458
    encoded_resp_body = StringIO()
459

    
460
    # Configure cURL
461
    curl.setopt(pycurl.CUSTOMREQUEST, str(method))
462
    curl.setopt(pycurl.URL, str(url))
463
    curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
464
    curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
465

    
466
    try:
467
      # Send request and wait for response
468
      try:
469
        curl.perform()
470
      except pycurl.error, err:
471
        if err.args[0] in _CURL_SSL_CERT_ERRORS:
472
          raise CertificateError("SSL certificate error %s" % err)
473

    
474
        raise GanetiApiError(str(err))
475
    finally:
476
      # Reset settings to not keep references to large objects in memory
477
      # between requests
478
      curl.setopt(pycurl.POSTFIELDS, "")
479
      curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)
480

    
481
    # Get HTTP response code
482
    http_code = curl.getinfo(pycurl.RESPONSE_CODE)
483

    
484
    # Was anything written to the response buffer?
485
    if encoded_resp_body.tell():
486
      response_content = simplejson.loads(encoded_resp_body.getvalue())
487
    else:
488
      response_content = None
489

    
490
    if http_code != HTTP_OK:
491
      if isinstance(response_content, dict):
492
        msg = ("%s %s: %s" %
493
               (response_content["code"],
494
                response_content["message"],
495
                response_content["explain"]))
496
      else:
497
        msg = str(response_content)
498

    
499
      raise GanetiApiError(msg, code=http_code)
500

    
501
    return response_content
502

    
503
  def GetVersion(self):
504
    """Gets the Remote API version running on the cluster.
505

506
    @rtype: int
507
    @return: Ganeti Remote API version
508

509
    """
510
    return self._SendRequest(HTTP_GET, "/version", None, None)
511

    
512
  def GetFeatures(self):
513
    """Gets the list of optional features supported by RAPI server.
514

515
    @rtype: list
516
    @return: List of optional features
517

518
    """
519
    try:
520
      return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
521
                               None, None)
522
    except GanetiApiError, err:
523
      # Older RAPI servers don't support this resource
524
      if err.code == HTTP_NOT_FOUND:
525
        return []
526

    
527
      raise
528

    
529
  def GetOperatingSystems(self):
530
    """Gets the Operating Systems running in the Ganeti cluster.
531

532
    @rtype: list of str
533
    @return: operating systems
534

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

    
539
  def GetInfo(self):
540
    """Gets info about the cluster.
541

542
    @rtype: dict
543
    @return: information about the cluster
544

545
    """
546
    return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
547
                             None, None)
548

    
549
  def RedistributeConfig(self):
550
    """Tells the cluster to redistribute its configuration files.
551

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

555
    """
556
    return self._SendRequest(HTTP_PUT,
557
                             "/%s/redistribute-config" % GANETI_RAPI_VERSION,
558
                             None, None)
559

    
560
  def ModifyCluster(self, **kwargs):
561
    """Modifies cluster parameters.
562

563
    More details for parameters can be found in the RAPI documentation.
564

565
    @rtype: string
566
    @return: job id
567

568
    """
569
    body = kwargs
570

    
571
    return self._SendRequest(HTTP_PUT,
572
                             "/%s/modify" % GANETI_RAPI_VERSION, None, body)
573

    
574
  def GetClusterTags(self):
575
    """Gets the cluster tags.
576

577
    @rtype: list of str
578
    @return: cluster tags
579

580
    """
581
    return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
582
                             None, None)
583

    
584
  def AddClusterTags(self, tags, dry_run=False):
585
    """Adds tags to the cluster.
586

587
    @type tags: list of str
588
    @param tags: tags to add to the cluster
589
    @type dry_run: bool
590
    @param dry_run: whether to perform a dry run
591

592
    @rtype: string
593
    @return: job id
594

595
    """
596
    query = [("tag", t) for t in tags]
597
    _AppendDryRunIf(query, dry_run)
598

    
599
    return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
600
                             query, None)
601

    
602
  def DeleteClusterTags(self, tags, dry_run=False):
603
    """Deletes tags from the cluster.
604

605
    @type tags: list of str
606
    @param tags: tags to delete
607
    @type dry_run: bool
608
    @param dry_run: whether to perform a dry run
609
    @rtype: string
610
    @return: job id
611

612
    """
613
    query = [("tag", t) for t in tags]
614
    _AppendDryRunIf(query, dry_run)
615

    
616
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
617
                             query, None)
618

    
619
  def GetInstances(self, bulk=False):
620
    """Gets information about instances on the cluster.
621

622
    @type bulk: bool
623
    @param bulk: whether to return all information about all instances
624

625
    @rtype: list of dict or list of str
626
    @return: if bulk is True, info about the instances, else a list of instances
627

628
    """
629
    query = []
630
    _AppendIf(query, bulk, ("bulk", 1))
631

    
632
    instances = self._SendRequest(HTTP_GET,
633
                                  "/%s/instances" % GANETI_RAPI_VERSION,
634
                                  query, None)
635
    if bulk:
636
      return instances
637
    else:
638
      return [i["id"] for i in instances]
639

    
640
  def GetInstance(self, instance):
641
    """Gets information about an instance.
642

643
    @type instance: str
644
    @param instance: instance whose info to return
645

646
    @rtype: dict
647
    @return: info about the instance
648

649
    """
650
    return self._SendRequest(HTTP_GET,
651
                             ("/%s/instances/%s" %
652
                              (GANETI_RAPI_VERSION, instance)), None, None)
653

    
654
  def GetInstanceInfo(self, instance, static=None):
655
    """Gets information about an instance.
656

657
    @type instance: string
658
    @param instance: Instance name
659
    @rtype: string
660
    @return: Job ID
661

662
    """
663
    if static is not None:
664
      query = [("static", static)]
665
    else:
666
      query = None
667

    
668
    return self._SendRequest(HTTP_GET,
669
                             ("/%s/instances/%s/info" %
670
                              (GANETI_RAPI_VERSION, instance)), query, None)
671

    
672
  def CreateInstance(self, mode, name, disk_template, disks, nics,
673
                     **kwargs):
674
    """Creates a new instance.
675

676
    More details for parameters can be found in the RAPI documentation.
677

678
    @type mode: string
679
    @param mode: Instance creation mode
680
    @type name: string
681
    @param name: Hostname of the instance to create
682
    @type disk_template: string
683
    @param disk_template: Disk template for instance (e.g. plain, diskless,
684
                          file, or drbd)
685
    @type disks: list of dicts
686
    @param disks: List of disk definitions
687
    @type nics: list of dicts
688
    @param nics: List of NIC definitions
689
    @type dry_run: bool
690
    @keyword dry_run: whether to perform a dry run
691

692
    @rtype: string
693
    @return: job id
694

695
    """
696
    query = []
697

    
698
    _AppendDryRunIf(query, kwargs.get("dry_run"))
699

    
700
    if _INST_CREATE_REQV1 in self.GetFeatures():
701
      # All required fields for request data version 1
702
      body = {
703
        _REQ_DATA_VERSION_FIELD: 1,
704
        "mode": mode,
705
        "name": name,
706
        "disk_template": disk_template,
707
        "disks": disks,
708
        "nics": nics,
709
        }
710

    
711
      conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
712
      if conflicts:
713
        raise GanetiApiError("Required fields can not be specified as"
714
                             " keywords: %s" % ", ".join(conflicts))
715

    
716
      body.update((key, value) for key, value in kwargs.iteritems()
717
                  if key != "dry_run")
718
    else:
719
      raise GanetiApiError("Server does not support new-style (version 1)"
720
                           " instance creation requests")
721

    
722
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
723
                             query, body)
724

    
725
  def DeleteInstance(self, instance, dry_run=False):
726
    """Deletes an instance.
727

728
    @type instance: str
729
    @param instance: the instance to delete
730

731
    @rtype: string
732
    @return: job id
733

734
    """
735
    query = []
736
    _AppendDryRunIf(query, dry_run)
737

    
738
    return self._SendRequest(HTTP_DELETE,
739
                             ("/%s/instances/%s" %
740
                              (GANETI_RAPI_VERSION, instance)), query, None)
741

    
742
  def ModifyInstance(self, instance, **kwargs):
743
    """Modifies an instance.
744

745
    More details for parameters can be found in the RAPI documentation.
746

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

752
    """
753
    body = kwargs
754

    
755
    return self._SendRequest(HTTP_PUT,
756
                             ("/%s/instances/%s/modify" %
757
                              (GANETI_RAPI_VERSION, instance)), None, body)
758

    
759
  def ActivateInstanceDisks(self, instance, ignore_size=None):
760
    """Activates an instance's disks.
761

762
    @type instance: string
763
    @param instance: Instance name
764
    @type ignore_size: bool
765
    @param ignore_size: Whether to ignore recorded size
766
    @rtype: string
767
    @return: job id
768

769
    """
770
    query = []
771
    _AppendIf(query, ignore_size, ("ignore_size", 1))
772

    
773
    return self._SendRequest(HTTP_PUT,
774
                             ("/%s/instances/%s/activate-disks" %
775
                              (GANETI_RAPI_VERSION, instance)), query, None)
776

    
777
  def DeactivateInstanceDisks(self, instance):
778
    """Deactivates an instance's disks.
779

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

785
    """
786
    return self._SendRequest(HTTP_PUT,
787
                             ("/%s/instances/%s/deactivate-disks" %
788
                              (GANETI_RAPI_VERSION, instance)), None, None)
789

    
790
  def RecreateInstanceDisks(self, instance, disks=None, nodes=None):
791
    """Recreate an instance's disks.
792

793
    @type instance: string
794
    @param instance: Instance name
795
    @type disks: list of int
796
    @param disks: List of disk indexes
797
    @type nodes: list of string
798
    @param nodes: New instance nodes, if relocation is desired
799
    @rtype: string
800
    @return: job id
801

802
    """
803
    body = {}
804
    _SetItemIf(body, disks is not None, "disks", disks)
805
    _SetItemIf(body, nodes is not None, "nodes", nodes)
806

    
807
    return self._SendRequest(HTTP_POST,
808
                             ("/%s/instances/%s/recreate-disks" %
809
                              (GANETI_RAPI_VERSION, instance)), None, body)
810

    
811
  def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
812
    """Grows a disk of an instance.
813

814
    More details for parameters can be found in the RAPI documentation.
815

816
    @type instance: string
817
    @param instance: Instance name
818
    @type disk: integer
819
    @param disk: Disk index
820
    @type amount: integer
821
    @param amount: Grow disk by this amount (MiB)
822
    @type wait_for_sync: bool
823
    @param wait_for_sync: Wait for disk to synchronize
824
    @rtype: string
825
    @return: job id
826

827
    """
828
    body = {
829
      "amount": amount,
830
      }
831

    
832
    _SetItemIf(body, wait_for_sync is not None, "wait_for_sync", wait_for_sync)
833

    
834
    return self._SendRequest(HTTP_POST,
835
                             ("/%s/instances/%s/disk/%s/grow" %
836
                              (GANETI_RAPI_VERSION, instance, disk)),
837
                             None, body)
838

    
839
  def GetInstanceTags(self, instance):
840
    """Gets tags for an instance.
841

842
    @type instance: str
843
    @param instance: instance whose tags to return
844

845
    @rtype: list of str
846
    @return: tags for the instance
847

848
    """
849
    return self._SendRequest(HTTP_GET,
850
                             ("/%s/instances/%s/tags" %
851
                              (GANETI_RAPI_VERSION, instance)), None, None)
852

    
853
  def AddInstanceTags(self, instance, tags, dry_run=False):
854
    """Adds tags to an instance.
855

856
    @type instance: str
857
    @param instance: instance to add tags to
858
    @type tags: list of str
859
    @param tags: tags to add to the instance
860
    @type dry_run: bool
861
    @param dry_run: whether to perform a dry run
862

863
    @rtype: string
864
    @return: job id
865

866
    """
867
    query = [("tag", t) for t in tags]
868
    _AppendDryRunIf(query, dry_run)
869

    
870
    return self._SendRequest(HTTP_PUT,
871
                             ("/%s/instances/%s/tags" %
872
                              (GANETI_RAPI_VERSION, instance)), query, None)
873

    
874
  def DeleteInstanceTags(self, instance, tags, dry_run=False):
875
    """Deletes tags from an instance.
876

877
    @type instance: str
878
    @param instance: instance to delete tags from
879
    @type tags: list of str
880
    @param tags: tags to delete
881
    @type dry_run: bool
882
    @param dry_run: whether to perform a dry run
883
    @rtype: string
884
    @return: job id
885

886
    """
887
    query = [("tag", t) for t in tags]
888
    _AppendDryRunIf(query, dry_run)
889

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

    
894
  def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
895
                     dry_run=False):
896
    """Reboots an instance.
897

898
    @type instance: str
899
    @param instance: instance to rebot
900
    @type reboot_type: str
901
    @param reboot_type: one of: hard, soft, full
902
    @type ignore_secondaries: bool
903
    @param ignore_secondaries: if True, ignores errors for the secondary node
904
        while re-assembling disks (in hard-reboot mode only)
905
    @type dry_run: bool
906
    @param dry_run: whether to perform a dry run
907
    @rtype: string
908
    @return: job id
909

910
    """
911
    query = []
912
    _AppendDryRunIf(query, dry_run)
913
    _AppendIf(query, reboot_type, ("type", reboot_type))
914
    _AppendIf(query, ignore_secondaries is not None,
915
              ("ignore_secondaries", ignore_secondaries))
916

    
917
    return self._SendRequest(HTTP_POST,
918
                             ("/%s/instances/%s/reboot" %
919
                              (GANETI_RAPI_VERSION, instance)), query, None)
920

    
921
  def ShutdownInstance(self, instance, dry_run=False, no_remember=False):
922
    """Shuts down an instance.
923

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

933
    """
934
    query = []
935
    _AppendDryRunIf(query, dry_run)
936
    _AppendIf(query, no_remember, ("no-remember", 1))
937

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

    
942
  def StartupInstance(self, instance, dry_run=False, no_remember=False):
943
    """Starts up an instance.
944

945
    @type instance: str
946
    @param instance: the instance to start up
947
    @type dry_run: bool
948
    @param dry_run: whether to perform a dry run
949
    @type no_remember: bool
950
    @param no_remember: if true, will not record the state change
951
    @rtype: string
952
    @return: job id
953

954
    """
955
    query = []
956
    _AppendDryRunIf(query, dry_run)
957
    _AppendIf(query, no_remember, ("no-remember", 1))
958

    
959
    return self._SendRequest(HTTP_PUT,
960
                             ("/%s/instances/%s/startup" %
961
                              (GANETI_RAPI_VERSION, instance)), query, None)
962

    
963
  def ReinstallInstance(self, instance, os=None, no_startup=False,
964
                        osparams=None):
965
    """Reinstalls an instance.
966

967
    @type instance: str
968
    @param instance: The instance to reinstall
969
    @type os: str or None
970
    @param os: The operating system to reinstall. If None, the instance's
971
        current operating system will be installed again
972
    @type no_startup: bool
973
    @param no_startup: Whether to start the instance automatically
974
    @rtype: string
975
    @return: job id
976

977
    """
978
    if _INST_REINSTALL_REQV1 in self.GetFeatures():
979
      body = {
980
        "start": not no_startup,
981
        }
982
      _SetItemIf(body, os is not None, "os", os)
983
      _SetItemIf(body, osparams is not None, "osparams", osparams)
984
      return self._SendRequest(HTTP_POST,
985
                               ("/%s/instances/%s/reinstall" %
986
                                (GANETI_RAPI_VERSION, instance)), None, body)
987

    
988
    # Use old request format
989
    if osparams:
990
      raise GanetiApiError("Server does not support specifying OS parameters"
991
                           " for instance reinstallation")
992

    
993
    query = []
994
    _AppendIf(query, os, ("os", os))
995
    _AppendIf(query, no_startup, ("nostartup", 1))
996

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

    
1001
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
1002
                           remote_node=None, iallocator=None):
1003
    """Replaces disks on an instance.
1004

1005
    @type instance: str
1006
    @param instance: instance whose disks to replace
1007
    @type disks: list of ints
1008
    @param disks: Indexes of disks to replace
1009
    @type mode: str
1010
    @param mode: replacement mode to use (defaults to replace_auto)
1011
    @type remote_node: str or None
1012
    @param remote_node: new secondary node to use (for use with
1013
        replace_new_secondary mode)
1014
    @type iallocator: str or None
1015
    @param iallocator: instance allocator plugin to use (for use with
1016
                       replace_auto mode)
1017

1018
    @rtype: string
1019
    @return: job id
1020

1021
    """
1022
    query = [
1023
      ("mode", mode),
1024
      ]
1025

    
1026
    # TODO: Convert to body parameters
1027

    
1028
    if disks is not None:
1029
      _AppendIf(query, True,
1030
                ("disks", ",".join(str(idx) for idx in disks)))
1031

    
1032
    _AppendIf(query, remote_node is not None, ("remote_node", remote_node))
1033
    _AppendIf(query, iallocator is not None, ("iallocator", iallocator))
1034

    
1035
    return self._SendRequest(HTTP_POST,
1036
                             ("/%s/instances/%s/replace-disks" %
1037
                              (GANETI_RAPI_VERSION, instance)), query, None)
1038

    
1039
  def PrepareExport(self, instance, mode):
1040
    """Prepares an instance for an export.
1041

1042
    @type instance: string
1043
    @param instance: Instance name
1044
    @type mode: string
1045
    @param mode: Export mode
1046
    @rtype: string
1047
    @return: Job ID
1048

1049
    """
1050
    query = [("mode", mode)]
1051
    return self._SendRequest(HTTP_PUT,
1052
                             ("/%s/instances/%s/prepare-export" %
1053
                              (GANETI_RAPI_VERSION, instance)), query, None)
1054

    
1055
  def ExportInstance(self, instance, mode, destination, shutdown=None,
1056
                     remove_instance=None,
1057
                     x509_key_name=None, destination_x509_ca=None):
1058
    """Exports an instance.
1059

1060
    @type instance: string
1061
    @param instance: Instance name
1062
    @type mode: string
1063
    @param mode: Export mode
1064
    @rtype: string
1065
    @return: Job ID
1066

1067
    """
1068
    body = {
1069
      "destination": destination,
1070
      "mode": mode,
1071
      }
1072

    
1073
    _SetItemIf(body, shutdown is not None, "shutdown", shutdown)
1074
    _SetItemIf(body, remove_instance is not None,
1075
               "remove_instance", remove_instance)
1076
    _SetItemIf(body, x509_key_name is not None, "x509_key_name", x509_key_name)
1077
    _SetItemIf(body, destination_x509_ca is not None,
1078
               "destination_x509_ca", destination_x509_ca)
1079

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

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

1087
    @type instance: string
1088
    @param instance: Instance name
1089
    @type mode: string
1090
    @param mode: Migration mode
1091
    @type cleanup: bool
1092
    @param cleanup: Whether to clean up a previously failed migration
1093
    @rtype: string
1094
    @return: job id
1095

1096
    """
1097
    body = {}
1098
    _SetItemIf(body, mode is not None, "mode", mode)
1099
    _SetItemIf(body, cleanup is not None, "cleanup", cleanup)
1100

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

    
1105
  def FailoverInstance(self, instance, iallocator=None,
1106
                       ignore_consistency=None, target_node=None):
1107
    """Does a failover of an instance.
1108

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

1121
    """
1122
    body = {}
1123
    _SetItemIf(body, iallocator is not None, "iallocator", iallocator)
1124
    _SetItemIf(body, ignore_consistency is not None,
1125
               "ignore_consistency", ignore_consistency)
1126
    _SetItemIf(body, target_node is not None, "target_node", target_node)
1127

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

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

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

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

    
1151
    _SetItemIf(body, ip_check is not None, "ip_check", ip_check)
1152
    _SetItemIf(body, name_check is not None, "name_check", name_check)
1153

    
1154
    return self._SendRequest(HTTP_PUT,
1155
                             ("/%s/instances/%s/rename" %
1156
                              (GANETI_RAPI_VERSION, instance)), None, body)
1157

    
1158
  def GetInstanceConsole(self, instance):
1159
    """Request information for connecting to instance's console.
1160

1161
    @type instance: string
1162
    @param instance: Instance name
1163
    @rtype: dict
1164
    @return: dictionary containing information about instance's console
1165

1166
    """
1167
    return self._SendRequest(HTTP_GET,
1168
                             ("/%s/instances/%s/console" %
1169
                              (GANETI_RAPI_VERSION, instance)), None, None)
1170

    
1171
  def GetJobs(self):
1172
    """Gets all jobs for the cluster.
1173

1174
    @rtype: list of int
1175
    @return: job ids for the cluster
1176

1177
    """
1178
    return [int(j["id"])
1179
            for j in self._SendRequest(HTTP_GET,
1180
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1181
                                       None, None)]
1182

    
1183
  def GetJobStatus(self, job_id):
1184
    """Gets the status of a job.
1185

1186
    @type job_id: string
1187
    @param job_id: job id whose status to query
1188

1189
    @rtype: dict
1190
    @return: job status
1191

1192
    """
1193
    return self._SendRequest(HTTP_GET,
1194
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1195
                             None, None)
1196

    
1197
  def WaitForJobCompletion(self, job_id, period=5, retries=-1):
1198
    """Polls cluster for job status until completion.
1199

1200
    Completion is defined as any of the following states listed in
1201
    L{JOB_STATUS_FINALIZED}.
1202

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

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

1217
    """
1218
    while retries != 0:
1219
      job_result = self.GetJobStatus(job_id)
1220

    
1221
      if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
1222
        return True
1223
      elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
1224
        return False
1225

    
1226
      if period:
1227
        time.sleep(period)
1228

    
1229
      if retries > 0:
1230
        retries -= 1
1231

    
1232
    return False
1233

    
1234
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1235
    """Waits for job changes.
1236

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

1243
    """
1244
    body = {
1245
      "fields": fields,
1246
      "previous_job_info": prev_job_info,
1247
      "previous_log_serial": prev_log_serial,
1248
      }
1249

    
1250
    return self._SendRequest(HTTP_GET,
1251
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1252
                             None, body)
1253

    
1254
  def CancelJob(self, job_id, dry_run=False):
1255
    """Cancels a job.
1256

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

1264
    """
1265
    query = []
1266
    _AppendDryRunIf(query, dry_run)
1267

    
1268
    return self._SendRequest(HTTP_DELETE,
1269
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1270
                             query, None)
1271

    
1272
  def GetNodes(self, bulk=False):
1273
    """Gets all nodes in the cluster.
1274

1275
    @type bulk: bool
1276
    @param bulk: whether to return all information about all instances
1277

1278
    @rtype: list of dict or str
1279
    @return: if bulk is true, info about nodes in the cluster,
1280
        else list of nodes in the cluster
1281

1282
    """
1283
    query = []
1284
    _AppendIf(query, bulk, ("bulk", 1))
1285

    
1286
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1287
                              query, None)
1288
    if bulk:
1289
      return nodes
1290
    else:
1291
      return [n["id"] for n in nodes]
1292

    
1293
  def GetNode(self, node):
1294
    """Gets information about a node.
1295

1296
    @type node: str
1297
    @param node: node whose info to return
1298

1299
    @rtype: dict
1300
    @return: info about the node
1301

1302
    """
1303
    return self._SendRequest(HTTP_GET,
1304
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1305
                             None, None)
1306

    
1307
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1308
                   dry_run=False, early_release=None,
1309
                   mode=None, accept_old=False):
1310
    """Evacuates instances from a Ganeti node.
1311

1312
    @type node: str
1313
    @param node: node to evacuate
1314
    @type iallocator: str or None
1315
    @param iallocator: instance allocator to use
1316
    @type remote_node: str
1317
    @param remote_node: node to evaucate to
1318
    @type dry_run: bool
1319
    @param dry_run: whether to perform a dry run
1320
    @type early_release: bool
1321
    @param early_release: whether to enable parallelization
1322
    @type mode: string
1323
    @param mode: Node evacuation mode
1324
    @type accept_old: bool
1325
    @param accept_old: Whether caller is ready to accept old-style (pre-2.5)
1326
        results
1327

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

1334
    @raises GanetiApiError: if an iallocator and remote_node are both
1335
        specified
1336

1337
    """
1338
    if iallocator and remote_node:
1339
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1340

    
1341
    query = []
1342
    _AppendDryRunIf(query, dry_run)
1343

    
1344
    if _NODE_EVAC_RES1 in self.GetFeatures():
1345
      # Server supports body parameters
1346
      body = {}
1347

    
1348
      _SetItemIf(body, iallocator is not None, "iallocator", iallocator)
1349
      _SetItemIf(body, remote_node is not None, "remote_node", remote_node)
1350
      _SetItemIf(body, early_release is not None,
1351
                 "early_release", early_release)
1352
      _SetItemIf(body, mode is not None, "mode", mode)
1353
    else:
1354
      # Pre-2.5 request format
1355
      body = None
1356

    
1357
      if not accept_old:
1358
        raise GanetiApiError("Server is version 2.4 or earlier and caller does"
1359
                             " not accept old-style results (parameter"
1360
                             " accept_old)")
1361

    
1362
      # Pre-2.5 servers can only evacuate secondaries
1363
      if mode is not None and mode != NODE_EVAC_SEC:
1364
        raise GanetiApiError("Server can only evacuate secondary instances")
1365

    
1366
      _AppendIf(query, iallocator, ("iallocator", iallocator))
1367
      _AppendIf(query, remote_node, ("remote_node", remote_node))
1368
      _AppendIf(query, early_release, ("early_release", 1))
1369

    
1370
    return self._SendRequest(HTTP_POST,
1371
                             ("/%s/nodes/%s/evacuate" %
1372
                              (GANETI_RAPI_VERSION, node)), query, body)
1373

    
1374
  def MigrateNode(self, node, mode=None, dry_run=False, iallocator=None,
1375
                  target_node=None):
1376
    """Migrates all primary instances from a node.
1377

1378
    @type node: str
1379
    @param node: node to migrate
1380
    @type mode: string
1381
    @param mode: if passed, it will overwrite the live migration type,
1382
        otherwise the hypervisor default will be used
1383
    @type dry_run: bool
1384
    @param dry_run: whether to perform a dry run
1385
    @type iallocator: string
1386
    @param iallocator: instance allocator to use
1387
    @type target_node: string
1388
    @param target_node: Target node for shared-storage instances
1389

1390
    @rtype: string
1391
    @return: job id
1392

1393
    """
1394
    query = []
1395
    _AppendDryRunIf(query, dry_run)
1396

    
1397
    if _NODE_MIGRATE_REQV1 in self.GetFeatures():
1398
      body = {}
1399

    
1400
      _SetItemIf(body, mode is not None, "mode", mode)
1401
      _SetItemIf(body, iallocator is not None, "iallocator", iallocator)
1402
      _SetItemIf(body, target_node is not None, "target_node", target_node)
1403

    
1404
      assert len(query) <= 1
1405

    
1406
      return self._SendRequest(HTTP_POST,
1407
                               ("/%s/nodes/%s/migrate" %
1408
                                (GANETI_RAPI_VERSION, node)), query, body)
1409
    else:
1410
      # Use old request format
1411
      if target_node is not None:
1412
        raise GanetiApiError("Server does not support specifying target node"
1413
                             " for node migration")
1414

    
1415
      _AppendIf(query, mode is not None, ("mode", mode))
1416

    
1417
      return self._SendRequest(HTTP_POST,
1418
                               ("/%s/nodes/%s/migrate" %
1419
                                (GANETI_RAPI_VERSION, node)), query, None)
1420

    
1421
  def GetNodeRole(self, node):
1422
    """Gets the current role for a node.
1423

1424
    @type node: str
1425
    @param node: node whose role to return
1426

1427
    @rtype: str
1428
    @return: the current role for a node
1429

1430
    """
1431
    return self._SendRequest(HTTP_GET,
1432
                             ("/%s/nodes/%s/role" %
1433
                              (GANETI_RAPI_VERSION, node)), None, None)
1434

    
1435
  def SetNodeRole(self, node, role, force=False, auto_promote=None):
1436
    """Sets the role for a node.
1437

1438
    @type node: str
1439
    @param node: the node whose role to set
1440
    @type role: str
1441
    @param role: the role to set for the node
1442
    @type force: bool
1443
    @param force: whether to force the role change
1444
    @type auto_promote: bool
1445
    @param auto_promote: Whether node(s) should be promoted to master candidate
1446
                         if necessary
1447

1448
    @rtype: string
1449
    @return: job id
1450

1451
    """
1452
    query = []
1453
    _AppendForceIf(query, force)
1454
    _AppendIf(query, auto_promote is not None, ("auto-promote", auto_promote))
1455

    
1456
    return self._SendRequest(HTTP_PUT,
1457
                             ("/%s/nodes/%s/role" %
1458
                              (GANETI_RAPI_VERSION, node)), query, role)
1459

    
1460
  def PowercycleNode(self, node, force=False):
1461
    """Powercycles a node.
1462

1463
    @type node: string
1464
    @param node: Node name
1465
    @type force: bool
1466
    @param force: Whether to force the operation
1467
    @rtype: string
1468
    @return: job id
1469

1470
    """
1471
    query = []
1472
    _AppendForceIf(query, force)
1473

    
1474
    return self._SendRequest(HTTP_POST,
1475
                             ("/%s/nodes/%s/powercycle" %
1476
                              (GANETI_RAPI_VERSION, node)), query, None)
1477

    
1478
  def ModifyNode(self, node, **kwargs):
1479
    """Modifies a node.
1480

1481
    More details for parameters can be found in the RAPI documentation.
1482

1483
    @type node: string
1484
    @param node: Node name
1485
    @rtype: string
1486
    @return: job id
1487

1488
    """
1489
    return self._SendRequest(HTTP_POST,
1490
                             ("/%s/nodes/%s/modify" %
1491
                              (GANETI_RAPI_VERSION, node)), None, kwargs)
1492

    
1493
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1494
    """Gets the storage units for a node.
1495

1496
    @type node: str
1497
    @param node: the node whose storage units to return
1498
    @type storage_type: str
1499
    @param storage_type: storage type whose units to return
1500
    @type output_fields: str
1501
    @param output_fields: storage type fields to return
1502

1503
    @rtype: string
1504
    @return: job id where results can be retrieved
1505

1506
    """
1507
    query = [
1508
      ("storage_type", storage_type),
1509
      ("output_fields", output_fields),
1510
      ]
1511

    
1512
    return self._SendRequest(HTTP_GET,
1513
                             ("/%s/nodes/%s/storage" %
1514
                              (GANETI_RAPI_VERSION, node)), query, None)
1515

    
1516
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1517
    """Modifies parameters of storage units on the node.
1518

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

1529
    @rtype: string
1530
    @return: job id
1531

1532
    """
1533
    query = [
1534
      ("storage_type", storage_type),
1535
      ("name", name),
1536
      ]
1537

    
1538
    _AppendIf(query, allocatable is not None, ("allocatable", allocatable))
1539

    
1540
    return self._SendRequest(HTTP_PUT,
1541
                             ("/%s/nodes/%s/storage/modify" %
1542
                              (GANETI_RAPI_VERSION, node)), query, None)
1543

    
1544
  def RepairNodeStorageUnits(self, node, storage_type, name):
1545
    """Repairs a storage unit on the node.
1546

1547
    @type node: str
1548
    @param node: node whose storage units to repair
1549
    @type storage_type: str
1550
    @param storage_type: storage type to repair
1551
    @type name: str
1552
    @param name: name of the storage unit to repair
1553

1554
    @rtype: string
1555
    @return: job id
1556

1557
    """
1558
    query = [
1559
      ("storage_type", storage_type),
1560
      ("name", name),
1561
      ]
1562

    
1563
    return self._SendRequest(HTTP_PUT,
1564
                             ("/%s/nodes/%s/storage/repair" %
1565
                              (GANETI_RAPI_VERSION, node)), query, None)
1566

    
1567
  def GetNodeTags(self, node):
1568
    """Gets the tags for a node.
1569

1570
    @type node: str
1571
    @param node: node whose tags to return
1572

1573
    @rtype: list of str
1574
    @return: tags for the node
1575

1576
    """
1577
    return self._SendRequest(HTTP_GET,
1578
                             ("/%s/nodes/%s/tags" %
1579
                              (GANETI_RAPI_VERSION, node)), None, None)
1580

    
1581
  def AddNodeTags(self, node, tags, dry_run=False):
1582
    """Adds tags to a node.
1583

1584
    @type node: str
1585
    @param node: node to add tags to
1586
    @type tags: list of str
1587
    @param tags: tags to add to the node
1588
    @type dry_run: bool
1589
    @param dry_run: whether to perform a dry run
1590

1591
    @rtype: string
1592
    @return: job id
1593

1594
    """
1595
    query = [("tag", t) for t in tags]
1596
    _AppendDryRunIf(query, dry_run)
1597

    
1598
    return self._SendRequest(HTTP_PUT,
1599
                             ("/%s/nodes/%s/tags" %
1600
                              (GANETI_RAPI_VERSION, node)), query, tags)
1601

    
1602
  def DeleteNodeTags(self, node, tags, dry_run=False):
1603
    """Delete tags from a node.
1604

1605
    @type node: str
1606
    @param node: node to remove tags from
1607
    @type tags: list of str
1608
    @param tags: tags to remove from the node
1609
    @type dry_run: bool
1610
    @param dry_run: whether to perform a dry run
1611

1612
    @rtype: string
1613
    @return: job id
1614

1615
    """
1616
    query = [("tag", t) for t in tags]
1617
    _AppendDryRunIf(query, dry_run)
1618

    
1619
    return self._SendRequest(HTTP_DELETE,
1620
                             ("/%s/nodes/%s/tags" %
1621
                              (GANETI_RAPI_VERSION, node)), query, None)
1622

    
1623
  def GetGroups(self, bulk=False):
1624
    """Gets all node groups in the cluster.
1625

1626
    @type bulk: bool
1627
    @param bulk: whether to return all information about the groups
1628

1629
    @rtype: list of dict or str
1630
    @return: if bulk is true, a list of dictionaries with info about all node
1631
        groups in the cluster, else a list of names of those node groups
1632

1633
    """
1634
    query = []
1635
    _AppendIf(query, bulk, ("bulk", 1))
1636

    
1637
    groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1638
                               query, None)
1639
    if bulk:
1640
      return groups
1641
    else:
1642
      return [g["name"] for g in groups]
1643

    
1644
  def GetGroup(self, group):
1645
    """Gets information about a node group.
1646

1647
    @type group: str
1648
    @param group: name of the node group whose info to return
1649

1650
    @rtype: dict
1651
    @return: info about the node group
1652

1653
    """
1654
    return self._SendRequest(HTTP_GET,
1655
                             "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
1656
                             None, None)
1657

    
1658
  def CreateGroup(self, name, alloc_policy=None, dry_run=False):
1659
    """Creates a new node group.
1660

1661
    @type name: str
1662
    @param name: the name of node group to create
1663
    @type alloc_policy: str
1664
    @param alloc_policy: the desired allocation policy for the group, if any
1665
    @type dry_run: bool
1666
    @param dry_run: whether to peform a dry run
1667

1668
    @rtype: string
1669
    @return: job id
1670

1671
    """
1672
    query = []
1673
    _AppendDryRunIf(query, dry_run)
1674

    
1675
    body = {
1676
      "name": name,
1677
      "alloc_policy": alloc_policy
1678
      }
1679

    
1680
    return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1681
                             query, body)
1682

    
1683
  def ModifyGroup(self, group, **kwargs):
1684
    """Modifies a node group.
1685

1686
    More details for parameters can be found in the RAPI documentation.
1687

1688
    @type group: string
1689
    @param group: Node group name
1690
    @rtype: string
1691
    @return: job id
1692

1693
    """
1694
    return self._SendRequest(HTTP_PUT,
1695
                             ("/%s/groups/%s/modify" %
1696
                              (GANETI_RAPI_VERSION, group)), None, kwargs)
1697

    
1698
  def DeleteGroup(self, group, dry_run=False):
1699
    """Deletes a node group.
1700

1701
    @type group: str
1702
    @param group: the node group to delete
1703
    @type dry_run: bool
1704
    @param dry_run: whether to peform a dry run
1705

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

1709
    """
1710
    query = []
1711
    _AppendDryRunIf(query, dry_run)
1712

    
1713
    return self._SendRequest(HTTP_DELETE,
1714
                             ("/%s/groups/%s" %
1715
                              (GANETI_RAPI_VERSION, group)), query, None)
1716

    
1717
  def RenameGroup(self, group, new_name):
1718
    """Changes the name of a node group.
1719

1720
    @type group: string
1721
    @param group: Node group name
1722
    @type new_name: string
1723
    @param new_name: New node group name
1724

1725
    @rtype: string
1726
    @return: job id
1727

1728
    """
1729
    body = {
1730
      "new_name": new_name,
1731
      }
1732

    
1733
    return self._SendRequest(HTTP_PUT,
1734
                             ("/%s/groups/%s/rename" %
1735
                              (GANETI_RAPI_VERSION, group)), None, body)
1736

    
1737
  def AssignGroupNodes(self, group, nodes, force=False, dry_run=False):
1738
    """Assigns nodes to a group.
1739

1740
    @type group: string
1741
    @param group: Node gropu name
1742
    @type nodes: list of strings
1743
    @param nodes: List of nodes to assign to the group
1744

1745
    @rtype: string
1746
    @return: job id
1747

1748
    """
1749
    query = []
1750
    _AppendForceIf(query, force)
1751
    _AppendDryRunIf(query, dry_run)
1752

    
1753
    body = {
1754
      "nodes": nodes,
1755
      }
1756

    
1757
    return self._SendRequest(HTTP_PUT,
1758
                             ("/%s/groups/%s/assign-nodes" %
1759
                             (GANETI_RAPI_VERSION, group)), query, body)
1760

    
1761
  def GetGroupTags(self, group):
1762
    """Gets tags for a node group.
1763

1764
    @type group: string
1765
    @param group: Node group whose tags to return
1766

1767
    @rtype: list of strings
1768
    @return: tags for the group
1769

1770
    """
1771
    return self._SendRequest(HTTP_GET,
1772
                             ("/%s/groups/%s/tags" %
1773
                              (GANETI_RAPI_VERSION, group)), None, None)
1774

    
1775
  def AddGroupTags(self, group, tags, dry_run=False):
1776
    """Adds tags to a node group.
1777

1778
    @type group: str
1779
    @param group: group to add tags to
1780
    @type tags: list of string
1781
    @param tags: tags to add to the group
1782
    @type dry_run: bool
1783
    @param dry_run: whether to perform a dry run
1784

1785
    @rtype: string
1786
    @return: job id
1787

1788
    """
1789
    query = [("tag", t) for t in tags]
1790
    _AppendDryRunIf(query, dry_run)
1791

    
1792
    return self._SendRequest(HTTP_PUT,
1793
                             ("/%s/groups/%s/tags" %
1794
                              (GANETI_RAPI_VERSION, group)), query, None)
1795

    
1796
  def DeleteGroupTags(self, group, tags, dry_run=False):
1797
    """Deletes tags from a node group.
1798

1799
    @type group: str
1800
    @param group: group to delete tags from
1801
    @type tags: list of string
1802
    @param tags: tags to delete
1803
    @type dry_run: bool
1804
    @param dry_run: whether to perform a dry run
1805
    @rtype: string
1806
    @return: job id
1807

1808
    """
1809
    query = [("tag", t) for t in tags]
1810
    _AppendDryRunIf(query, dry_run)
1811

    
1812
    return self._SendRequest(HTTP_DELETE,
1813
                             ("/%s/groups/%s/tags" %
1814
                              (GANETI_RAPI_VERSION, group)), query, None)
1815

    
1816
  def Query(self, what, fields, qfilter=None):
1817
    """Retrieves information about resources.
1818

1819
    @type what: string
1820
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1821
    @type fields: list of string
1822
    @param fields: Requested fields
1823
    @type qfilter: None or list
1824
    @param qfilter: Query filter
1825

1826
    @rtype: string
1827
    @return: job id
1828

1829
    """
1830
    body = {
1831
      "fields": fields,
1832
      }
1833

    
1834
    _SetItemIf(body, qfilter is not None, "qfilter", qfilter)
1835
    # TODO: remove "filter" after 2.7
1836
    _SetItemIf(body, qfilter is not None, "filter", qfilter)
1837

    
1838
    return self._SendRequest(HTTP_PUT,
1839
                             ("/%s/query/%s" %
1840
                              (GANETI_RAPI_VERSION, what)), None, body)
1841

    
1842
  def QueryFields(self, what, fields=None):
1843
    """Retrieves available fields for a resource.
1844

1845
    @type what: string
1846
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1847
    @type fields: list of string
1848
    @param fields: Requested fields
1849

1850
    @rtype: string
1851
    @return: job id
1852

1853
    """
1854
    query = []
1855

    
1856
    if fields is not None:
1857
      _AppendIf(query, True, ("fields", ",".join(fields)))
1858

    
1859
    return self._SendRequest(HTTP_GET,
1860
                             ("/%s/query/%s/fields" %
1861
                              (GANETI_RAPI_VERSION, what)), query, None)