Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ fcee9675

History | View | Annotate | Download (37.7 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=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._host = host
263
    self._port = port
264
    self._logger = logger
265

    
266
    self._base_url = "https://%s:%s" % (host, port)
267

    
268
    # Create pycURL object if not supplied
269
    if not curl:
270
      curl = pycurl.Curl()
271

    
272
    # Default cURL settings
273
    curl.setopt(pycurl.VERBOSE, False)
274
    curl.setopt(pycurl.FOLLOWLOCATION, False)
275
    curl.setopt(pycurl.MAXREDIRS, 5)
276
    curl.setopt(pycurl.NOSIGNAL, True)
277
    curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
278
    curl.setopt(pycurl.SSL_VERIFYHOST, 0)
279
    curl.setopt(pycurl.SSL_VERIFYPEER, False)
280
    curl.setopt(pycurl.HTTPHEADER, [
281
      "Accept: %s" % HTTP_APP_JSON,
282
      "Content-type: %s" % HTTP_APP_JSON,
283
      ])
284

    
285
    # Setup authentication
286
    if username is not None:
287
      if password is None:
288
        raise Error("Password not specified")
289
      curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
290
      curl.setopt(pycurl.USERPWD, str("%s:%s" % (username, password)))
291
    elif password:
292
      raise Error("Specified password without username")
293

    
294
    # Call external configuration function
295
    if curl_config_fn:
296
      curl_config_fn(curl, logger)
297

    
298
    self._curl = curl
299

    
300
  @staticmethod
301
  def _EncodeQuery(query):
302
    """Encode query values for RAPI URL.
303

304
    @type query: list of two-tuples
305
    @param query: Query arguments
306
    @rtype: list
307
    @return: Query list with encoded values
308

309
    """
310
    result = []
311

    
312
    for name, value in query:
313
      if value is None:
314
        result.append((name, ""))
315

    
316
      elif isinstance(value, bool):
317
        # Boolean values must be encoded as 0 or 1
318
        result.append((name, int(value)))
319

    
320
      elif isinstance(value, (list, tuple, dict)):
321
        raise ValueError("Invalid query data type %r" % type(value).__name__)
322

    
323
      else:
324
        result.append((name, value))
325

    
326
    return result
327

    
328
  def _SendRequest(self, method, path, query, content):
329
    """Sends an HTTP request.
330

331
    This constructs a full URL, encodes and decodes HTTP bodies, and
332
    handles invalid responses in a pythonic way.
333

334
    @type method: string
335
    @param method: HTTP method to use
336
    @type path: string
337
    @param path: HTTP URL path
338
    @type query: list of two-tuples
339
    @param query: query arguments to pass to urllib.urlencode
340
    @type content: str or None
341
    @param content: HTTP body content
342

343
    @rtype: str
344
    @return: JSON-Decoded response
345

346
    @raises CertificateError: If an invalid SSL certificate is found
347
    @raises GanetiApiError: If an invalid response is returned
348

349
    """
350
    assert path.startswith("/")
351

    
352
    curl = self._curl
353

    
354
    if content is not None:
355
      encoded_content = self._json_encoder.encode(content)
356
    else:
357
      encoded_content = ""
358

    
359
    # Build URL
360
    urlparts = [self._base_url, path]
361
    if query:
362
      urlparts.append("?")
363
      urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
364

    
365
    url = "".join(urlparts)
366

    
367
    self._logger.debug("Sending request %s %s to %s:%s (content=%r)",
368
                       method, url, self._host, self._port, encoded_content)
369

    
370
    # Buffer for response
371
    encoded_resp_body = StringIO()
372

    
373
    # Configure cURL
374
    curl.setopt(pycurl.CUSTOMREQUEST, str(method))
375
    curl.setopt(pycurl.URL, str(url))
376
    curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
377
    curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
378

    
379
    try:
380
      # Send request and wait for response
381
      try:
382
        curl.perform()
383
      except pycurl.error, err:
384
        if err.args[0] in _CURL_SSL_CERT_ERRORS:
385
          raise CertificateError("SSL certificate error %s" % err)
386

    
387
        raise GanetiApiError(str(err))
388
    finally:
389
      # Reset settings to not keep references to large objects in memory
390
      # between requests
391
      curl.setopt(pycurl.POSTFIELDS, "")
392
      curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)
393

    
394
    # Get HTTP response code
395
    http_code = curl.getinfo(pycurl.RESPONSE_CODE)
396

    
397
    # Was anything written to the response buffer?
398
    if encoded_resp_body.tell():
399
      response_content = simplejson.loads(encoded_resp_body.getvalue())
400
    else:
401
      response_content = None
402

    
403
    if http_code != HTTP_OK:
404
      if isinstance(response_content, dict):
405
        msg = ("%s %s: %s" %
406
               (response_content["code"],
407
                response_content["message"],
408
                response_content["explain"]))
409
      else:
410
        msg = str(response_content)
411

    
412
      raise GanetiApiError(msg, code=http_code)
413

    
414
    return response_content
415

    
416
  def GetVersion(self):
417
    """Gets the Remote API version running on the cluster.
418

419
    @rtype: int
420
    @return: Ganeti Remote API version
421

422
    """
423
    return self._SendRequest(HTTP_GET, "/version", None, None)
424

    
425
  def GetFeatures(self):
426
    """Gets the list of optional features supported by RAPI server.
427

428
    @rtype: list
429
    @return: List of optional features
430

431
    """
432
    try:
433
      return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
434
                               None, None)
435
    except GanetiApiError, err:
436
      # Older RAPI servers don't support this resource
437
      if err.code == HTTP_NOT_FOUND:
438
        return []
439

    
440
      raise
441

    
442
  def GetOperatingSystems(self):
443
    """Gets the Operating Systems running in the Ganeti cluster.
444

445
    @rtype: list of str
446
    @return: operating systems
447

448
    """
449
    return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
450
                             None, None)
451

    
452
  def GetInfo(self):
453
    """Gets info about the cluster.
454

455
    @rtype: dict
456
    @return: information about the cluster
457

458
    """
459
    return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
460
                             None, None)
461

    
462
  def GetClusterTags(self):
463
    """Gets the cluster tags.
464

465
    @rtype: list of str
466
    @return: cluster tags
467

468
    """
469
    return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
470
                             None, None)
471

    
472
  def AddClusterTags(self, tags, dry_run=False):
473
    """Adds tags to the cluster.
474

475
    @type tags: list of str
476
    @param tags: tags to add to the cluster
477
    @type dry_run: bool
478
    @param dry_run: whether to perform a dry run
479

480
    @rtype: int
481
    @return: job id
482

483
    """
484
    query = [("tag", t) for t in tags]
485
    if dry_run:
486
      query.append(("dry-run", 1))
487

    
488
    return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
489
                             query, None)
490

    
491
  def DeleteClusterTags(self, tags, dry_run=False):
492
    """Deletes tags from the cluster.
493

494
    @type tags: list of str
495
    @param tags: tags to delete
496
    @type dry_run: bool
497
    @param dry_run: whether to perform a dry run
498

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

    
504
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
505
                             query, None)
506

    
507
  def GetInstances(self, bulk=False):
508
    """Gets information about instances on the cluster.
509

510
    @type bulk: bool
511
    @param bulk: whether to return all information about all instances
512

513
    @rtype: list of dict or list of str
514
    @return: if bulk is True, info about the instances, else a list of instances
515

516
    """
517
    query = []
518
    if bulk:
519
      query.append(("bulk", 1))
520

    
521
    instances = self._SendRequest(HTTP_GET,
522
                                  "/%s/instances" % GANETI_RAPI_VERSION,
523
                                  query, None)
524
    if bulk:
525
      return instances
526
    else:
527
      return [i["id"] for i in instances]
528

    
529
  def GetInstance(self, instance):
530
    """Gets information about an instance.
531

532
    @type instance: str
533
    @param instance: instance whose info to return
534

535
    @rtype: dict
536
    @return: info about the instance
537

538
    """
539
    return self._SendRequest(HTTP_GET,
540
                             ("/%s/instances/%s" %
541
                              (GANETI_RAPI_VERSION, instance)), None, None)
542

    
543
  def GetInstanceInfo(self, instance, static=None):
544
    """Gets information about an instance.
545

546
    @type instance: string
547
    @param instance: Instance name
548
    @rtype: string
549
    @return: Job ID
550

551
    """
552
    if static is not None:
553
      query = [("static", static)]
554
    else:
555
      query = None
556

    
557
    return self._SendRequest(HTTP_GET,
558
                             ("/%s/instances/%s/info" %
559
                              (GANETI_RAPI_VERSION, instance)), query, None)
560

    
561
  def CreateInstance(self, mode, name, disk_template, disks, nics,
562
                     **kwargs):
563
    """Creates a new instance.
564

565
    More details for parameters can be found in the RAPI documentation.
566

567
    @type mode: string
568
    @param mode: Instance creation mode
569
    @type name: string
570
    @param name: Hostname of the instance to create
571
    @type disk_template: string
572
    @param disk_template: Disk template for instance (e.g. plain, diskless,
573
                          file, or drbd)
574
    @type disks: list of dicts
575
    @param disks: List of disk definitions
576
    @type nics: list of dicts
577
    @param nics: List of NIC definitions
578
    @type dry_run: bool
579
    @keyword dry_run: whether to perform a dry run
580

581
    @rtype: int
582
    @return: job id
583

584
    """
585
    query = []
586

    
587
    if kwargs.get("dry_run"):
588
      query.append(("dry-run", 1))
589

    
590
    if _INST_CREATE_REQV1 in self.GetFeatures():
591
      # All required fields for request data version 1
592
      body = {
593
        _REQ_DATA_VERSION_FIELD: 1,
594
        "mode": mode,
595
        "name": name,
596
        "disk_template": disk_template,
597
        "disks": disks,
598
        "nics": nics,
599
        }
600

    
601
      conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
602
      if conflicts:
603
        raise GanetiApiError("Required fields can not be specified as"
604
                             " keywords: %s" % ", ".join(conflicts))
605

    
606
      body.update((key, value) for key, value in kwargs.iteritems()
607
                  if key != "dry_run")
608
    else:
609
      # Old request format (version 0)
610

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

    
617
      # Validate disks
618
      for idx, disk in enumerate(disks):
619
        unsupported = set(disk.keys()) - _INST_CREATE_V0_DISK_PARAMS
620
        if unsupported:
621
          raise GanetiApiError("Server supports request version 0 only, but"
622
                               " disk %s specifies the unsupported parameters"
623
                               " %s, allowed are %s" %
624
                               (idx, unsupported,
625
                                list(_INST_CREATE_V0_DISK_PARAMS)))
626

    
627
      assert (len(_INST_CREATE_V0_DISK_PARAMS) == 1 and
628
              "size" in _INST_CREATE_V0_DISK_PARAMS)
629
      disk_sizes = [disk["size"] for disk in disks]
630

    
631
      # Validate NICs
632
      if not nics:
633
        raise GanetiApiError("Server supports request version 0 only, but"
634
                             " no NIC specified")
635
      elif len(nics) > 1:
636
        raise GanetiApiError("Server supports request version 0 only, but"
637
                             " more than one NIC specified")
638

    
639
      assert len(nics) == 1
640

    
641
      unsupported = set(nics[0].keys()) - _INST_NIC_PARAMS
642
      if unsupported:
643
        raise GanetiApiError("Server supports request version 0 only, but"
644
                             " NIC 0 specifies the unsupported parameters %s,"
645
                             " allowed are %s" %
646
                             (unsupported, list(_INST_NIC_PARAMS)))
647

    
648
      # Validate other parameters
649
      unsupported = (set(kwargs.keys()) - _INST_CREATE_V0_PARAMS -
650
                     _INST_CREATE_V0_DPARAMS)
651
      if unsupported:
652
        allowed = _INST_CREATE_V0_PARAMS.union(_INST_CREATE_V0_DPARAMS)
653
        raise GanetiApiError("Server supports request version 0 only, but"
654
                             " the following unsupported parameters are"
655
                             " specified: %s, allowed are %s" %
656
                             (unsupported, list(allowed)))
657

    
658
      # All required fields for request data version 0
659
      body = {
660
        _REQ_DATA_VERSION_FIELD: 0,
661
        "name": name,
662
        "disk_template": disk_template,
663
        "disks": disk_sizes,
664
        }
665

    
666
      # NIC fields
667
      assert len(nics) == 1
668
      assert not (set(body.keys()) & set(nics[0].keys()))
669
      body.update(nics[0])
670

    
671
      # Copy supported fields
672
      assert not (set(body.keys()) & set(kwargs.keys()))
673
      body.update(dict((key, value) for key, value in kwargs.items()
674
                       if key in _INST_CREATE_V0_PARAMS))
675

    
676
      # Merge dictionaries
677
      for i in (value for key, value in kwargs.items()
678
                if key in _INST_CREATE_V0_DPARAMS):
679
        assert not (set(body.keys()) & set(i.keys()))
680
        body.update(i)
681

    
682
      assert not (set(kwargs.keys()) -
683
                  (_INST_CREATE_V0_PARAMS | _INST_CREATE_V0_DPARAMS))
684
      assert not (set(body.keys()) & _INST_CREATE_V0_DPARAMS)
685

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

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

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

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

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

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

    
707
  def GetInstanceTags(self, instance):
708
    """Gets tags for an instance.
709

710
    @type instance: str
711
    @param instance: instance whose tags to return
712

713
    @rtype: list of str
714
    @return: tags for the instance
715

716
    """
717
    return self._SendRequest(HTTP_GET,
718
                             ("/%s/instances/%s/tags" %
719
                              (GANETI_RAPI_VERSION, instance)), None, None)
720

    
721
  def AddInstanceTags(self, instance, tags, dry_run=False):
722
    """Adds tags to an instance.
723

724
    @type instance: str
725
    @param instance: instance to add tags to
726
    @type tags: list of str
727
    @param tags: tags to add to the instance
728
    @type dry_run: bool
729
    @param dry_run: whether to perform a dry run
730

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

734
    """
735
    query = [("tag", t) for t in tags]
736
    if dry_run:
737
      query.append(("dry-run", 1))
738

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

    
743
  def DeleteInstanceTags(self, instance, tags, dry_run=False):
744
    """Deletes tags from an instance.
745

746
    @type instance: str
747
    @param instance: instance to delete tags from
748
    @type tags: list of str
749
    @param tags: tags to delete
750
    @type dry_run: bool
751
    @param dry_run: whether to perform a dry run
752

753
    """
754
    query = [("tag", t) for t in tags]
755
    if dry_run:
756
      query.append(("dry-run", 1))
757

    
758
    return self._SendRequest(HTTP_DELETE,
759
                             ("/%s/instances/%s/tags" %
760
                              (GANETI_RAPI_VERSION, instance)), query, None)
761

    
762
  def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
763
                     dry_run=False):
764
    """Reboots an instance.
765

766
    @type instance: str
767
    @param instance: instance to rebot
768
    @type reboot_type: str
769
    @param reboot_type: one of: hard, soft, full
770
    @type ignore_secondaries: bool
771
    @param ignore_secondaries: if True, ignores errors for the secondary node
772
        while re-assembling disks (in hard-reboot mode only)
773
    @type dry_run: bool
774
    @param dry_run: whether to perform a dry run
775

776
    """
777
    query = []
778
    if reboot_type:
779
      query.append(("type", reboot_type))
780
    if ignore_secondaries is not None:
781
      query.append(("ignore_secondaries", ignore_secondaries))
782
    if dry_run:
783
      query.append(("dry-run", 1))
784

    
785
    return self._SendRequest(HTTP_POST,
786
                             ("/%s/instances/%s/reboot" %
787
                              (GANETI_RAPI_VERSION, instance)), query, None)
788

    
789
  def ShutdownInstance(self, instance, dry_run=False):
790
    """Shuts down an instance.
791

792
    @type instance: str
793
    @param instance: the instance to shut down
794
    @type dry_run: bool
795
    @param dry_run: whether to perform a dry run
796

797
    """
798
    query = []
799
    if dry_run:
800
      query.append(("dry-run", 1))
801

    
802
    return self._SendRequest(HTTP_PUT,
803
                             ("/%s/instances/%s/shutdown" %
804
                              (GANETI_RAPI_VERSION, instance)), query, None)
805

    
806
  def StartupInstance(self, instance, dry_run=False):
807
    """Starts up an instance.
808

809
    @type instance: str
810
    @param instance: the instance to start up
811
    @type dry_run: bool
812
    @param dry_run: whether to perform a dry run
813

814
    """
815
    query = []
816
    if dry_run:
817
      query.append(("dry-run", 1))
818

    
819
    return self._SendRequest(HTTP_PUT,
820
                             ("/%s/instances/%s/startup" %
821
                              (GANETI_RAPI_VERSION, instance)), query, None)
822

    
823
  def ReinstallInstance(self, instance, os=None, no_startup=False):
824
    """Reinstalls an instance.
825

826
    @type instance: str
827
    @param instance: The instance to reinstall
828
    @type os: str or None
829
    @param os: The operating system to reinstall. If None, the instance's
830
        current operating system will be installed again
831
    @type no_startup: bool
832
    @param no_startup: Whether to start the instance automatically
833

834
    """
835
    query = []
836
    if os:
837
      query.append(("os", os))
838
    if no_startup:
839
      query.append(("nostartup", 1))
840
    return self._SendRequest(HTTP_POST,
841
                             ("/%s/instances/%s/reinstall" %
842
                              (GANETI_RAPI_VERSION, instance)), query, None)
843

    
844
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
845
                           remote_node=None, iallocator=None, dry_run=False):
846
    """Replaces disks on an instance.
847

848
    @type instance: str
849
    @param instance: instance whose disks to replace
850
    @type disks: list of ints
851
    @param disks: Indexes of disks to replace
852
    @type mode: str
853
    @param mode: replacement mode to use (defaults to replace_auto)
854
    @type remote_node: str or None
855
    @param remote_node: new secondary node to use (for use with
856
        replace_new_secondary mode)
857
    @type iallocator: str or None
858
    @param iallocator: instance allocator plugin to use (for use with
859
                       replace_auto mode)
860
    @type dry_run: bool
861
    @param dry_run: whether to perform a dry run
862

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

866
    """
867
    query = [
868
      ("mode", mode),
869
      ]
870

    
871
    if disks:
872
      query.append(("disks", ",".join(str(idx) for idx in disks)))
873

    
874
    if remote_node:
875
      query.append(("remote_node", remote_node))
876

    
877
    if iallocator:
878
      query.append(("iallocator", iallocator))
879

    
880
    if dry_run:
881
      query.append(("dry-run", 1))
882

    
883
    return self._SendRequest(HTTP_POST,
884
                             ("/%s/instances/%s/replace-disks" %
885
                              (GANETI_RAPI_VERSION, instance)), query, None)
886

    
887
  def PrepareExport(self, instance, mode):
888
    """Prepares an instance for an export.
889

890
    @type instance: string
891
    @param instance: Instance name
892
    @type mode: string
893
    @param mode: Export mode
894
    @rtype: string
895
    @return: Job ID
896

897
    """
898
    query = [("mode", mode)]
899
    return self._SendRequest(HTTP_PUT,
900
                             ("/%s/instances/%s/prepare-export" %
901
                              (GANETI_RAPI_VERSION, instance)), query, None)
902

    
903
  def ExportInstance(self, instance, mode, destination, shutdown=None,
904
                     remove_instance=None,
905
                     x509_key_name=None, destination_x509_ca=None):
906
    """Exports an instance.
907

908
    @type instance: string
909
    @param instance: Instance name
910
    @type mode: string
911
    @param mode: Export mode
912
    @rtype: string
913
    @return: Job ID
914

915
    """
916
    body = {
917
      "destination": destination,
918
      "mode": mode,
919
      }
920

    
921
    if shutdown is not None:
922
      body["shutdown"] = shutdown
923

    
924
    if remove_instance is not None:
925
      body["remove_instance"] = remove_instance
926

    
927
    if x509_key_name is not None:
928
      body["x509_key_name"] = x509_key_name
929

    
930
    if destination_x509_ca is not None:
931
      body["destination_x509_ca"] = destination_x509_ca
932

    
933
    return self._SendRequest(HTTP_PUT,
934
                             ("/%s/instances/%s/export" %
935
                              (GANETI_RAPI_VERSION, instance)), None, body)
936

    
937
  def MigrateInstance(self, instance, mode=None, cleanup=None):
938
    """Starts up an instance.
939

940
    @type instance: string
941
    @param instance: Instance name
942
    @type mode: string
943
    @param mode: Migration mode
944
    @type cleanup: bool
945
    @param cleanup: Whether to clean up a previously failed migration
946

947
    """
948
    body = {}
949

    
950
    if mode is not None:
951
      body["mode"] = mode
952

    
953
    if cleanup is not None:
954
      body["cleanup"] = cleanup
955

    
956
    return self._SendRequest(HTTP_PUT,
957
                             ("/%s/instances/%s/migrate" %
958
                              (GANETI_RAPI_VERSION, instance)), None, body)
959

    
960
  def GetJobs(self):
961
    """Gets all jobs for the cluster.
962

963
    @rtype: list of int
964
    @return: job ids for the cluster
965

966
    """
967
    return [int(j["id"])
968
            for j in self._SendRequest(HTTP_GET,
969
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
970
                                       None, None)]
971

    
972
  def GetJobStatus(self, job_id):
973
    """Gets the status of a job.
974

975
    @type job_id: int
976
    @param job_id: job id whose status to query
977

978
    @rtype: dict
979
    @return: job status
980

981
    """
982
    return self._SendRequest(HTTP_GET,
983
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
984
                             None, None)
985

    
986
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
987
    """Waits for job changes.
988

989
    @type job_id: int
990
    @param job_id: Job ID for which to wait
991

992
    """
993
    body = {
994
      "fields": fields,
995
      "previous_job_info": prev_job_info,
996
      "previous_log_serial": prev_log_serial,
997
      }
998

    
999
    return self._SendRequest(HTTP_GET,
1000
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1001
                             None, body)
1002

    
1003
  def CancelJob(self, job_id, dry_run=False):
1004
    """Cancels a job.
1005

1006
    @type job_id: int
1007
    @param job_id: id of the job to delete
1008
    @type dry_run: bool
1009
    @param dry_run: whether to perform a dry run
1010

1011
    """
1012
    query = []
1013
    if dry_run:
1014
      query.append(("dry-run", 1))
1015

    
1016
    return self._SendRequest(HTTP_DELETE,
1017
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1018
                             query, None)
1019

    
1020
  def GetNodes(self, bulk=False):
1021
    """Gets all nodes in the cluster.
1022

1023
    @type bulk: bool
1024
    @param bulk: whether to return all information about all instances
1025

1026
    @rtype: list of dict or str
1027
    @return: if bulk is true, info about nodes in the cluster,
1028
        else list of nodes in the cluster
1029

1030
    """
1031
    query = []
1032
    if bulk:
1033
      query.append(("bulk", 1))
1034

    
1035
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1036
                              query, None)
1037
    if bulk:
1038
      return nodes
1039
    else:
1040
      return [n["id"] for n in nodes]
1041

    
1042
  def GetNode(self, node):
1043
    """Gets information about a node.
1044

1045
    @type node: str
1046
    @param node: node whose info to return
1047

1048
    @rtype: dict
1049
    @return: info about the node
1050

1051
    """
1052
    return self._SendRequest(HTTP_GET,
1053
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1054
                             None, None)
1055

    
1056
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1057
                   dry_run=False, early_release=False):
1058
    """Evacuates instances from a Ganeti node.
1059

1060
    @type node: str
1061
    @param node: node to evacuate
1062
    @type iallocator: str or None
1063
    @param iallocator: instance allocator to use
1064
    @type remote_node: str
1065
    @param remote_node: node to evaucate to
1066
    @type dry_run: bool
1067
    @param dry_run: whether to perform a dry run
1068
    @type early_release: bool
1069
    @param early_release: whether to enable parallelization
1070

1071
    @rtype: list
1072
    @return: list of (job ID, instance name, new secondary node); if
1073
        dry_run was specified, then the actual move jobs were not
1074
        submitted and the job IDs will be C{None}
1075

1076
    @raises GanetiApiError: if an iallocator and remote_node are both
1077
        specified
1078

1079
    """
1080
    if iallocator and remote_node:
1081
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1082

    
1083
    query = []
1084
    if iallocator:
1085
      query.append(("iallocator", iallocator))
1086
    if remote_node:
1087
      query.append(("remote_node", remote_node))
1088
    if dry_run:
1089
      query.append(("dry-run", 1))
1090
    if early_release:
1091
      query.append(("early_release", 1))
1092

    
1093
    return self._SendRequest(HTTP_POST,
1094
                             ("/%s/nodes/%s/evacuate" %
1095
                              (GANETI_RAPI_VERSION, node)), query, None)
1096

    
1097
  def MigrateNode(self, node, mode=None, dry_run=False):
1098
    """Migrates all primary instances from a node.
1099

1100
    @type node: str
1101
    @param node: node to migrate
1102
    @type mode: string
1103
    @param mode: if passed, it will overwrite the live migration type,
1104
        otherwise the hypervisor default will be used
1105
    @type dry_run: bool
1106
    @param dry_run: whether to perform a dry run
1107

1108
    @rtype: int
1109
    @return: job id
1110

1111
    """
1112
    query = []
1113
    if mode is not None:
1114
      query.append(("mode", mode))
1115
    if dry_run:
1116
      query.append(("dry-run", 1))
1117

    
1118
    return self._SendRequest(HTTP_POST,
1119
                             ("/%s/nodes/%s/migrate" %
1120
                              (GANETI_RAPI_VERSION, node)), query, None)
1121

    
1122
  def GetNodeRole(self, node):
1123
    """Gets the current role for a node.
1124

1125
    @type node: str
1126
    @param node: node whose role to return
1127

1128
    @rtype: str
1129
    @return: the current role for a node
1130

1131
    """
1132
    return self._SendRequest(HTTP_GET,
1133
                             ("/%s/nodes/%s/role" %
1134
                              (GANETI_RAPI_VERSION, node)), None, None)
1135

    
1136
  def SetNodeRole(self, node, role, force=False):
1137
    """Sets the role for a node.
1138

1139
    @type node: str
1140
    @param node: the node whose role to set
1141
    @type role: str
1142
    @param role: the role to set for the node
1143
    @type force: bool
1144
    @param force: whether to force the role change
1145

1146
    @rtype: int
1147
    @return: job id
1148

1149
    """
1150
    query = [
1151
      ("force", force),
1152
      ]
1153

    
1154
    return self._SendRequest(HTTP_PUT,
1155
                             ("/%s/nodes/%s/role" %
1156
                              (GANETI_RAPI_VERSION, node)), query, role)
1157

    
1158
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1159
    """Gets the storage units for a node.
1160

1161
    @type node: str
1162
    @param node: the node whose storage units to return
1163
    @type storage_type: str
1164
    @param storage_type: storage type whose units to return
1165
    @type output_fields: str
1166
    @param output_fields: storage type fields to return
1167

1168
    @rtype: int
1169
    @return: job id where results can be retrieved
1170

1171
    """
1172
    query = [
1173
      ("storage_type", storage_type),
1174
      ("output_fields", output_fields),
1175
      ]
1176

    
1177
    return self._SendRequest(HTTP_GET,
1178
                             ("/%s/nodes/%s/storage" %
1179
                              (GANETI_RAPI_VERSION, node)), query, None)
1180

    
1181
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1182
    """Modifies parameters of storage units on the node.
1183

1184
    @type node: str
1185
    @param node: node whose storage units to modify
1186
    @type storage_type: str
1187
    @param storage_type: storage type whose units to modify
1188
    @type name: str
1189
    @param name: name of the storage unit
1190
    @type allocatable: bool or None
1191
    @param allocatable: Whether to set the "allocatable" flag on the storage
1192
                        unit (None=no modification, True=set, False=unset)
1193

1194
    @rtype: int
1195
    @return: job id
1196

1197
    """
1198
    query = [
1199
      ("storage_type", storage_type),
1200
      ("name", name),
1201
      ]
1202

    
1203
    if allocatable is not None:
1204
      query.append(("allocatable", allocatable))
1205

    
1206
    return self._SendRequest(HTTP_PUT,
1207
                             ("/%s/nodes/%s/storage/modify" %
1208
                              (GANETI_RAPI_VERSION, node)), query, None)
1209

    
1210
  def RepairNodeStorageUnits(self, node, storage_type, name):
1211
    """Repairs a storage unit on the node.
1212

1213
    @type node: str
1214
    @param node: node whose storage units to repair
1215
    @type storage_type: str
1216
    @param storage_type: storage type to repair
1217
    @type name: str
1218
    @param name: name of the storage unit to repair
1219

1220
    @rtype: int
1221
    @return: job id
1222

1223
    """
1224
    query = [
1225
      ("storage_type", storage_type),
1226
      ("name", name),
1227
      ]
1228

    
1229
    return self._SendRequest(HTTP_PUT,
1230
                             ("/%s/nodes/%s/storage/repair" %
1231
                              (GANETI_RAPI_VERSION, node)), query, None)
1232

    
1233
  def GetNodeTags(self, node):
1234
    """Gets the tags for a node.
1235

1236
    @type node: str
1237
    @param node: node whose tags to return
1238

1239
    @rtype: list of str
1240
    @return: tags for the node
1241

1242
    """
1243
    return self._SendRequest(HTTP_GET,
1244
                             ("/%s/nodes/%s/tags" %
1245
                              (GANETI_RAPI_VERSION, node)), None, None)
1246

    
1247
  def AddNodeTags(self, node, tags, dry_run=False):
1248
    """Adds tags to a node.
1249

1250
    @type node: str
1251
    @param node: node to add tags to
1252
    @type tags: list of str
1253
    @param tags: tags to add to the node
1254
    @type dry_run: bool
1255
    @param dry_run: whether to perform a dry run
1256

1257
    @rtype: int
1258
    @return: job id
1259

1260
    """
1261
    query = [("tag", t) for t in tags]
1262
    if dry_run:
1263
      query.append(("dry-run", 1))
1264

    
1265
    return self._SendRequest(HTTP_PUT,
1266
                             ("/%s/nodes/%s/tags" %
1267
                              (GANETI_RAPI_VERSION, node)), query, tags)
1268

    
1269
  def DeleteNodeTags(self, node, tags, dry_run=False):
1270
    """Delete tags from a node.
1271

1272
    @type node: str
1273
    @param node: node to remove tags from
1274
    @type tags: list of str
1275
    @param tags: tags to remove from the node
1276
    @type dry_run: bool
1277
    @param dry_run: whether to perform a dry run
1278

1279
    @rtype: int
1280
    @return: job id
1281

1282
    """
1283
    query = [("tag", t) for t in tags]
1284
    if dry_run:
1285
      query.append(("dry-run", 1))
1286

    
1287
    return self._SendRequest(HTTP_DELETE,
1288
                             ("/%s/nodes/%s/tags" %
1289
                              (GANETI_RAPI_VERSION, node)), query, None)