Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ 5ef5cfea

History | View | Annotate | Download (30.1 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
# No Ganeti-specific modules should be imported. The RAPI client is supposed to
25
# be standalone.
26

    
27
import httplib
28
import urllib2
29
import logging
30
import simplejson
31
import socket
32
import urllib
33
import OpenSSL
34
import distutils.version
35

    
36

    
37
GANETI_RAPI_PORT = 5080
38
GANETI_RAPI_VERSION = 2
39

    
40
HTTP_DELETE = "DELETE"
41
HTTP_GET = "GET"
42
HTTP_PUT = "PUT"
43
HTTP_POST = "POST"
44
HTTP_OK = 200
45
HTTP_NOT_FOUND = 404
46
HTTP_APP_JSON = "application/json"
47

    
48
REPLACE_DISK_PRI = "replace_on_primary"
49
REPLACE_DISK_SECONDARY = "replace_on_secondary"
50
REPLACE_DISK_CHG = "replace_new_secondary"
51
REPLACE_DISK_AUTO = "replace_auto"
52

    
53
NODE_ROLE_DRAINED = "drained"
54
NODE_ROLE_MASTER_CANDIATE = "master-candidate"
55
NODE_ROLE_MASTER = "master"
56
NODE_ROLE_OFFLINE = "offline"
57
NODE_ROLE_REGULAR = "regular"
58

    
59

    
60
class Error(Exception):
61
  """Base error class for this module.
62

63
  """
64
  pass
65

    
66

    
67
class CertificateError(Error):
68
  """Raised when a problem is found with the SSL certificate.
69

70
  """
71
  pass
72

    
73

    
74
class GanetiApiError(Error):
75
  """Generic error raised from Ganeti API.
76

77
  """
78
  def __init__(self, msg, code=None):
79
    Error.__init__(self, msg)
80
    self.code = code
81

    
82

    
83
def FormatX509Name(x509_name):
84
  """Formats an X509 name.
85

86
  @type x509_name: OpenSSL.crypto.X509Name
87

88
  """
89
  try:
90
    # Only supported in pyOpenSSL 0.7 and above
91
    get_components_fn = x509_name.get_components
92
  except AttributeError:
93
    return repr(x509_name)
94
  else:
95
    return "".join("/%s=%s" % (name, value)
96
                   for name, value in get_components_fn())
97

    
98

    
99
class CertAuthorityVerify:
100
  """Certificate verificator for SSL context.
101

102
  Configures SSL context to verify server's certificate.
103

104
  """
105
  _CAPATH_MINVERSION = "0.9"
106
  _DEFVFYPATHS_MINVERSION = "0.9"
107

    
108
  _PYOPENSSL_VERSION = OpenSSL.__version__
109
  _PARSED_PYOPENSSL_VERSION = distutils.version.LooseVersion(_PYOPENSSL_VERSION)
110

    
111
  _SUPPORT_CAPATH = (_PARSED_PYOPENSSL_VERSION >= _CAPATH_MINVERSION)
112
  _SUPPORT_DEFVFYPATHS = (_PARSED_PYOPENSSL_VERSION >= _DEFVFYPATHS_MINVERSION)
113

    
114
  def __init__(self, cafile=None, capath=None, use_default_verify_paths=False):
115
    """Initializes this class.
116

117
    @type cafile: string
118
    @param cafile: In which file we can find the certificates
119
    @type capath: string
120
    @param capath: In which directory we can find the certificates
121
    @type use_default_verify_paths: bool
122
    @param use_default_verify_paths: Whether the platform provided CA
123
                                     certificates are to be used for
124
                                     verification purposes
125

126
    """
127
    self._cafile = cafile
128
    self._capath = capath
129
    self._use_default_verify_paths = use_default_verify_paths
130

    
131
    if self._capath is not None and not self._SUPPORT_CAPATH:
132
      raise Error(("PyOpenSSL %s has no support for a CA directory,"
133
                   " version %s or above is required") %
134
                  (self._PYOPENSSL_VERSION, self._CAPATH_MINVERSION))
135

    
136
    if self._use_default_verify_paths and not self._SUPPORT_DEFVFYPATHS:
137
      raise Error(("PyOpenSSL %s has no support for using default verification"
138
                   " paths, version %s or above is required") %
139
                  (self._PYOPENSSL_VERSION, self._DEFVFYPATHS_MINVERSION))
140

    
141
  @staticmethod
142
  def _VerifySslCertCb(logger, _, cert, errnum, errdepth, ok):
143
    """Callback for SSL certificate verification.
144

145
    @param logger: Logging object
146

147
    """
148
    if ok:
149
      log_fn = logger.debug
150
    else:
151
      log_fn = logger.error
152

    
153
    log_fn("Verifying SSL certificate at depth %s, subject '%s', issuer '%s'",
154
           errdepth, FormatX509Name(cert.get_subject()),
155
           FormatX509Name(cert.get_issuer()))
156

    
157
    if not ok:
158
      try:
159
        # Only supported in pyOpenSSL 0.7 and above
160
        # pylint: disable-msg=E1101
161
        fn = OpenSSL.crypto.X509_verify_cert_error_string
162
      except AttributeError:
163
        errmsg = ""
164
      else:
165
        errmsg = ":%s" % fn(errnum)
166

    
167
      logger.error("verify error:num=%s%s", errnum, errmsg)
168

    
169
    return ok
170

    
171
  def __call__(self, ctx, logger):
172
    """Configures an SSL context to verify certificates.
173

174
    @type ctx: OpenSSL.SSL.Context
175
    @param ctx: SSL context
176

177
    """
178
    if self._use_default_verify_paths:
179
      ctx.set_default_verify_paths()
180

    
181
    if self._cafile or self._capath:
182
      if self._SUPPORT_CAPATH:
183
        ctx.load_verify_locations(self._cafile, self._capath)
184
      else:
185
        ctx.load_verify_locations(self._cafile)
186

    
187
    ctx.set_verify(OpenSSL.SSL.VERIFY_PEER,
188
                   lambda conn, cert, errnum, errdepth, ok: \
189
                     self._VerifySslCertCb(logger, conn, cert,
190
                                           errnum, errdepth, ok))
191

    
192

    
193
class _HTTPSConnectionOpenSSL(httplib.HTTPSConnection):
194
  """HTTPS Connection handler that verifies the SSL certificate.
195

196
  """
197
  def __init__(self, *args, **kwargs):
198
    """Initializes this class.
199

200
    """
201
    httplib.HTTPSConnection.__init__(self, *args, **kwargs)
202
    self._logger = None
203
    self._config_ssl_verification = None
204

    
205
  def Setup(self, logger, config_ssl_verification):
206
    """Sets the SSL verification config function.
207

208
    @param logger: Logging object
209
    @type config_ssl_verification: callable
210

211
    """
212
    assert self._logger is None
213
    assert self._config_ssl_verification is None
214

    
215
    self._logger = logger
216
    self._config_ssl_verification = config_ssl_verification
217

    
218
  def connect(self):
219
    """Connect to the server specified when the object was created.
220

221
    This ensures that SSL certificates are verified.
222

223
    """
224
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
225

    
226
    ctx = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
227
    ctx.set_options(OpenSSL.SSL.OP_NO_SSLv2)
228

    
229
    if self._config_ssl_verification:
230
      self._config_ssl_verification(ctx, self._logger)
231

    
232
    ssl = OpenSSL.SSL.Connection(ctx, sock)
233
    ssl.connect((self.host, self.port))
234

    
235
    self.sock = httplib.FakeSocket(sock, ssl)
236

    
237

    
238
class _HTTPSHandler(urllib2.HTTPSHandler):
239
  def __init__(self, logger, config_ssl_verification):
240
    """Initializes this class.
241

242
    @param logger: Logging object
243
    @type config_ssl_verification: callable
244
    @param config_ssl_verification: Function to configure SSL context for
245
                                    certificate verification
246

247
    """
248
    urllib2.HTTPSHandler.__init__(self)
249
    self._logger = logger
250
    self._config_ssl_verification = config_ssl_verification
251

    
252
  def _CreateHttpsConnection(self, *args, **kwargs):
253
    """Wrapper around L{_HTTPSConnectionOpenSSL} to add SSL verification.
254

255
    This wrapper is necessary provide a compatible API to urllib2.
256

257
    """
258
    conn = _HTTPSConnectionOpenSSL(*args, **kwargs)
259
    conn.Setup(self._logger, self._config_ssl_verification)
260
    return conn
261

    
262
  def https_open(self, req):
263
    """Creates HTTPS connection.
264

265
    Called by urllib2.
266

267
    """
268
    return self.do_open(self._CreateHttpsConnection, req)
269

    
270

    
271
class _RapiRequest(urllib2.Request):
272
  def __init__(self, method, url, headers, data):
273
    """Initializes this class.
274

275
    """
276
    urllib2.Request.__init__(self, url, data=data, headers=headers)
277
    self._method = method
278

    
279
  def get_method(self):
280
    """Returns the HTTP request method.
281

282
    """
283
    return self._method
284

    
285

    
286
class GanetiRapiClient(object):
287
  """Ganeti RAPI client.
288

289
  """
290
  USER_AGENT = "Ganeti RAPI Client"
291
  _json_encoder = simplejson.JSONEncoder(sort_keys=True)
292

    
293
  def __init__(self, host, port=GANETI_RAPI_PORT,
294
               username=None, password=None,
295
               config_ssl_verification=None, ignore_proxy=False,
296
               logger=logging):
297
    """Constructor.
298

299
    @type host: string
300
    @param host: the ganeti cluster master to interact with
301
    @type port: int
302
    @param port: the port on which the RAPI is running (default is 5080)
303
    @type username: string
304
    @param username: the username to connect with
305
    @type password: string
306
    @param password: the password to connect with
307
    @type config_ssl_verification: callable
308
    @param config_ssl_verification: Function to configure SSL context for
309
                                    certificate verification
310
    @type ignore_proxy: bool
311
    @param ignore_proxy: Whether to ignore proxy settings
312
    @param logger: Logging object
313

314
    """
315
    self._host = host
316
    self._port = port
317
    self._logger = logger
318

    
319
    self._base_url = "https://%s:%s" % (host, port)
320

    
321
    handlers = [_HTTPSHandler(self._logger, config_ssl_verification)]
322

    
323
    if username is not None:
324
      pwmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
325
      pwmgr.add_password(None, self._base_url, username, password)
326
      handlers.append(urllib2.HTTPBasicAuthHandler(pwmgr))
327
    elif password:
328
      raise Error("Specified password without username")
329

    
330
    if ignore_proxy:
331
      handlers.append(urllib2.ProxyHandler({}))
332

    
333
    self._http = urllib2.build_opener(*handlers) # pylint: disable-msg=W0142
334

    
335
    self._headers = {
336
      "Accept": HTTP_APP_JSON,
337
      "Content-type": HTTP_APP_JSON,
338
      "User-Agent": self.USER_AGENT,
339
      }
340

    
341
  @staticmethod
342
  def _EncodeQuery(query):
343
    """Encode query values for RAPI URL.
344

345
    @type query: list of two-tuples
346
    @param query: Query arguments
347
    @rtype: list
348
    @return: Query list with encoded values
349

350
    """
351
    result = []
352

    
353
    for name, value in query:
354
      if value is None:
355
        result.append((name, ""))
356

    
357
      elif isinstance(value, bool):
358
        # Boolean values must be encoded as 0 or 1
359
        result.append((name, int(value)))
360

    
361
      elif isinstance(value, (list, tuple, dict)):
362
        raise ValueError("Invalid query data type %r" % type(value).__name__)
363

    
364
      else:
365
        result.append((name, value))
366

    
367
    return result
368

    
369
  def _SendRequest(self, method, path, query, content):
370
    """Sends an HTTP request.
371

372
    This constructs a full URL, encodes and decodes HTTP bodies, and
373
    handles invalid responses in a pythonic way.
374

375
    @type method: string
376
    @param method: HTTP method to use
377
    @type path: string
378
    @param path: HTTP URL path
379
    @type query: list of two-tuples
380
    @param query: query arguments to pass to urllib.urlencode
381
    @type content: str or None
382
    @param content: HTTP body content
383

384
    @rtype: str
385
    @return: JSON-Decoded response
386

387
    @raises CertificateError: If an invalid SSL certificate is found
388
    @raises GanetiApiError: If an invalid response is returned
389

390
    """
391
    assert path.startswith("/")
392

    
393
    if content:
394
      encoded_content = self._json_encoder.encode(content)
395
    else:
396
      encoded_content = None
397

    
398
    # Build URL
399
    url = [self._base_url, path]
400
    if query:
401
      url.append("?")
402
      url.append(urllib.urlencode(self._EncodeQuery(query)))
403

    
404
    req = _RapiRequest(method, "".join(url), self._headers, encoded_content)
405

    
406
    try:
407
      resp = self._http.open(req)
408
      encoded_response_content = resp.read()
409
    except (OpenSSL.SSL.Error, OpenSSL.crypto.Error), err:
410
      raise CertificateError("SSL issue: %s (%r)" % (err, err))
411

    
412
    if encoded_response_content:
413
      response_content = simplejson.loads(encoded_response_content)
414
    else:
415
      response_content = None
416

    
417
    # TODO: Are there other status codes that are valid? (redirect?)
418
    if resp.code != HTTP_OK:
419
      if isinstance(response_content, dict):
420
        msg = ("%s %s: %s" %
421
               (response_content["code"],
422
                response_content["message"],
423
                response_content["explain"]))
424
      else:
425
        msg = str(response_content)
426

    
427
      raise GanetiApiError(msg, code=resp.code)
428

    
429
    return response_content
430

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

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

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

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

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

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

    
455
      raise
456

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
544
  def GetInstanceInfo(self, instance):
545
    """Gets information about an instance.
546

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

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

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

    
558
  def CreateInstance(self, dry_run=False):
559
    """Creates a new instance.
560

561
    @type dry_run: bool
562
    @param dry_run: whether to perform a dry run
563

564
    @rtype: int
565
    @return: job id
566

567
    """
568
    # TODO: Pass arguments needed to actually create an instance.
569
    query = []
570
    if dry_run:
571
      query.append(("dry-run", 1))
572

    
573
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
574
                             query, None)
575

    
576
  def DeleteInstance(self, instance, dry_run=False):
577
    """Deletes an instance.
578

579
    @type instance: str
580
    @param instance: the instance to delete
581

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

585
    """
586
    query = []
587
    if dry_run:
588
      query.append(("dry-run", 1))
589

    
590
    return self._SendRequest(HTTP_DELETE,
591
                             ("/%s/instances/%s" %
592
                              (GANETI_RAPI_VERSION, instance)), query, None)
593

    
594
  def GetInstanceTags(self, instance):
595
    """Gets tags for an instance.
596

597
    @type instance: str
598
    @param instance: instance whose tags to return
599

600
    @rtype: list of str
601
    @return: tags for the instance
602

603
    """
604
    return self._SendRequest(HTTP_GET,
605
                             ("/%s/instances/%s/tags" %
606
                              (GANETI_RAPI_VERSION, instance)), None, None)
607

    
608
  def AddInstanceTags(self, instance, tags, dry_run=False):
609
    """Adds tags to an instance.
610

611
    @type instance: str
612
    @param instance: instance to add tags to
613
    @type tags: list of str
614
    @param tags: tags to add to the instance
615
    @type dry_run: bool
616
    @param dry_run: whether to perform a dry run
617

618
    @rtype: int
619
    @return: job id
620

621
    """
622
    query = [("tag", t) for t in tags]
623
    if dry_run:
624
      query.append(("dry-run", 1))
625

    
626
    return self._SendRequest(HTTP_PUT,
627
                             ("/%s/instances/%s/tags" %
628
                              (GANETI_RAPI_VERSION, instance)), query, None)
629

    
630
  def DeleteInstanceTags(self, instance, tags, dry_run=False):
631
    """Deletes tags from an instance.
632

633
    @type instance: str
634
    @param instance: instance to delete tags from
635
    @type tags: list of str
636
    @param tags: tags to delete
637
    @type dry_run: bool
638
    @param dry_run: whether to perform a dry run
639

640
    """
641
    query = [("tag", t) for t in tags]
642
    if dry_run:
643
      query.append(("dry-run", 1))
644

    
645
    return self._SendRequest(HTTP_DELETE,
646
                             ("/%s/instances/%s/tags" %
647
                              (GANETI_RAPI_VERSION, instance)), query, None)
648

    
649
  def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
650
                     dry_run=False):
651
    """Reboots an instance.
652

653
    @type instance: str
654
    @param instance: instance to rebot
655
    @type reboot_type: str
656
    @param reboot_type: one of: hard, soft, full
657
    @type ignore_secondaries: bool
658
    @param ignore_secondaries: if True, ignores errors for the secondary node
659
        while re-assembling disks (in hard-reboot mode only)
660
    @type dry_run: bool
661
    @param dry_run: whether to perform a dry run
662

663
    """
664
    query = []
665
    if reboot_type:
666
      query.append(("type", reboot_type))
667
    if ignore_secondaries is not None:
668
      query.append(("ignore_secondaries", ignore_secondaries))
669
    if dry_run:
670
      query.append(("dry-run", 1))
671

    
672
    return self._SendRequest(HTTP_POST,
673
                             ("/%s/instances/%s/reboot" %
674
                              (GANETI_RAPI_VERSION, instance)), query, None)
675

    
676
  def ShutdownInstance(self, instance, dry_run=False):
677
    """Shuts down an instance.
678

679
    @type instance: str
680
    @param instance: the instance to shut down
681
    @type dry_run: bool
682
    @param dry_run: whether to perform a dry run
683

684
    """
685
    query = []
686
    if dry_run:
687
      query.append(("dry-run", 1))
688

    
689
    return self._SendRequest(HTTP_PUT,
690
                             ("/%s/instances/%s/shutdown" %
691
                              (GANETI_RAPI_VERSION, instance)), query, None)
692

    
693
  def StartupInstance(self, instance, dry_run=False):
694
    """Starts up an instance.
695

696
    @type instance: str
697
    @param instance: the instance to start up
698
    @type dry_run: bool
699
    @param dry_run: whether to perform a dry run
700

701
    """
702
    query = []
703
    if dry_run:
704
      query.append(("dry-run", 1))
705

    
706
    return self._SendRequest(HTTP_PUT,
707
                             ("/%s/instances/%s/startup" %
708
                              (GANETI_RAPI_VERSION, instance)), query, None)
709

    
710
  def ReinstallInstance(self, instance, os, no_startup=False):
711
    """Reinstalls an instance.
712

713
    @type instance: str
714
    @param instance: the instance to reinstall
715
    @type os: str
716
    @param os: the os to reinstall
717
    @type no_startup: bool
718
    @param no_startup: whether to start the instance automatically
719

720
    """
721
    query = [("os", os)]
722
    if no_startup:
723
      query.append(("nostartup", 1))
724
    return self._SendRequest(HTTP_POST,
725
                             ("/%s/instances/%s/reinstall" %
726
                              (GANETI_RAPI_VERSION, instance)), query, None)
727

    
728
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
729
                           remote_node=None, iallocator=None, dry_run=False):
730
    """Replaces disks on an instance.
731

732
    @type instance: str
733
    @param instance: instance whose disks to replace
734
    @type disks: list of ints
735
    @param disks: Indexes of disks to replace
736
    @type mode: str
737
    @param mode: replacement mode to use (defaults to replace_auto)
738
    @type remote_node: str or None
739
    @param remote_node: new secondary node to use (for use with
740
        replace_new_secondary mode)
741
    @type iallocator: str or None
742
    @param iallocator: instance allocator plugin to use (for use with
743
                       replace_auto mode)
744
    @type dry_run: bool
745
    @param dry_run: whether to perform a dry run
746

747
    @rtype: int
748
    @return: job id
749

750
    """
751
    query = [
752
      ("mode", mode),
753
      ]
754

    
755
    if disks:
756
      query.append(("disks", ",".join(str(idx) for idx in disks)))
757

    
758
    if remote_node:
759
      query.append(("remote_node", remote_node))
760

    
761
    if iallocator:
762
      query.append(("iallocator", iallocator))
763

    
764
    if dry_run:
765
      query.append(("dry-run", 1))
766

    
767
    return self._SendRequest(HTTP_POST,
768
                             ("/%s/instances/%s/replace-disks" %
769
                              (GANETI_RAPI_VERSION, instance)), query, None)
770

    
771
  def GetJobs(self):
772
    """Gets all jobs for the cluster.
773

774
    @rtype: list of int
775
    @return: job ids for the cluster
776

777
    """
778
    return [int(j["id"])
779
            for j in self._SendRequest(HTTP_GET,
780
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
781
                                       None, None)]
782

    
783
  def GetJobStatus(self, job_id):
784
    """Gets the status of a job.
785

786
    @type job_id: int
787
    @param job_id: job id whose status to query
788

789
    @rtype: dict
790
    @return: job status
791

792
    """
793
    return self._SendRequest(HTTP_GET,
794
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
795
                             None, None)
796

    
797
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
798
    """Waits for job changes.
799

800
    @type job_id: int
801
    @param job_id: Job ID for which to wait
802

803
    """
804
    body = {
805
      "fields": fields,
806
      "previous_job_info": prev_job_info,
807
      "previous_log_serial": prev_log_serial,
808
      }
809

    
810
    return self._SendRequest(HTTP_GET,
811
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
812
                             None, body)
813

    
814
  def CancelJob(self, job_id, dry_run=False):
815
    """Cancels a job.
816

817
    @type job_id: int
818
    @param job_id: id of the job to delete
819
    @type dry_run: bool
820
    @param dry_run: whether to perform a dry run
821

822
    """
823
    query = []
824
    if dry_run:
825
      query.append(("dry-run", 1))
826

    
827
    return self._SendRequest(HTTP_DELETE,
828
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
829
                             query, None)
830

    
831
  def GetNodes(self, bulk=False):
832
    """Gets all nodes in the cluster.
833

834
    @type bulk: bool
835
    @param bulk: whether to return all information about all instances
836

837
    @rtype: list of dict or str
838
    @return: if bulk is true, info about nodes in the cluster,
839
        else list of nodes in the cluster
840

841
    """
842
    query = []
843
    if bulk:
844
      query.append(("bulk", 1))
845

    
846
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
847
                              query, None)
848
    if bulk:
849
      return nodes
850
    else:
851
      return [n["id"] for n in nodes]
852

    
853
  def GetNodeInfo(self, node):
854
    """Gets information about a node.
855

856
    @type node: str
857
    @param node: node whose info to return
858

859
    @rtype: dict
860
    @return: info about the node
861

862
    """
863
    return self._SendRequest(HTTP_GET,
864
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
865
                             None, None)
866

    
867
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
868
                   dry_run=False):
869
    """Evacuates instances from a Ganeti node.
870

871
    @type node: str
872
    @param node: node to evacuate
873
    @type iallocator: str or None
874
    @param iallocator: instance allocator to use
875
    @type remote_node: str
876
    @param remote_node: node to evaucate to
877
    @type dry_run: bool
878
    @param dry_run: whether to perform a dry run
879

880
    @rtype: int
881
    @return: job id
882

883
    @raises GanetiApiError: if an iallocator and remote_node are both specified
884

885
    """
886
    if iallocator and remote_node:
887
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
888

    
889
    query = []
890
    if iallocator:
891
      query.append(("iallocator", iallocator))
892
    if remote_node:
893
      query.append(("remote_node", remote_node))
894
    if dry_run:
895
      query.append(("dry-run", 1))
896

    
897
    return self._SendRequest(HTTP_POST,
898
                             ("/%s/nodes/%s/evacuate" %
899
                              (GANETI_RAPI_VERSION, node)), query, None)
900

    
901
  def MigrateNode(self, node, live=True, dry_run=False):
902
    """Migrates all primary instances from a node.
903

904
    @type node: str
905
    @param node: node to migrate
906
    @type live: bool
907
    @param live: whether to use live migration
908
    @type dry_run: bool
909
    @param dry_run: whether to perform a dry run
910

911
    @rtype: int
912
    @return: job id
913

914
    """
915
    query = []
916
    if live:
917
      query.append(("live", 1))
918
    if dry_run:
919
      query.append(("dry-run", 1))
920

    
921
    return self._SendRequest(HTTP_POST,
922
                             ("/%s/nodes/%s/migrate" %
923
                              (GANETI_RAPI_VERSION, node)), query, None)
924

    
925
  def GetNodeRole(self, node):
926
    """Gets the current role for a node.
927

928
    @type node: str
929
    @param node: node whose role to return
930

931
    @rtype: str
932
    @return: the current role for a node
933

934
    """
935
    return self._SendRequest(HTTP_GET,
936
                             ("/%s/nodes/%s/role" %
937
                              (GANETI_RAPI_VERSION, node)), None, None)
938

    
939
  def SetNodeRole(self, node, role, force=False):
940
    """Sets the role for a node.
941

942
    @type node: str
943
    @param node: the node whose role to set
944
    @type role: str
945
    @param role: the role to set for the node
946
    @type force: bool
947
    @param force: whether to force the role change
948

949
    @rtype: int
950
    @return: job id
951

952
    """
953
    query = [
954
      ("force", force),
955
      ]
956

    
957
    return self._SendRequest(HTTP_PUT,
958
                             ("/%s/nodes/%s/role" %
959
                              (GANETI_RAPI_VERSION, node)), query, role)
960

    
961
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
962
    """Gets the storage units for a node.
963

964
    @type node: str
965
    @param node: the node whose storage units to return
966
    @type storage_type: str
967
    @param storage_type: storage type whose units to return
968
    @type output_fields: str
969
    @param output_fields: storage type fields to return
970

971
    @rtype: int
972
    @return: job id where results can be retrieved
973

974
    """
975
    query = [
976
      ("storage_type", storage_type),
977
      ("output_fields", output_fields),
978
      ]
979

    
980
    return self._SendRequest(HTTP_GET,
981
                             ("/%s/nodes/%s/storage" %
982
                              (GANETI_RAPI_VERSION, node)), query, None)
983

    
984
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
985
    """Modifies parameters of storage units on the node.
986

987
    @type node: str
988
    @param node: node whose storage units to modify
989
    @type storage_type: str
990
    @param storage_type: storage type whose units to modify
991
    @type name: str
992
    @param name: name of the storage unit
993
    @type allocatable: bool or None
994
    @param allocatable: Whether to set the "allocatable" flag on the storage
995
                        unit (None=no modification, True=set, False=unset)
996

997
    @rtype: int
998
    @return: job id
999

1000
    """
1001
    query = [
1002
      ("storage_type", storage_type),
1003
      ("name", name),
1004
      ]
1005

    
1006
    if allocatable is not None:
1007
      query.append(("allocatable", allocatable))
1008

    
1009
    return self._SendRequest(HTTP_PUT,
1010
                             ("/%s/nodes/%s/storage/modify" %
1011
                              (GANETI_RAPI_VERSION, node)), query, None)
1012

    
1013
  def RepairNodeStorageUnits(self, node, storage_type, name):
1014
    """Repairs a storage unit on the node.
1015

1016
    @type node: str
1017
    @param node: node whose storage units to repair
1018
    @type storage_type: str
1019
    @param storage_type: storage type to repair
1020
    @type name: str
1021
    @param name: name of the storage unit to repair
1022

1023
    @rtype: int
1024
    @return: job id
1025

1026
    """
1027
    query = [
1028
      ("storage_type", storage_type),
1029
      ("name", name),
1030
      ]
1031

    
1032
    return self._SendRequest(HTTP_PUT,
1033
                             ("/%s/nodes/%s/storage/repair" %
1034
                              (GANETI_RAPI_VERSION, node)), query, None)
1035

    
1036
  def GetNodeTags(self, node):
1037
    """Gets the tags for a node.
1038

1039
    @type node: str
1040
    @param node: node whose tags to return
1041

1042
    @rtype: list of str
1043
    @return: tags for the node
1044

1045
    """
1046
    return self._SendRequest(HTTP_GET,
1047
                             ("/%s/nodes/%s/tags" %
1048
                              (GANETI_RAPI_VERSION, node)), None, None)
1049

    
1050
  def AddNodeTags(self, node, tags, dry_run=False):
1051
    """Adds tags to a node.
1052

1053
    @type node: str
1054
    @param node: node to add tags to
1055
    @type tags: list of str
1056
    @param tags: tags to add to the node
1057
    @type dry_run: bool
1058
    @param dry_run: whether to perform a dry run
1059

1060
    @rtype: int
1061
    @return: job id
1062

1063
    """
1064
    query = [("tag", t) for t in tags]
1065
    if dry_run:
1066
      query.append(("dry-run", 1))
1067

    
1068
    return self._SendRequest(HTTP_PUT,
1069
                             ("/%s/nodes/%s/tags" %
1070
                              (GANETI_RAPI_VERSION, node)), query, tags)
1071

    
1072
  def DeleteNodeTags(self, node, tags, dry_run=False):
1073
    """Delete tags from a node.
1074

1075
    @type node: str
1076
    @param node: node to remove tags from
1077
    @type tags: list of str
1078
    @param tags: tags to remove from the node
1079
    @type dry_run: bool
1080
    @param dry_run: whether to perform a dry run
1081

1082
    @rtype: int
1083
    @return: job id
1084

1085
    """
1086
    query = [("tag", t) for t in tags]
1087
    if dry_run:
1088
      query.append(("dry-run", 1))
1089

    
1090
    return self._SendRequest(HTTP_DELETE,
1091
                             ("/%s/nodes/%s/tags" %
1092
                              (GANETI_RAPI_VERSION, node)), query, None)