Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ d654aae1

History | View | Annotate | Download (38.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2010 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 urllib
39
import threading
40
import pycurl
41

    
42
try:
43
  from cStringIO import StringIO
44
except ImportError:
45
  from StringIO import StringIO
46

    
47

    
48
GANETI_RAPI_PORT = 5080
49
GANETI_RAPI_VERSION = 2
50

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

    
59
REPLACE_DISK_PRI = "replace_on_primary"
60
REPLACE_DISK_SECONDARY = "replace_on_secondary"
61
REPLACE_DISK_CHG = "replace_new_secondary"
62
REPLACE_DISK_AUTO = "replace_auto"
63

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

    
70
# Internal constants
71
_REQ_DATA_VERSION_FIELD = "__version__"
72
_INST_CREATE_REQV1 = "instance-create-reqv1"
73
_INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link", "bridge"])
74
_INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
75
_INST_CREATE_V0_PARAMS = frozenset([
76
  "os", "pnode", "snode", "iallocator", "start", "ip_check", "name_check",
77
  "hypervisor", "file_storage_dir", "file_driver", "dry_run",
78
  ])
79
_INST_CREATE_V0_DPARAMS = frozenset(["beparams", "hvparams"])
80

    
81
# Older pycURL versions don't have all error constants
82
try:
83
  _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
84
  _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
85
except AttributeError:
86
  _CURLE_SSL_CACERT = 60
87
  _CURLE_SSL_CACERT_BADFILE = 77
88

    
89
_CURL_SSL_CERT_ERRORS = frozenset([
90
  _CURLE_SSL_CACERT,
91
  _CURLE_SSL_CACERT_BADFILE,
92
  ])
93

    
94

    
95
class Error(Exception):
96
  """Base error class for this module.
97

98
  """
99
  pass
100

    
101

    
102
class CertificateError(Error):
103
  """Raised when a problem is found with the SSL certificate.
104

105
  """
106
  pass
107

    
108

    
109
class GanetiApiError(Error):
110
  """Generic error raised from Ganeti API.
111

112
  """
113
  def __init__(self, msg, code=None):
114
    Error.__init__(self, msg)
115
    self.code = code
116

    
117

    
118
def UsesRapiClient(fn):
119
  """Decorator for code using RAPI client to initialize pycURL.
120

121
  """
122
  def wrapper(*args, **kwargs):
123
    # curl_global_init(3) and curl_global_cleanup(3) must be called with only
124
    # one thread running. This check is just a safety measure -- it doesn't
125
    # cover all cases.
126
    assert threading.activeCount() == 1, \
127
           "Found active threads when initializing pycURL"
128

    
129
    pycurl.global_init(pycurl.GLOBAL_ALL)
130
    try:
131
      return fn(*args, **kwargs)
132
    finally:
133
      pycurl.global_cleanup()
134

    
135
  return wrapper
136

    
137

    
138
def GenericCurlConfig(verbose=False, use_signal=False,
139
                      use_curl_cabundle=False, cafile=None, capath=None,
140
                      proxy=None, verify_hostname=False,
141
                      connect_timeout=None, timeout=None,
142
                      _pycurl_version_fn=pycurl.version_info):
143
  """Curl configuration function generator.
144

145
  @type verbose: bool
146
  @param verbose: Whether to set cURL to verbose mode
147
  @type use_signal: bool
148
  @param use_signal: Whether to allow cURL to use signals
149
  @type use_curl_cabundle: bool
150
  @param use_curl_cabundle: Whether to use cURL's default CA bundle
151
  @type cafile: string
152
  @param cafile: In which file we can find the certificates
153
  @type capath: string
154
  @param capath: In which directory we can find the certificates
155
  @type proxy: string
156
  @param proxy: Proxy to use, None for default behaviour and empty string for
157
                disabling proxies (see curl_easy_setopt(3))
158
  @type verify_hostname: bool
159
  @param verify_hostname: Whether to verify the remote peer certificate's
160
                          commonName
161
  @type connect_timeout: number
162
  @param connect_timeout: Timeout for establishing connection in seconds
163
  @type timeout: number
164
  @param timeout: Timeout for complete transfer in seconds (see
165
                  curl_easy_setopt(3)).
166

167
  """
168
  if use_curl_cabundle and (cafile or capath):
169
    raise Error("Can not use default CA bundle when CA file or path is set")
170

    
171
  def _ConfigCurl(curl, logger):
172
    """Configures a cURL object
173

174
    @type curl: pycurl.Curl
175
    @param curl: cURL object
176

177
    """
178
    logger.debug("Using cURL version %s", pycurl.version)
179

    
180
    # pycurl.version_info returns a tuple with information about the used
181
    # version of libcurl. Item 5 is the SSL library linked to it.
182
    # e.g.: (3, '7.18.0', 463360, 'x86_64-pc-linux-gnu', 1581, 'GnuTLS/2.0.4',
183
    # 0, '1.2.3.3', ...)
184
    sslver = _pycurl_version_fn()[5]
185
    if not sslver:
186
      raise Error("No SSL support in cURL")
187

    
188
    lcsslver = sslver.lower()
189
    if lcsslver.startswith("openssl/"):
190
      pass
191
    elif lcsslver.startswith("gnutls/"):
192
      if capath:
193
        raise Error("cURL linked against GnuTLS has no support for a"
194
                    " CA path (%s)" % (pycurl.version, ))
195
    else:
196
      raise NotImplementedError("cURL uses unsupported SSL version '%s'" %
197
                                sslver)
198

    
199
    curl.setopt(pycurl.VERBOSE, verbose)
200
    curl.setopt(pycurl.NOSIGNAL, not use_signal)
201

    
202
    # Whether to verify remote peer's CN
203
    if verify_hostname:
204
      # curl_easy_setopt(3): "When CURLOPT_SSL_VERIFYHOST is 2, that
205
      # certificate must indicate that the server is the server to which you
206
      # meant to connect, or the connection fails. [...] When the value is 1,
207
      # the certificate must contain a Common Name field, but it doesn't matter
208
      # what name it says. [...]"
209
      curl.setopt(pycurl.SSL_VERIFYHOST, 2)
210
    else:
211
      curl.setopt(pycurl.SSL_VERIFYHOST, 0)
212

    
213
    if cafile or capath or use_curl_cabundle:
214
      # Require certificates to be checked
215
      curl.setopt(pycurl.SSL_VERIFYPEER, True)
216
      if cafile:
217
        curl.setopt(pycurl.CAINFO, str(cafile))
218
      if capath:
219
        curl.setopt(pycurl.CAPATH, str(capath))
220
      # Not changing anything for using default CA bundle
221
    else:
222
      # Disable SSL certificate verification
223
      curl.setopt(pycurl.SSL_VERIFYPEER, False)
224

    
225
    if proxy is not None:
226
      curl.setopt(pycurl.PROXY, str(proxy))
227

    
228
    # Timeouts
229
    if connect_timeout is not None:
230
      curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
231
    if timeout is not None:
232
      curl.setopt(pycurl.TIMEOUT, timeout)
233

    
234
  return _ConfigCurl
235

    
236

    
237
class GanetiRapiClient(object):
238
  """Ganeti RAPI client.
239

240
  """
241
  USER_AGENT = "Ganeti RAPI Client"
242
  _json_encoder = simplejson.JSONEncoder(sort_keys=True)
243

    
244
  def __init__(self, host, port=GANETI_RAPI_PORT,
245
               username=None, password=None, logger=logging,
246
               curl_config_fn=None, curl_factory=None):
247
    """Initializes this class.
248

249
    @type host: string
250
    @param host: the ganeti cluster master to interact with
251
    @type port: int
252
    @param port: the port on which the RAPI is running (default is 5080)
253
    @type username: string
254
    @param username: the username to connect with
255
    @type password: string
256
    @param password: the password to connect with
257
    @type curl_config_fn: callable
258
    @param curl_config_fn: Function to configure C{pycurl.Curl} object
259
    @param logger: Logging object
260

261
    """
262
    self._username = username
263
    self._password = password
264
    self._logger = logger
265
    self._curl_config_fn = curl_config_fn
266
    self._curl_factory = curl_factory
267

    
268
    self._base_url = "https://%s:%s" % (host, port)
269

    
270
    if username is not None:
271
      if password is None:
272
        raise Error("Password not specified")
273
    elif password:
274
      raise Error("Specified password without username")
275

    
276
  def _CreateCurl(self):
277
    """Creates a cURL object.
278

279
    """
280
    # Create pycURL object if no factory is provided
281
    if self._curl_factory:
282
      curl = self._curl_factory()
283
    else:
284
      curl = pycurl.Curl()
285

    
286
    # Default cURL settings
287
    curl.setopt(pycurl.VERBOSE, False)
288
    curl.setopt(pycurl.FOLLOWLOCATION, False)
289
    curl.setopt(pycurl.MAXREDIRS, 5)
290
    curl.setopt(pycurl.NOSIGNAL, True)
291
    curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
292
    curl.setopt(pycurl.SSL_VERIFYHOST, 0)
293
    curl.setopt(pycurl.SSL_VERIFYPEER, False)
294
    curl.setopt(pycurl.HTTPHEADER, [
295
      "Accept: %s" % HTTP_APP_JSON,
296
      "Content-type: %s" % HTTP_APP_JSON,
297
      ])
298

    
299
    assert ((self._username is None and self._password is None) ^
300
            (self._username is not None and self._password is not None))
301

    
302
    if self._username:
303
      # Setup authentication
304
      curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
305
      curl.setopt(pycurl.USERPWD,
306
                  str("%s:%s" % (self._username, self._password)))
307

    
308
    # Call external configuration function
309
    if self._curl_config_fn:
310
      self._curl_config_fn(curl, self._logger)
311

    
312
    return curl
313

    
314
  @staticmethod
315
  def _EncodeQuery(query):
316
    """Encode query values for RAPI URL.
317

318
    @type query: list of two-tuples
319
    @param query: Query arguments
320
    @rtype: list
321
    @return: Query list with encoded values
322

323
    """
324
    result = []
325

    
326
    for name, value in query:
327
      if value is None:
328
        result.append((name, ""))
329

    
330
      elif isinstance(value, bool):
331
        # Boolean values must be encoded as 0 or 1
332
        result.append((name, int(value)))
333

    
334
      elif isinstance(value, (list, tuple, dict)):
335
        raise ValueError("Invalid query data type %r" % type(value).__name__)
336

    
337
      else:
338
        result.append((name, value))
339

    
340
    return result
341

    
342
  def _SendRequest(self, method, path, query, content):
343
    """Sends an HTTP request.
344

345
    This constructs a full URL, encodes and decodes HTTP bodies, and
346
    handles invalid responses in a pythonic way.
347

348
    @type method: string
349
    @param method: HTTP method to use
350
    @type path: string
351
    @param path: HTTP URL path
352
    @type query: list of two-tuples
353
    @param query: query arguments to pass to urllib.urlencode
354
    @type content: str or None
355
    @param content: HTTP body content
356

357
    @rtype: str
358
    @return: JSON-Decoded response
359

360
    @raises CertificateError: If an invalid SSL certificate is found
361
    @raises GanetiApiError: If an invalid response is returned
362

363
    """
364
    assert path.startswith("/")
365

    
366
    curl = self._CreateCurl()
367

    
368
    if content is not None:
369
      encoded_content = self._json_encoder.encode(content)
370
    else:
371
      encoded_content = ""
372

    
373
    # Build URL
374
    urlparts = [self._base_url, path]
375
    if query:
376
      urlparts.append("?")
377
      urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
378

    
379
    url = "".join(urlparts)
380

    
381
    self._logger.debug("Sending request %s %s (content=%r)",
382
                       method, url, encoded_content)
383

    
384
    # Buffer for response
385
    encoded_resp_body = StringIO()
386

    
387
    # Configure cURL
388
    curl.setopt(pycurl.CUSTOMREQUEST, str(method))
389
    curl.setopt(pycurl.URL, str(url))
390
    curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
391
    curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
392

    
393
    try:
394
      # Send request and wait for response
395
      try:
396
        curl.perform()
397
      except pycurl.error, err:
398
        if err.args[0] in _CURL_SSL_CERT_ERRORS:
399
          raise CertificateError("SSL certificate error %s" % err)
400

    
401
        raise GanetiApiError(str(err))
402
    finally:
403
      # Reset settings to not keep references to large objects in memory
404
      # between requests
405
      curl.setopt(pycurl.POSTFIELDS, "")
406
      curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)
407

    
408
    # Get HTTP response code
409
    http_code = curl.getinfo(pycurl.RESPONSE_CODE)
410

    
411
    # Was anything written to the response buffer?
412
    if encoded_resp_body.tell():
413
      response_content = simplejson.loads(encoded_resp_body.getvalue())
414
    else:
415
      response_content = None
416

    
417
    if http_code != HTTP_OK:
418
      if isinstance(response_content, dict):
419
        msg = ("%s %s: %s" %
420
               (response_content["code"],
421
                response_content["message"],
422
                response_content["explain"]))
423
      else:
424
        msg = str(response_content)
425

    
426
      raise GanetiApiError(msg, code=http_code)
427

    
428
    return response_content
429

    
430
  def GetVersion(self):
431
    """Gets the Remote API version running on the cluster.
432

433
    @rtype: int
434
    @return: Ganeti Remote API version
435

436
    """
437
    return self._SendRequest(HTTP_GET, "/version", None, None)
438

    
439
  def GetFeatures(self):
440
    """Gets the list of optional features supported by RAPI server.
441

442
    @rtype: list
443
    @return: List of optional features
444

445
    """
446
    try:
447
      return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
448
                               None, None)
449
    except GanetiApiError, err:
450
      # Older RAPI servers don't support this resource
451
      if err.code == HTTP_NOT_FOUND:
452
        return []
453

    
454
      raise
455

    
456
  def GetOperatingSystems(self):
457
    """Gets the Operating Systems running in the Ganeti cluster.
458

459
    @rtype: list of str
460
    @return: operating systems
461

462
    """
463
    return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
464
                             None, None)
465

    
466
  def GetInfo(self):
467
    """Gets info about the cluster.
468

469
    @rtype: dict
470
    @return: information about the cluster
471

472
    """
473
    return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
474
                             None, None)
475

    
476
  def GetClusterTags(self):
477
    """Gets the cluster tags.
478

479
    @rtype: list of str
480
    @return: cluster tags
481

482
    """
483
    return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
484
                             None, None)
485

    
486
  def AddClusterTags(self, tags, dry_run=False):
487
    """Adds tags to the cluster.
488

489
    @type tags: list of str
490
    @param tags: tags to add to the cluster
491
    @type dry_run: bool
492
    @param dry_run: whether to perform a dry run
493

494
    @rtype: int
495
    @return: job id
496

497
    """
498
    query = [("tag", t) for t in tags]
499
    if dry_run:
500
      query.append(("dry-run", 1))
501

    
502
    return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
503
                             query, None)
504

    
505
  def DeleteClusterTags(self, tags, dry_run=False):
506
    """Deletes tags from the cluster.
507

508
    @type tags: list of str
509
    @param tags: tags to delete
510
    @type dry_run: bool
511
    @param dry_run: whether to perform a dry run
512

513
    """
514
    query = [("tag", t) for t in tags]
515
    if dry_run:
516
      query.append(("dry-run", 1))
517

    
518
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
519
                             query, None)
520

    
521
  def GetInstances(self, bulk=False):
522
    """Gets information about instances on the cluster.
523

524
    @type bulk: bool
525
    @param bulk: whether to return all information about all instances
526

527
    @rtype: list of dict or list of str
528
    @return: if bulk is True, info about the instances, else a list of instances
529

530
    """
531
    query = []
532
    if bulk:
533
      query.append(("bulk", 1))
534

    
535
    instances = self._SendRequest(HTTP_GET,
536
                                  "/%s/instances" % GANETI_RAPI_VERSION,
537
                                  query, None)
538
    if bulk:
539
      return instances
540
    else:
541
      return [i["id"] for i in instances]
542

    
543
  def GetInstance(self, instance):
544
    """Gets information about an instance.
545

546
    @type instance: str
547
    @param instance: instance whose info to return
548

549
    @rtype: dict
550
    @return: info about the instance
551

552
    """
553
    return self._SendRequest(HTTP_GET,
554
                             ("/%s/instances/%s" %
555
                              (GANETI_RAPI_VERSION, instance)), None, None)
556

    
557
  def GetInstanceInfo(self, instance, static=None):
558
    """Gets information about an instance.
559

560
    @type instance: string
561
    @param instance: Instance name
562
    @rtype: string
563
    @return: Job ID
564

565
    """
566
    if static is not None:
567
      query = [("static", static)]
568
    else:
569
      query = None
570

    
571
    return self._SendRequest(HTTP_GET,
572
                             ("/%s/instances/%s/info" %
573
                              (GANETI_RAPI_VERSION, instance)), query, None)
574

    
575
  def CreateInstance(self, mode, name, disk_template, disks, nics,
576
                     **kwargs):
577
    """Creates a new instance.
578

579
    More details for parameters can be found in the RAPI documentation.
580

581
    @type mode: string
582
    @param mode: Instance creation mode
583
    @type name: string
584
    @param name: Hostname of the instance to create
585
    @type disk_template: string
586
    @param disk_template: Disk template for instance (e.g. plain, diskless,
587
                          file, or drbd)
588
    @type disks: list of dicts
589
    @param disks: List of disk definitions
590
    @type nics: list of dicts
591
    @param nics: List of NIC definitions
592
    @type dry_run: bool
593
    @keyword dry_run: whether to perform a dry run
594

595
    @rtype: int
596
    @return: job id
597

598
    """
599
    query = []
600

    
601
    if kwargs.get("dry_run"):
602
      query.append(("dry-run", 1))
603

    
604
    if _INST_CREATE_REQV1 in self.GetFeatures():
605
      # All required fields for request data version 1
606
      body = {
607
        _REQ_DATA_VERSION_FIELD: 1,
608
        "mode": mode,
609
        "name": name,
610
        "disk_template": disk_template,
611
        "disks": disks,
612
        "nics": nics,
613
        }
614

    
615
      conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
616
      if conflicts:
617
        raise GanetiApiError("Required fields can not be specified as"
618
                             " keywords: %s" % ", ".join(conflicts))
619

    
620
      body.update((key, value) for key, value in kwargs.iteritems()
621
                  if key != "dry_run")
622
    else:
623
      # Old request format (version 0)
624

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

    
631
      # Validate disks
632
      for idx, disk in enumerate(disks):
633
        unsupported = set(disk.keys()) - _INST_CREATE_V0_DISK_PARAMS
634
        if unsupported:
635
          raise GanetiApiError("Server supports request version 0 only, but"
636
                               " disk %s specifies the unsupported parameters"
637
                               " %s, allowed are %s" %
638
                               (idx, unsupported,
639
                                list(_INST_CREATE_V0_DISK_PARAMS)))
640

    
641
      assert (len(_INST_CREATE_V0_DISK_PARAMS) == 1 and
642
              "size" in _INST_CREATE_V0_DISK_PARAMS)
643
      disk_sizes = [disk["size"] for disk in disks]
644

    
645
      # Validate NICs
646
      if not nics:
647
        raise GanetiApiError("Server supports request version 0 only, but"
648
                             " no NIC specified")
649
      elif len(nics) > 1:
650
        raise GanetiApiError("Server supports request version 0 only, but"
651
                             " more than one NIC specified")
652

    
653
      assert len(nics) == 1
654

    
655
      unsupported = set(nics[0].keys()) - _INST_NIC_PARAMS
656
      if unsupported:
657
        raise GanetiApiError("Server supports request version 0 only, but"
658
                             " NIC 0 specifies the unsupported parameters %s,"
659
                             " allowed are %s" %
660
                             (unsupported, list(_INST_NIC_PARAMS)))
661

    
662
      # Validate other parameters
663
      unsupported = (set(kwargs.keys()) - _INST_CREATE_V0_PARAMS -
664
                     _INST_CREATE_V0_DPARAMS)
665
      if unsupported:
666
        allowed = _INST_CREATE_V0_PARAMS.union(_INST_CREATE_V0_DPARAMS)
667
        raise GanetiApiError("Server supports request version 0 only, but"
668
                             " the following unsupported parameters are"
669
                             " specified: %s, allowed are %s" %
670
                             (unsupported, list(allowed)))
671

    
672
      # All required fields for request data version 0
673
      body = {
674
        _REQ_DATA_VERSION_FIELD: 0,
675
        "name": name,
676
        "disk_template": disk_template,
677
        "disks": disk_sizes,
678
        }
679

    
680
      # NIC fields
681
      assert len(nics) == 1
682
      assert not (set(body.keys()) & set(nics[0].keys()))
683
      body.update(nics[0])
684

    
685
      # Copy supported fields
686
      assert not (set(body.keys()) & set(kwargs.keys()))
687
      body.update(dict((key, value) for key, value in kwargs.items()
688
                       if key in _INST_CREATE_V0_PARAMS))
689

    
690
      # Merge dictionaries
691
      for i in (value for key, value in kwargs.items()
692
                if key in _INST_CREATE_V0_DPARAMS):
693
        assert not (set(body.keys()) & set(i.keys()))
694
        body.update(i)
695

    
696
      assert not (set(kwargs.keys()) -
697
                  (_INST_CREATE_V0_PARAMS | _INST_CREATE_V0_DPARAMS))
698
      assert not (set(body.keys()) & _INST_CREATE_V0_DPARAMS)
699

    
700
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
701
                             query, body)
702

    
703
  def DeleteInstance(self, instance, dry_run=False):
704
    """Deletes an instance.
705

706
    @type instance: str
707
    @param instance: the instance to delete
708

709
    @rtype: int
710
    @return: job id
711

712
    """
713
    query = []
714
    if dry_run:
715
      query.append(("dry-run", 1))
716

    
717
    return self._SendRequest(HTTP_DELETE,
718
                             ("/%s/instances/%s" %
719
                              (GANETI_RAPI_VERSION, instance)), query, None)
720

    
721
  def GetInstanceTags(self, instance):
722
    """Gets tags for an instance.
723

724
    @type instance: str
725
    @param instance: instance whose tags to return
726

727
    @rtype: list of str
728
    @return: tags for the instance
729

730
    """
731
    return self._SendRequest(HTTP_GET,
732
                             ("/%s/instances/%s/tags" %
733
                              (GANETI_RAPI_VERSION, instance)), None, None)
734

    
735
  def AddInstanceTags(self, instance, tags, dry_run=False):
736
    """Adds tags to an instance.
737

738
    @type instance: str
739
    @param instance: instance to add tags to
740
    @type tags: list of str
741
    @param tags: tags to add to the instance
742
    @type dry_run: bool
743
    @param dry_run: whether to perform a dry run
744

745
    @rtype: int
746
    @return: job id
747

748
    """
749
    query = [("tag", t) for t in tags]
750
    if dry_run:
751
      query.append(("dry-run", 1))
752

    
753
    return self._SendRequest(HTTP_PUT,
754
                             ("/%s/instances/%s/tags" %
755
                              (GANETI_RAPI_VERSION, instance)), query, None)
756

    
757
  def DeleteInstanceTags(self, instance, tags, dry_run=False):
758
    """Deletes tags from an instance.
759

760
    @type instance: str
761
    @param instance: instance to delete tags from
762
    @type tags: list of str
763
    @param tags: tags to delete
764
    @type dry_run: bool
765
    @param dry_run: whether to perform a dry run
766

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

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

    
776
  def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
777
                     dry_run=False):
778
    """Reboots an instance.
779

780
    @type instance: str
781
    @param instance: instance to rebot
782
    @type reboot_type: str
783
    @param reboot_type: one of: hard, soft, full
784
    @type ignore_secondaries: bool
785
    @param ignore_secondaries: if True, ignores errors for the secondary node
786
        while re-assembling disks (in hard-reboot mode only)
787
    @type dry_run: bool
788
    @param dry_run: whether to perform a dry run
789

790
    """
791
    query = []
792
    if reboot_type:
793
      query.append(("type", reboot_type))
794
    if ignore_secondaries is not None:
795
      query.append(("ignore_secondaries", ignore_secondaries))
796
    if dry_run:
797
      query.append(("dry-run", 1))
798

    
799
    return self._SendRequest(HTTP_POST,
800
                             ("/%s/instances/%s/reboot" %
801
                              (GANETI_RAPI_VERSION, instance)), query, None)
802

    
803
  def ShutdownInstance(self, instance, dry_run=False):
804
    """Shuts down an instance.
805

806
    @type instance: str
807
    @param instance: the instance to shut down
808
    @type dry_run: bool
809
    @param dry_run: whether to perform a dry run
810

811
    """
812
    query = []
813
    if dry_run:
814
      query.append(("dry-run", 1))
815

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

    
820
  def StartupInstance(self, instance, dry_run=False):
821
    """Starts up an instance.
822

823
    @type instance: str
824
    @param instance: the instance to start up
825
    @type dry_run: bool
826
    @param dry_run: whether to perform a dry run
827

828
    """
829
    query = []
830
    if dry_run:
831
      query.append(("dry-run", 1))
832

    
833
    return self._SendRequest(HTTP_PUT,
834
                             ("/%s/instances/%s/startup" %
835
                              (GANETI_RAPI_VERSION, instance)), query, None)
836

    
837
  def ReinstallInstance(self, instance, os=None, no_startup=False):
838
    """Reinstalls an instance.
839

840
    @type instance: str
841
    @param instance: The instance to reinstall
842
    @type os: str or None
843
    @param os: The operating system to reinstall. If None, the instance's
844
        current operating system will be installed again
845
    @type no_startup: bool
846
    @param no_startup: Whether to start the instance automatically
847

848
    """
849
    query = []
850
    if os:
851
      query.append(("os", os))
852
    if no_startup:
853
      query.append(("nostartup", 1))
854
    return self._SendRequest(HTTP_POST,
855
                             ("/%s/instances/%s/reinstall" %
856
                              (GANETI_RAPI_VERSION, instance)), query, None)
857

    
858
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
859
                           remote_node=None, iallocator=None, dry_run=False):
860
    """Replaces disks on an instance.
861

862
    @type instance: str
863
    @param instance: instance whose disks to replace
864
    @type disks: list of ints
865
    @param disks: Indexes of disks to replace
866
    @type mode: str
867
    @param mode: replacement mode to use (defaults to replace_auto)
868
    @type remote_node: str or None
869
    @param remote_node: new secondary node to use (for use with
870
        replace_new_secondary mode)
871
    @type iallocator: str or None
872
    @param iallocator: instance allocator plugin to use (for use with
873
                       replace_auto mode)
874
    @type dry_run: bool
875
    @param dry_run: whether to perform a dry run
876

877
    @rtype: int
878
    @return: job id
879

880
    """
881
    query = [
882
      ("mode", mode),
883
      ]
884

    
885
    if disks:
886
      query.append(("disks", ",".join(str(idx) for idx in disks)))
887

    
888
    if remote_node:
889
      query.append(("remote_node", remote_node))
890

    
891
    if iallocator:
892
      query.append(("iallocator", iallocator))
893

    
894
    if dry_run:
895
      query.append(("dry-run", 1))
896

    
897
    return self._SendRequest(HTTP_POST,
898
                             ("/%s/instances/%s/replace-disks" %
899
                              (GANETI_RAPI_VERSION, instance)), query, None)
900

    
901
  def PrepareExport(self, instance, mode):
902
    """Prepares an instance for an export.
903

904
    @type instance: string
905
    @param instance: Instance name
906
    @type mode: string
907
    @param mode: Export mode
908
    @rtype: string
909
    @return: Job ID
910

911
    """
912
    query = [("mode", mode)]
913
    return self._SendRequest(HTTP_PUT,
914
                             ("/%s/instances/%s/prepare-export" %
915
                              (GANETI_RAPI_VERSION, instance)), query, None)
916

    
917
  def ExportInstance(self, instance, mode, destination, shutdown=None,
918
                     remove_instance=None,
919
                     x509_key_name=None, destination_x509_ca=None):
920
    """Exports an instance.
921

922
    @type instance: string
923
    @param instance: Instance name
924
    @type mode: string
925
    @param mode: Export mode
926
    @rtype: string
927
    @return: Job ID
928

929
    """
930
    body = {
931
      "destination": destination,
932
      "mode": mode,
933
      }
934

    
935
    if shutdown is not None:
936
      body["shutdown"] = shutdown
937

    
938
    if remove_instance is not None:
939
      body["remove_instance"] = remove_instance
940

    
941
    if x509_key_name is not None:
942
      body["x509_key_name"] = x509_key_name
943

    
944
    if destination_x509_ca is not None:
945
      body["destination_x509_ca"] = destination_x509_ca
946

    
947
    return self._SendRequest(HTTP_PUT,
948
                             ("/%s/instances/%s/export" %
949
                              (GANETI_RAPI_VERSION, instance)), None, body)
950

    
951
  def MigrateInstance(self, instance, mode=None, cleanup=None):
952
    """Starts up an instance.
953

954
    @type instance: string
955
    @param instance: Instance name
956
    @type mode: string
957
    @param mode: Migration mode
958
    @type cleanup: bool
959
    @param cleanup: Whether to clean up a previously failed migration
960

961
    """
962
    body = {}
963

    
964
    if mode is not None:
965
      body["mode"] = mode
966

    
967
    if cleanup is not None:
968
      body["cleanup"] = cleanup
969

    
970
    return self._SendRequest(HTTP_PUT,
971
                             ("/%s/instances/%s/migrate" %
972
                              (GANETI_RAPI_VERSION, instance)), None, body)
973

    
974
  def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
975
    """Changes the name of an instance.
976

977
    @type instance: string
978
    @param instance: Instance name
979
    @type new_name: string
980
    @param new_name: New instance name
981
    @type ip_check: bool
982
    @param ip_check: Whether to ensure instance's IP address is inactive
983
    @type name_check: bool
984
    @param name_check: Whether to ensure instance's name is resolvable
985

986
    """
987
    body = {
988
      "new_name": new_name,
989
      }
990

    
991
    if ip_check is not None:
992
      body["ip_check"] = ip_check
993

    
994
    if name_check is not None:
995
      body["name_check"] = name_check
996

    
997
    return self._SendRequest(HTTP_PUT,
998
                             ("/%s/instances/%s/rename" %
999
                              (GANETI_RAPI_VERSION, instance)), None, body)
1000

    
1001
  def GetJobs(self):
1002
    """Gets all jobs for the cluster.
1003

1004
    @rtype: list of int
1005
    @return: job ids for the cluster
1006

1007
    """
1008
    return [int(j["id"])
1009
            for j in self._SendRequest(HTTP_GET,
1010
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1011
                                       None, None)]
1012

    
1013
  def GetJobStatus(self, job_id):
1014
    """Gets the status of a job.
1015

1016
    @type job_id: int
1017
    @param job_id: job id whose status to query
1018

1019
    @rtype: dict
1020
    @return: job status
1021

1022
    """
1023
    return self._SendRequest(HTTP_GET,
1024
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1025
                             None, None)
1026

    
1027
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1028
    """Waits for job changes.
1029

1030
    @type job_id: int
1031
    @param job_id: Job ID for which to wait
1032

1033
    """
1034
    body = {
1035
      "fields": fields,
1036
      "previous_job_info": prev_job_info,
1037
      "previous_log_serial": prev_log_serial,
1038
      }
1039

    
1040
    return self._SendRequest(HTTP_GET,
1041
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1042
                             None, body)
1043

    
1044
  def CancelJob(self, job_id, dry_run=False):
1045
    """Cancels a job.
1046

1047
    @type job_id: int
1048
    @param job_id: id of the job to delete
1049
    @type dry_run: bool
1050
    @param dry_run: whether to perform a dry run
1051

1052
    """
1053
    query = []
1054
    if dry_run:
1055
      query.append(("dry-run", 1))
1056

    
1057
    return self._SendRequest(HTTP_DELETE,
1058
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1059
                             query, None)
1060

    
1061
  def GetNodes(self, bulk=False):
1062
    """Gets all nodes in the cluster.
1063

1064
    @type bulk: bool
1065
    @param bulk: whether to return all information about all instances
1066

1067
    @rtype: list of dict or str
1068
    @return: if bulk is true, info about nodes in the cluster,
1069
        else list of nodes in the cluster
1070

1071
    """
1072
    query = []
1073
    if bulk:
1074
      query.append(("bulk", 1))
1075

    
1076
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1077
                              query, None)
1078
    if bulk:
1079
      return nodes
1080
    else:
1081
      return [n["id"] for n in nodes]
1082

    
1083
  def GetNode(self, node):
1084
    """Gets information about a node.
1085

1086
    @type node: str
1087
    @param node: node whose info to return
1088

1089
    @rtype: dict
1090
    @return: info about the node
1091

1092
    """
1093
    return self._SendRequest(HTTP_GET,
1094
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1095
                             None, None)
1096

    
1097
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1098
                   dry_run=False, early_release=False):
1099
    """Evacuates instances from a Ganeti node.
1100

1101
    @type node: str
1102
    @param node: node to evacuate
1103
    @type iallocator: str or None
1104
    @param iallocator: instance allocator to use
1105
    @type remote_node: str
1106
    @param remote_node: node to evaucate to
1107
    @type dry_run: bool
1108
    @param dry_run: whether to perform a dry run
1109
    @type early_release: bool
1110
    @param early_release: whether to enable parallelization
1111

1112
    @rtype: list
1113
    @return: list of (job ID, instance name, new secondary node); if
1114
        dry_run was specified, then the actual move jobs were not
1115
        submitted and the job IDs will be C{None}
1116

1117
    @raises GanetiApiError: if an iallocator and remote_node are both
1118
        specified
1119

1120
    """
1121
    if iallocator and remote_node:
1122
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1123

    
1124
    query = []
1125
    if iallocator:
1126
      query.append(("iallocator", iallocator))
1127
    if remote_node:
1128
      query.append(("remote_node", remote_node))
1129
    if dry_run:
1130
      query.append(("dry-run", 1))
1131
    if early_release:
1132
      query.append(("early_release", 1))
1133

    
1134
    return self._SendRequest(HTTP_POST,
1135
                             ("/%s/nodes/%s/evacuate" %
1136
                              (GANETI_RAPI_VERSION, node)), query, None)
1137

    
1138
  def MigrateNode(self, node, mode=None, dry_run=False):
1139
    """Migrates all primary instances from a node.
1140

1141
    @type node: str
1142
    @param node: node to migrate
1143
    @type mode: string
1144
    @param mode: if passed, it will overwrite the live migration type,
1145
        otherwise the hypervisor default will be used
1146
    @type dry_run: bool
1147
    @param dry_run: whether to perform a dry run
1148

1149
    @rtype: int
1150
    @return: job id
1151

1152
    """
1153
    query = []
1154
    if mode is not None:
1155
      query.append(("mode", mode))
1156
    if dry_run:
1157
      query.append(("dry-run", 1))
1158

    
1159
    return self._SendRequest(HTTP_POST,
1160
                             ("/%s/nodes/%s/migrate" %
1161
                              (GANETI_RAPI_VERSION, node)), query, None)
1162

    
1163
  def GetNodeRole(self, node):
1164
    """Gets the current role for a node.
1165

1166
    @type node: str
1167
    @param node: node whose role to return
1168

1169
    @rtype: str
1170
    @return: the current role for a node
1171

1172
    """
1173
    return self._SendRequest(HTTP_GET,
1174
                             ("/%s/nodes/%s/role" %
1175
                              (GANETI_RAPI_VERSION, node)), None, None)
1176

    
1177
  def SetNodeRole(self, node, role, force=False):
1178
    """Sets the role for a node.
1179

1180
    @type node: str
1181
    @param node: the node whose role to set
1182
    @type role: str
1183
    @param role: the role to set for the node
1184
    @type force: bool
1185
    @param force: whether to force the role change
1186

1187
    @rtype: int
1188
    @return: job id
1189

1190
    """
1191
    query = [
1192
      ("force", force),
1193
      ]
1194

    
1195
    return self._SendRequest(HTTP_PUT,
1196
                             ("/%s/nodes/%s/role" %
1197
                              (GANETI_RAPI_VERSION, node)), query, role)
1198

    
1199
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1200
    """Gets the storage units for a node.
1201

1202
    @type node: str
1203
    @param node: the node whose storage units to return
1204
    @type storage_type: str
1205
    @param storage_type: storage type whose units to return
1206
    @type output_fields: str
1207
    @param output_fields: storage type fields to return
1208

1209
    @rtype: int
1210
    @return: job id where results can be retrieved
1211

1212
    """
1213
    query = [
1214
      ("storage_type", storage_type),
1215
      ("output_fields", output_fields),
1216
      ]
1217

    
1218
    return self._SendRequest(HTTP_GET,
1219
                             ("/%s/nodes/%s/storage" %
1220
                              (GANETI_RAPI_VERSION, node)), query, None)
1221

    
1222
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1223
    """Modifies parameters of storage units on the node.
1224

1225
    @type node: str
1226
    @param node: node whose storage units to modify
1227
    @type storage_type: str
1228
    @param storage_type: storage type whose units to modify
1229
    @type name: str
1230
    @param name: name of the storage unit
1231
    @type allocatable: bool or None
1232
    @param allocatable: Whether to set the "allocatable" flag on the storage
1233
                        unit (None=no modification, True=set, False=unset)
1234

1235
    @rtype: int
1236
    @return: job id
1237

1238
    """
1239
    query = [
1240
      ("storage_type", storage_type),
1241
      ("name", name),
1242
      ]
1243

    
1244
    if allocatable is not None:
1245
      query.append(("allocatable", allocatable))
1246

    
1247
    return self._SendRequest(HTTP_PUT,
1248
                             ("/%s/nodes/%s/storage/modify" %
1249
                              (GANETI_RAPI_VERSION, node)), query, None)
1250

    
1251
  def RepairNodeStorageUnits(self, node, storage_type, name):
1252
    """Repairs a storage unit on the node.
1253

1254
    @type node: str
1255
    @param node: node whose storage units to repair
1256
    @type storage_type: str
1257
    @param storage_type: storage type to repair
1258
    @type name: str
1259
    @param name: name of the storage unit to repair
1260

1261
    @rtype: int
1262
    @return: job id
1263

1264
    """
1265
    query = [
1266
      ("storage_type", storage_type),
1267
      ("name", name),
1268
      ]
1269

    
1270
    return self._SendRequest(HTTP_PUT,
1271
                             ("/%s/nodes/%s/storage/repair" %
1272
                              (GANETI_RAPI_VERSION, node)), query, None)
1273

    
1274
  def GetNodeTags(self, node):
1275
    """Gets the tags for a node.
1276

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

1280
    @rtype: list of str
1281
    @return: tags for the node
1282

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

    
1288
  def AddNodeTags(self, node, tags, dry_run=False):
1289
    """Adds tags to a node.
1290

1291
    @type node: str
1292
    @param node: node to add tags to
1293
    @type tags: list of str
1294
    @param tags: tags to add to the node
1295
    @type dry_run: bool
1296
    @param dry_run: whether to perform a dry run
1297

1298
    @rtype: int
1299
    @return: job id
1300

1301
    """
1302
    query = [("tag", t) for t in tags]
1303
    if dry_run:
1304
      query.append(("dry-run", 1))
1305

    
1306
    return self._SendRequest(HTTP_PUT,
1307
                             ("/%s/nodes/%s/tags" %
1308
                              (GANETI_RAPI_VERSION, node)), query, tags)
1309

    
1310
  def DeleteNodeTags(self, node, tags, dry_run=False):
1311
    """Delete tags from a node.
1312

1313
    @type node: str
1314
    @param node: node to remove tags from
1315
    @type tags: list of str
1316
    @param tags: tags to remove from the node
1317
    @type dry_run: bool
1318
    @param dry_run: whether to perform a dry run
1319

1320
    @rtype: int
1321
    @return: job id
1322

1323
    """
1324
    query = [("tag", t) for t in tags]
1325
    if dry_run:
1326
      query.append(("dry-run", 1))
1327

    
1328
    return self._SendRequest(HTTP_DELETE,
1329
                             ("/%s/nodes/%s/tags" %
1330
                              (GANETI_RAPI_VERSION, node)), query, None)