Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ e0ac6ce6

History | View | Annotate | Download (37.5 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, no_startup=False):
824
    """Reinstalls an instance.
825

826
    @type instance: str
827
    @param instance: the instance to reinstall
828
    @type os: str
829
    @param os: the os to reinstall
830
    @type no_startup: bool
831
    @param no_startup: whether to start the instance automatically
832

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

    
841
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
842
                           remote_node=None, iallocator=None, dry_run=False):
843
    """Replaces disks on an instance.
844

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

860
    @rtype: int
861
    @return: job id
862

863
    """
864
    query = [
865
      ("mode", mode),
866
      ]
867

    
868
    if disks:
869
      query.append(("disks", ",".join(str(idx) for idx in disks)))
870

    
871
    if remote_node:
872
      query.append(("remote_node", remote_node))
873

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

    
877
    if dry_run:
878
      query.append(("dry-run", 1))
879

    
880
    return self._SendRequest(HTTP_POST,
881
                             ("/%s/instances/%s/replace-disks" %
882
                              (GANETI_RAPI_VERSION, instance)), query, None)
883

    
884
  def PrepareExport(self, instance, mode):
885
    """Prepares an instance for an export.
886

887
    @type instance: string
888
    @param instance: Instance name
889
    @type mode: string
890
    @param mode: Export mode
891
    @rtype: string
892
    @return: Job ID
893

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

    
900
  def ExportInstance(self, instance, mode, destination, shutdown=None,
901
                     remove_instance=None,
902
                     x509_key_name=None, destination_x509_ca=None):
903
    """Exports an instance.
904

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

912
    """
913
    body = {
914
      "destination": destination,
915
      "mode": mode,
916
      }
917

    
918
    if shutdown is not None:
919
      body["shutdown"] = shutdown
920

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

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

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

    
930
    return self._SendRequest(HTTP_PUT,
931
                             ("/%s/instances/%s/export" %
932
                              (GANETI_RAPI_VERSION, instance)), None, body)
933

    
934
  def MigrateInstance(self, instance, mode=None, cleanup=None):
935
    """Starts up an instance.
936

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

944
    """
945
    body = {}
946

    
947
    if mode is not None:
948
      body["mode"] = mode
949

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

    
953
    return self._SendRequest(HTTP_PUT,
954
                             ("/%s/instances/%s/migrate" %
955
                              (GANETI_RAPI_VERSION, instance)), None, body)
956

    
957
  def GetJobs(self):
958
    """Gets all jobs for the cluster.
959

960
    @rtype: list of int
961
    @return: job ids for the cluster
962

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

    
969
  def GetJobStatus(self, job_id):
970
    """Gets the status of a job.
971

972
    @type job_id: int
973
    @param job_id: job id whose status to query
974

975
    @rtype: dict
976
    @return: job status
977

978
    """
979
    return self._SendRequest(HTTP_GET,
980
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
981
                             None, None)
982

    
983
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
984
    """Waits for job changes.
985

986
    @type job_id: int
987
    @param job_id: Job ID for which to wait
988

989
    """
990
    body = {
991
      "fields": fields,
992
      "previous_job_info": prev_job_info,
993
      "previous_log_serial": prev_log_serial,
994
      }
995

    
996
    return self._SendRequest(HTTP_GET,
997
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
998
                             None, body)
999

    
1000
  def CancelJob(self, job_id, dry_run=False):
1001
    """Cancels a job.
1002

1003
    @type job_id: int
1004
    @param job_id: id of the job to delete
1005
    @type dry_run: bool
1006
    @param dry_run: whether to perform a dry run
1007

1008
    """
1009
    query = []
1010
    if dry_run:
1011
      query.append(("dry-run", 1))
1012

    
1013
    return self._SendRequest(HTTP_DELETE,
1014
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1015
                             query, None)
1016

    
1017
  def GetNodes(self, bulk=False):
1018
    """Gets all nodes in the cluster.
1019

1020
    @type bulk: bool
1021
    @param bulk: whether to return all information about all instances
1022

1023
    @rtype: list of dict or str
1024
    @return: if bulk is true, info about nodes in the cluster,
1025
        else list of nodes in the cluster
1026

1027
    """
1028
    query = []
1029
    if bulk:
1030
      query.append(("bulk", 1))
1031

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

    
1039
  def GetNode(self, node):
1040
    """Gets information about a node.
1041

1042
    @type node: str
1043
    @param node: node whose info to return
1044

1045
    @rtype: dict
1046
    @return: info about the node
1047

1048
    """
1049
    return self._SendRequest(HTTP_GET,
1050
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1051
                             None, None)
1052

    
1053
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1054
                   dry_run=False, early_release=False):
1055
    """Evacuates instances from a Ganeti node.
1056

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

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

1073
    @raises GanetiApiError: if an iallocator and remote_node are both
1074
        specified
1075

1076
    """
1077
    if iallocator and remote_node:
1078
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1079

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

    
1090
    return self._SendRequest(HTTP_POST,
1091
                             ("/%s/nodes/%s/evacuate" %
1092
                              (GANETI_RAPI_VERSION, node)), query, None)
1093

    
1094
  def MigrateNode(self, node, mode=None, dry_run=False):
1095
    """Migrates all primary instances from a node.
1096

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

1105
    @rtype: int
1106
    @return: job id
1107

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

    
1115
    return self._SendRequest(HTTP_POST,
1116
                             ("/%s/nodes/%s/migrate" %
1117
                              (GANETI_RAPI_VERSION, node)), query, None)
1118

    
1119
  def GetNodeRole(self, node):
1120
    """Gets the current role for a node.
1121

1122
    @type node: str
1123
    @param node: node whose role to return
1124

1125
    @rtype: str
1126
    @return: the current role for a node
1127

1128
    """
1129
    return self._SendRequest(HTTP_GET,
1130
                             ("/%s/nodes/%s/role" %
1131
                              (GANETI_RAPI_VERSION, node)), None, None)
1132

    
1133
  def SetNodeRole(self, node, role, force=False):
1134
    """Sets the role for a node.
1135

1136
    @type node: str
1137
    @param node: the node whose role to set
1138
    @type role: str
1139
    @param role: the role to set for the node
1140
    @type force: bool
1141
    @param force: whether to force the role change
1142

1143
    @rtype: int
1144
    @return: job id
1145

1146
    """
1147
    query = [
1148
      ("force", force),
1149
      ]
1150

    
1151
    return self._SendRequest(HTTP_PUT,
1152
                             ("/%s/nodes/%s/role" %
1153
                              (GANETI_RAPI_VERSION, node)), query, role)
1154

    
1155
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1156
    """Gets the storage units for a node.
1157

1158
    @type node: str
1159
    @param node: the node whose storage units to return
1160
    @type storage_type: str
1161
    @param storage_type: storage type whose units to return
1162
    @type output_fields: str
1163
    @param output_fields: storage type fields to return
1164

1165
    @rtype: int
1166
    @return: job id where results can be retrieved
1167

1168
    """
1169
    query = [
1170
      ("storage_type", storage_type),
1171
      ("output_fields", output_fields),
1172
      ]
1173

    
1174
    return self._SendRequest(HTTP_GET,
1175
                             ("/%s/nodes/%s/storage" %
1176
                              (GANETI_RAPI_VERSION, node)), query, None)
1177

    
1178
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1179
    """Modifies parameters of storage units on the node.
1180

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

1191
    @rtype: int
1192
    @return: job id
1193

1194
    """
1195
    query = [
1196
      ("storage_type", storage_type),
1197
      ("name", name),
1198
      ]
1199

    
1200
    if allocatable is not None:
1201
      query.append(("allocatable", allocatable))
1202

    
1203
    return self._SendRequest(HTTP_PUT,
1204
                             ("/%s/nodes/%s/storage/modify" %
1205
                              (GANETI_RAPI_VERSION, node)), query, None)
1206

    
1207
  def RepairNodeStorageUnits(self, node, storage_type, name):
1208
    """Repairs a storage unit on the node.
1209

1210
    @type node: str
1211
    @param node: node whose storage units to repair
1212
    @type storage_type: str
1213
    @param storage_type: storage type to repair
1214
    @type name: str
1215
    @param name: name of the storage unit to repair
1216

1217
    @rtype: int
1218
    @return: job id
1219

1220
    """
1221
    query = [
1222
      ("storage_type", storage_type),
1223
      ("name", name),
1224
      ]
1225

    
1226
    return self._SendRequest(HTTP_PUT,
1227
                             ("/%s/nodes/%s/storage/repair" %
1228
                              (GANETI_RAPI_VERSION, node)), query, None)
1229

    
1230
  def GetNodeTags(self, node):
1231
    """Gets the tags for a node.
1232

1233
    @type node: str
1234
    @param node: node whose tags to return
1235

1236
    @rtype: list of str
1237
    @return: tags for the node
1238

1239
    """
1240
    return self._SendRequest(HTTP_GET,
1241
                             ("/%s/nodes/%s/tags" %
1242
                              (GANETI_RAPI_VERSION, node)), None, None)
1243

    
1244
  def AddNodeTags(self, node, tags, dry_run=False):
1245
    """Adds tags to a node.
1246

1247
    @type node: str
1248
    @param node: node to add tags to
1249
    @type tags: list of str
1250
    @param tags: tags to add to the node
1251
    @type dry_run: bool
1252
    @param dry_run: whether to perform a dry run
1253

1254
    @rtype: int
1255
    @return: job id
1256

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

    
1262
    return self._SendRequest(HTTP_PUT,
1263
                             ("/%s/nodes/%s/tags" %
1264
                              (GANETI_RAPI_VERSION, node)), query, tags)
1265

    
1266
  def DeleteNodeTags(self, node, tags, dry_run=False):
1267
    """Delete tags from a node.
1268

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

1276
    @rtype: int
1277
    @return: job id
1278

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

    
1284
    return self._SendRequest(HTTP_DELETE,
1285
                             ("/%s/nodes/%s/tags" %
1286
                              (GANETI_RAPI_VERSION, node)), query, None)