Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ a01b500b

History | View | Annotate | Download (34 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
# Internal constants
60
_REQ_DATA_VERSION_FIELD = "__version__"
61
_INST_CREATE_REQV1 = "instance-create-reqv1"
62

    
63

    
64
class Error(Exception):
65
  """Base error class for this module.
66

67
  """
68
  pass
69

    
70

    
71
class CertificateError(Error):
72
  """Raised when a problem is found with the SSL certificate.
73

74
  """
75
  pass
76

    
77

    
78
class GanetiApiError(Error):
79
  """Generic error raised from Ganeti API.
80

81
  """
82
  def __init__(self, msg, code=None):
83
    Error.__init__(self, msg)
84
    self.code = code
85

    
86

    
87
def FormatX509Name(x509_name):
88
  """Formats an X509 name.
89

90
  @type x509_name: OpenSSL.crypto.X509Name
91

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

    
102

    
103
class CertAuthorityVerify:
104
  """Certificate verificator for SSL context.
105

106
  Configures SSL context to verify server's certificate.
107

108
  """
109
  _CAPATH_MINVERSION = "0.9"
110
  _DEFVFYPATHS_MINVERSION = "0.9"
111

    
112
  _PYOPENSSL_VERSION = OpenSSL.__version__
113
  _PARSED_PYOPENSSL_VERSION = distutils.version.LooseVersion(_PYOPENSSL_VERSION)
114

    
115
  _SUPPORT_CAPATH = (_PARSED_PYOPENSSL_VERSION >= _CAPATH_MINVERSION)
116
  _SUPPORT_DEFVFYPATHS = (_PARSED_PYOPENSSL_VERSION >= _DEFVFYPATHS_MINVERSION)
117

    
118
  def __init__(self, cafile=None, capath=None, use_default_verify_paths=False):
119
    """Initializes this class.
120

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

130
    """
131
    self._cafile = cafile
132
    self._capath = capath
133
    self._use_default_verify_paths = use_default_verify_paths
134

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

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

    
145
  @staticmethod
146
  def _VerifySslCertCb(logger, _, cert, errnum, errdepth, ok):
147
    """Callback for SSL certificate verification.
148

149
    @param logger: Logging object
150

151
    """
152
    if ok:
153
      log_fn = logger.debug
154
    else:
155
      log_fn = logger.error
156

    
157
    log_fn("Verifying SSL certificate at depth %s, subject '%s', issuer '%s'",
158
           errdepth, FormatX509Name(cert.get_subject()),
159
           FormatX509Name(cert.get_issuer()))
160

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

    
171
      logger.error("verify error:num=%s%s", errnum, errmsg)
172

    
173
    return ok
174

    
175
  def __call__(self, ctx, logger):
176
    """Configures an SSL context to verify certificates.
177

178
    @type ctx: OpenSSL.SSL.Context
179
    @param ctx: SSL context
180

181
    """
182
    if self._use_default_verify_paths:
183
      ctx.set_default_verify_paths()
184

    
185
    if self._cafile or self._capath:
186
      if self._SUPPORT_CAPATH:
187
        ctx.load_verify_locations(self._cafile, self._capath)
188
      else:
189
        ctx.load_verify_locations(self._cafile)
190

    
191
    ctx.set_verify(OpenSSL.SSL.VERIFY_PEER,
192
                   lambda conn, cert, errnum, errdepth, ok: \
193
                     self._VerifySslCertCb(logger, conn, cert,
194
                                           errnum, errdepth, ok))
195

    
196

    
197
class _HTTPSConnectionOpenSSL(httplib.HTTPSConnection):
198
  """HTTPS Connection handler that verifies the SSL certificate.
199

200
  """
201
  def __init__(self, *args, **kwargs):
202
    """Initializes this class.
203

204
    """
205
    httplib.HTTPSConnection.__init__(self, *args, **kwargs)
206
    self._logger = None
207
    self._config_ssl_verification = None
208

    
209
  def Setup(self, logger, config_ssl_verification):
210
    """Sets the SSL verification config function.
211

212
    @param logger: Logging object
213
    @type config_ssl_verification: callable
214

215
    """
216
    assert self._logger is None
217
    assert self._config_ssl_verification is None
218

    
219
    self._logger = logger
220
    self._config_ssl_verification = config_ssl_verification
221

    
222
  def connect(self):
223
    """Connect to the server specified when the object was created.
224

225
    This ensures that SSL certificates are verified.
226

227
    """
228
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
229

    
230
    ctx = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
231
    ctx.set_options(OpenSSL.SSL.OP_NO_SSLv2)
232

    
233
    if self._config_ssl_verification:
234
      self._config_ssl_verification(ctx, self._logger)
235

    
236
    ssl = OpenSSL.SSL.Connection(ctx, sock)
237
    ssl.connect((self.host, self.port))
238

    
239
    self.sock = httplib.FakeSocket(sock, ssl)
240

    
241

    
242
class _HTTPSHandler(urllib2.HTTPSHandler):
243
  def __init__(self, logger, config_ssl_verification):
244
    """Initializes this class.
245

246
    @param logger: Logging object
247
    @type config_ssl_verification: callable
248
    @param config_ssl_verification: Function to configure SSL context for
249
                                    certificate verification
250

251
    """
252
    urllib2.HTTPSHandler.__init__(self)
253
    self._logger = logger
254
    self._config_ssl_verification = config_ssl_verification
255

    
256
  def _CreateHttpsConnection(self, *args, **kwargs):
257
    """Wrapper around L{_HTTPSConnectionOpenSSL} to add SSL verification.
258

259
    This wrapper is necessary provide a compatible API to urllib2.
260

261
    """
262
    conn = _HTTPSConnectionOpenSSL(*args, **kwargs)
263
    conn.Setup(self._logger, self._config_ssl_verification)
264
    return conn
265

    
266
  def https_open(self, req):
267
    """Creates HTTPS connection.
268

269
    Called by urllib2.
270

271
    """
272
    return self.do_open(self._CreateHttpsConnection, req)
273

    
274

    
275
class _RapiRequest(urllib2.Request):
276
  def __init__(self, method, url, headers, data):
277
    """Initializes this class.
278

279
    """
280
    urllib2.Request.__init__(self, url, data=data, headers=headers)
281
    self._method = method
282

    
283
  def get_method(self):
284
    """Returns the HTTP request method.
285

286
    """
287
    return self._method
288

    
289

    
290
class GanetiRapiClient(object):
291
  """Ganeti RAPI client.
292

293
  """
294
  USER_AGENT = "Ganeti RAPI Client"
295
  _json_encoder = simplejson.JSONEncoder(sort_keys=True)
296

    
297
  def __init__(self, host, port=GANETI_RAPI_PORT,
298
               username=None, password=None,
299
               config_ssl_verification=None, ignore_proxy=False,
300
               logger=logging):
301
    """Constructor.
302

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

318
    """
319
    self._host = host
320
    self._port = port
321
    self._logger = logger
322

    
323
    self._base_url = "https://%s:%s" % (host, port)
324

    
325
    handlers = [_HTTPSHandler(self._logger, config_ssl_verification)]
326

    
327
    if username is not None:
328
      pwmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
329
      pwmgr.add_password(None, self._base_url, username, password)
330
      handlers.append(urllib2.HTTPBasicAuthHandler(pwmgr))
331
    elif password:
332
      raise Error("Specified password without username")
333

    
334
    if ignore_proxy:
335
      handlers.append(urllib2.ProxyHandler({}))
336

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

    
339
    self._headers = {
340
      "Accept": HTTP_APP_JSON,
341
      "Content-type": HTTP_APP_JSON,
342
      "User-Agent": self.USER_AGENT,
343
      }
344

    
345
  @staticmethod
346
  def _EncodeQuery(query):
347
    """Encode query values for RAPI URL.
348

349
    @type query: list of two-tuples
350
    @param query: Query arguments
351
    @rtype: list
352
    @return: Query list with encoded values
353

354
    """
355
    result = []
356

    
357
    for name, value in query:
358
      if value is None:
359
        result.append((name, ""))
360

    
361
      elif isinstance(value, bool):
362
        # Boolean values must be encoded as 0 or 1
363
        result.append((name, int(value)))
364

    
365
      elif isinstance(value, (list, tuple, dict)):
366
        raise ValueError("Invalid query data type %r" % type(value).__name__)
367

    
368
      else:
369
        result.append((name, value))
370

    
371
    return result
372

    
373
  def _SendRequest(self, method, path, query, content):
374
    """Sends an HTTP request.
375

376
    This constructs a full URL, encodes and decodes HTTP bodies, and
377
    handles invalid responses in a pythonic way.
378

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

388
    @rtype: str
389
    @return: JSON-Decoded response
390

391
    @raises CertificateError: If an invalid SSL certificate is found
392
    @raises GanetiApiError: If an invalid response is returned
393

394
    """
395
    assert path.startswith("/")
396

    
397
    if content:
398
      encoded_content = self._json_encoder.encode(content)
399
    else:
400
      encoded_content = None
401

    
402
    # Build URL
403
    urlparts = [self._base_url, path]
404
    if query:
405
      urlparts.append("?")
406
      urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
407

    
408
    url = "".join(urlparts)
409

    
410
    self._logger.debug("Sending request %s %s to %s:%s"
411
                       " (headers=%r, content=%r)",
412
                       method, url, self._host, self._port, self._headers,
413
                       encoded_content)
414

    
415
    req = _RapiRequest(method, url, self._headers, encoded_content)
416

    
417
    try:
418
      resp = self._http.open(req)
419
      encoded_response_content = resp.read()
420
    except (OpenSSL.SSL.Error, OpenSSL.crypto.Error), err:
421
      raise CertificateError("SSL issue: %s (%r)" % (err, err))
422
    except urllib2.HTTPError, err:
423
      raise GanetiApiError(str(err), code=err.code)
424
    except urllib2.URLError, err:
425
      raise GanetiApiError(str(err))
426

    
427
    if encoded_response_content:
428
      response_content = simplejson.loads(encoded_response_content)
429
    else:
430
      response_content = None
431

    
432
    # TODO: Are there other status codes that are valid? (redirect?)
433
    if resp.code != HTTP_OK:
434
      if isinstance(response_content, dict):
435
        msg = ("%s %s: %s" %
436
               (response_content["code"],
437
                response_content["message"],
438
                response_content["explain"]))
439
      else:
440
        msg = str(response_content)
441

    
442
      raise GanetiApiError(msg, code=resp.code)
443

    
444
    return response_content
445

    
446
  def GetVersion(self):
447
    """Gets the Remote API version running on the cluster.
448

449
    @rtype: int
450
    @return: Ganeti Remote API version
451

452
    """
453
    return self._SendRequest(HTTP_GET, "/version", None, None)
454

    
455
  def GetFeatures(self):
456
    """Gets the list of optional features supported by RAPI server.
457

458
    @rtype: list
459
    @return: List of optional features
460

461
    """
462
    try:
463
      return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
464
                               None, None)
465
    except GanetiApiError, err:
466
      # Older RAPI servers don't support this resource
467
      if err.code == HTTP_NOT_FOUND:
468
        return []
469

    
470
      raise
471

    
472
  def GetOperatingSystems(self):
473
    """Gets the Operating Systems running in the Ganeti cluster.
474

475
    @rtype: list of str
476
    @return: operating systems
477

478
    """
479
    return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
480
                             None, None)
481

    
482
  def GetInfo(self):
483
    """Gets info about the cluster.
484

485
    @rtype: dict
486
    @return: information about the cluster
487

488
    """
489
    return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
490
                             None, None)
491

    
492
  def GetClusterTags(self):
493
    """Gets the cluster tags.
494

495
    @rtype: list of str
496
    @return: cluster tags
497

498
    """
499
    return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
500
                             None, None)
501

    
502
  def AddClusterTags(self, tags, dry_run=False):
503
    """Adds tags to the cluster.
504

505
    @type tags: list of str
506
    @param tags: tags to add to the cluster
507
    @type dry_run: bool
508
    @param dry_run: whether to perform a dry run
509

510
    @rtype: int
511
    @return: job id
512

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

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

    
521
  def DeleteClusterTags(self, tags, dry_run=False):
522
    """Deletes tags from the cluster.
523

524
    @type tags: list of str
525
    @param tags: tags to delete
526
    @type dry_run: bool
527
    @param dry_run: whether to perform a dry run
528

529
    """
530
    query = [("tag", t) for t in tags]
531
    if dry_run:
532
      query.append(("dry-run", 1))
533

    
534
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
535
                             query, None)
536

    
537
  def GetInstances(self, bulk=False):
538
    """Gets information about instances on the cluster.
539

540
    @type bulk: bool
541
    @param bulk: whether to return all information about all instances
542

543
    @rtype: list of dict or list of str
544
    @return: if bulk is True, info about the instances, else a list of instances
545

546
    """
547
    query = []
548
    if bulk:
549
      query.append(("bulk", 1))
550

    
551
    instances = self._SendRequest(HTTP_GET,
552
                                  "/%s/instances" % GANETI_RAPI_VERSION,
553
                                  query, None)
554
    if bulk:
555
      return instances
556
    else:
557
      return [i["id"] for i in instances]
558

    
559
  def GetInstance(self, instance):
560
    """Gets information about an instance.
561

562
    @type instance: str
563
    @param instance: instance whose info to return
564

565
    @rtype: dict
566
    @return: info about the instance
567

568
    """
569
    return self._SendRequest(HTTP_GET,
570
                             ("/%s/instances/%s" %
571
                              (GANETI_RAPI_VERSION, instance)), None, None)
572

    
573
  def GetInstanceInfo(self, instance, static=None):
574
    """Gets information about an instance.
575

576
    @type instance: string
577
    @param instance: Instance name
578
    @rtype: string
579
    @return: Job ID
580

581
    """
582
    if static is not None:
583
      query = [("static", static)]
584
    else:
585
      query = None
586

    
587
    return self._SendRequest(HTTP_GET,
588
                             ("/%s/instances/%s/info" %
589
                              (GANETI_RAPI_VERSION, instance)), query, None)
590

    
591
  def CreateInstance(self, mode, name, disk_template, disks, nics,
592
                     **kwargs):
593
    """Creates a new instance.
594

595
    More details for parameters can be found in the RAPI documentation.
596

597
    @type mode: string
598
    @param mode: Instance creation mode
599
    @type name: string
600
    @param name: Hostname of the instance to create
601
    @type disk_template: string
602
    @param disk_template: Disk template for instance (e.g. plain, diskless,
603
                          file, or drbd)
604
    @type disks: list of dicts
605
    @param disks: List of disk definitions
606
    @type nics: list of dicts
607
    @param nics: List of NIC definitions
608
    @type dry_run: bool
609
    @keyword dry_run: whether to perform a dry run
610

611
    @rtype: int
612
    @return: job id
613

614
    """
615
    query = []
616

    
617
    if kwargs.get("dry_run"):
618
      query.append(("dry-run", 1))
619

    
620
    if _INST_CREATE_REQV1 in self.GetFeatures():
621
      # All required fields for request data version 1
622
      body = {
623
        _REQ_DATA_VERSION_FIELD: 1,
624
        "mode": mode,
625
        "name": name,
626
        "disk_template": disk_template,
627
        "disks": disks,
628
        "nics": nics,
629
        }
630

    
631
      conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
632
      if conflicts:
633
        raise GanetiApiError("Required fields can not be specified as"
634
                             " keywords: %s" % ", ".join(conflicts))
635

    
636
      body.update((key, value) for key, value in kwargs.iteritems()
637
                  if key != "dry_run")
638
    else:
639
      # TODO: Implement instance creation request data version 0
640
      # When implementing version 0, care should be taken to refuse unknown
641
      # parameters and invalid values. The interface of this function must stay
642
      # exactly the same for version 0 and 1 (e.g. they aren't allowed to
643
      # require different data types).
644
      raise NotImplementedError("Support for instance creation request data"
645
                                " version 0 is not yet implemented")
646

    
647
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
648
                             query, body)
649

    
650
  def DeleteInstance(self, instance, dry_run=False):
651
    """Deletes an instance.
652

653
    @type instance: str
654
    @param instance: the instance to delete
655

656
    @rtype: int
657
    @return: job id
658

659
    """
660
    query = []
661
    if dry_run:
662
      query.append(("dry-run", 1))
663

    
664
    return self._SendRequest(HTTP_DELETE,
665
                             ("/%s/instances/%s" %
666
                              (GANETI_RAPI_VERSION, instance)), query, None)
667

    
668
  def GetInstanceTags(self, instance):
669
    """Gets tags for an instance.
670

671
    @type instance: str
672
    @param instance: instance whose tags to return
673

674
    @rtype: list of str
675
    @return: tags for the instance
676

677
    """
678
    return self._SendRequest(HTTP_GET,
679
                             ("/%s/instances/%s/tags" %
680
                              (GANETI_RAPI_VERSION, instance)), None, None)
681

    
682
  def AddInstanceTags(self, instance, tags, dry_run=False):
683
    """Adds tags to an instance.
684

685
    @type instance: str
686
    @param instance: instance to add tags to
687
    @type tags: list of str
688
    @param tags: tags to add to the instance
689
    @type dry_run: bool
690
    @param dry_run: whether to perform a dry run
691

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

695
    """
696
    query = [("tag", t) for t in tags]
697
    if dry_run:
698
      query.append(("dry-run", 1))
699

    
700
    return self._SendRequest(HTTP_PUT,
701
                             ("/%s/instances/%s/tags" %
702
                              (GANETI_RAPI_VERSION, instance)), query, None)
703

    
704
  def DeleteInstanceTags(self, instance, tags, dry_run=False):
705
    """Deletes tags from an instance.
706

707
    @type instance: str
708
    @param instance: instance to delete tags from
709
    @type tags: list of str
710
    @param tags: tags to delete
711
    @type dry_run: bool
712
    @param dry_run: whether to perform a dry run
713

714
    """
715
    query = [("tag", t) for t in tags]
716
    if dry_run:
717
      query.append(("dry-run", 1))
718

    
719
    return self._SendRequest(HTTP_DELETE,
720
                             ("/%s/instances/%s/tags" %
721
                              (GANETI_RAPI_VERSION, instance)), query, None)
722

    
723
  def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
724
                     dry_run=False):
725
    """Reboots an instance.
726

727
    @type instance: str
728
    @param instance: instance to rebot
729
    @type reboot_type: str
730
    @param reboot_type: one of: hard, soft, full
731
    @type ignore_secondaries: bool
732
    @param ignore_secondaries: if True, ignores errors for the secondary node
733
        while re-assembling disks (in hard-reboot mode only)
734
    @type dry_run: bool
735
    @param dry_run: whether to perform a dry run
736

737
    """
738
    query = []
739
    if reboot_type:
740
      query.append(("type", reboot_type))
741
    if ignore_secondaries is not None:
742
      query.append(("ignore_secondaries", ignore_secondaries))
743
    if dry_run:
744
      query.append(("dry-run", 1))
745

    
746
    return self._SendRequest(HTTP_POST,
747
                             ("/%s/instances/%s/reboot" %
748
                              (GANETI_RAPI_VERSION, instance)), query, None)
749

    
750
  def ShutdownInstance(self, instance, dry_run=False):
751
    """Shuts down an instance.
752

753
    @type instance: str
754
    @param instance: the instance to shut down
755
    @type dry_run: bool
756
    @param dry_run: whether to perform a dry run
757

758
    """
759
    query = []
760
    if dry_run:
761
      query.append(("dry-run", 1))
762

    
763
    return self._SendRequest(HTTP_PUT,
764
                             ("/%s/instances/%s/shutdown" %
765
                              (GANETI_RAPI_VERSION, instance)), query, None)
766

    
767
  def StartupInstance(self, instance, dry_run=False):
768
    """Starts up an instance.
769

770
    @type instance: str
771
    @param instance: the instance to start up
772
    @type dry_run: bool
773
    @param dry_run: whether to perform a dry run
774

775
    """
776
    query = []
777
    if dry_run:
778
      query.append(("dry-run", 1))
779

    
780
    return self._SendRequest(HTTP_PUT,
781
                             ("/%s/instances/%s/startup" %
782
                              (GANETI_RAPI_VERSION, instance)), query, None)
783

    
784
  def ReinstallInstance(self, instance, os, no_startup=False):
785
    """Reinstalls an instance.
786

787
    @type instance: str
788
    @param instance: the instance to reinstall
789
    @type os: str
790
    @param os: the os to reinstall
791
    @type no_startup: bool
792
    @param no_startup: whether to start the instance automatically
793

794
    """
795
    query = [("os", os)]
796
    if no_startup:
797
      query.append(("nostartup", 1))
798
    return self._SendRequest(HTTP_POST,
799
                             ("/%s/instances/%s/reinstall" %
800
                              (GANETI_RAPI_VERSION, instance)), query, None)
801

    
802
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
803
                           remote_node=None, iallocator=None, dry_run=False):
804
    """Replaces disks on an instance.
805

806
    @type instance: str
807
    @param instance: instance whose disks to replace
808
    @type disks: list of ints
809
    @param disks: Indexes of disks to replace
810
    @type mode: str
811
    @param mode: replacement mode to use (defaults to replace_auto)
812
    @type remote_node: str or None
813
    @param remote_node: new secondary node to use (for use with
814
        replace_new_secondary mode)
815
    @type iallocator: str or None
816
    @param iallocator: instance allocator plugin to use (for use with
817
                       replace_auto mode)
818
    @type dry_run: bool
819
    @param dry_run: whether to perform a dry run
820

821
    @rtype: int
822
    @return: job id
823

824
    """
825
    query = [
826
      ("mode", mode),
827
      ]
828

    
829
    if disks:
830
      query.append(("disks", ",".join(str(idx) for idx in disks)))
831

    
832
    if remote_node:
833
      query.append(("remote_node", remote_node))
834

    
835
    if iallocator:
836
      query.append(("iallocator", iallocator))
837

    
838
    if dry_run:
839
      query.append(("dry-run", 1))
840

    
841
    return self._SendRequest(HTTP_POST,
842
                             ("/%s/instances/%s/replace-disks" %
843
                              (GANETI_RAPI_VERSION, instance)), query, None)
844

    
845
  def PrepareExport(self, instance, mode):
846
    """Prepares an instance for an export.
847

848
    @type instance: string
849
    @param instance: Instance name
850
    @type mode: string
851
    @param mode: Export mode
852
    @rtype: string
853
    @return: Job ID
854

855
    """
856
    query = [("mode", mode)]
857
    return self._SendRequest(HTTP_PUT,
858
                             ("/%s/instances/%s/prepare-export" %
859
                              (GANETI_RAPI_VERSION, instance)), query, None)
860

    
861
  def ExportInstance(self, instance, mode, destination, shutdown=None,
862
                     remove_instance=None,
863
                     x509_key_name=None, destination_x509_ca=None):
864
    """Exports an instance.
865

866
    @type instance: string
867
    @param instance: Instance name
868
    @type mode: string
869
    @param mode: Export mode
870
    @rtype: string
871
    @return: Job ID
872

873
    """
874
    body = {
875
      "destination": destination,
876
      "mode": mode,
877
      }
878

    
879
    if shutdown is not None:
880
      body["shutdown"] = shutdown
881

    
882
    if remove_instance is not None:
883
      body["remove_instance"] = remove_instance
884

    
885
    if x509_key_name is not None:
886
      body["x509_key_name"] = x509_key_name
887

    
888
    if destination_x509_ca is not None:
889
      body["destination_x509_ca"] = destination_x509_ca
890

    
891
    return self._SendRequest(HTTP_PUT,
892
                             ("/%s/instances/%s/export" %
893
                              (GANETI_RAPI_VERSION, instance)), None, body)
894

    
895
  def GetJobs(self):
896
    """Gets all jobs for the cluster.
897

898
    @rtype: list of int
899
    @return: job ids for the cluster
900

901
    """
902
    return [int(j["id"])
903
            for j in self._SendRequest(HTTP_GET,
904
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
905
                                       None, None)]
906

    
907
  def GetJobStatus(self, job_id):
908
    """Gets the status of a job.
909

910
    @type job_id: int
911
    @param job_id: job id whose status to query
912

913
    @rtype: dict
914
    @return: job status
915

916
    """
917
    return self._SendRequest(HTTP_GET,
918
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
919
                             None, None)
920

    
921
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
922
    """Waits for job changes.
923

924
    @type job_id: int
925
    @param job_id: Job ID for which to wait
926

927
    """
928
    body = {
929
      "fields": fields,
930
      "previous_job_info": prev_job_info,
931
      "previous_log_serial": prev_log_serial,
932
      }
933

    
934
    return self._SendRequest(HTTP_GET,
935
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
936
                             None, body)
937

    
938
  def CancelJob(self, job_id, dry_run=False):
939
    """Cancels a job.
940

941
    @type job_id: int
942
    @param job_id: id of the job to delete
943
    @type dry_run: bool
944
    @param dry_run: whether to perform a dry run
945

946
    """
947
    query = []
948
    if dry_run:
949
      query.append(("dry-run", 1))
950

    
951
    return self._SendRequest(HTTP_DELETE,
952
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
953
                             query, None)
954

    
955
  def GetNodes(self, bulk=False):
956
    """Gets all nodes in the cluster.
957

958
    @type bulk: bool
959
    @param bulk: whether to return all information about all instances
960

961
    @rtype: list of dict or str
962
    @return: if bulk is true, info about nodes in the cluster,
963
        else list of nodes in the cluster
964

965
    """
966
    query = []
967
    if bulk:
968
      query.append(("bulk", 1))
969

    
970
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
971
                              query, None)
972
    if bulk:
973
      return nodes
974
    else:
975
      return [n["id"] for n in nodes]
976

    
977
  def GetNode(self, node):
978
    """Gets information about a node.
979

980
    @type node: str
981
    @param node: node whose info to return
982

983
    @rtype: dict
984
    @return: info about the node
985

986
    """
987
    return self._SendRequest(HTTP_GET,
988
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
989
                             None, None)
990

    
991
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
992
                   dry_run=False):
993
    """Evacuates instances from a Ganeti node.
994

995
    @type node: str
996
    @param node: node to evacuate
997
    @type iallocator: str or None
998
    @param iallocator: instance allocator to use
999
    @type remote_node: str
1000
    @param remote_node: node to evaucate to
1001
    @type dry_run: bool
1002
    @param dry_run: whether to perform a dry run
1003

1004
    @rtype: int
1005
    @return: job id
1006

1007
    @raises GanetiApiError: if an iallocator and remote_node are both specified
1008

1009
    """
1010
    if iallocator and remote_node:
1011
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1012

    
1013
    query = []
1014
    if iallocator:
1015
      query.append(("iallocator", iallocator))
1016
    if remote_node:
1017
      query.append(("remote_node", remote_node))
1018
    if dry_run:
1019
      query.append(("dry-run", 1))
1020

    
1021
    return self._SendRequest(HTTP_POST,
1022
                             ("/%s/nodes/%s/evacuate" %
1023
                              (GANETI_RAPI_VERSION, node)), query, None)
1024

    
1025
  def MigrateNode(self, node, live=True, dry_run=False):
1026
    """Migrates all primary instances from a node.
1027

1028
    @type node: str
1029
    @param node: node to migrate
1030
    @type live: bool
1031
    @param live: whether to use live migration
1032
    @type dry_run: bool
1033
    @param dry_run: whether to perform a dry run
1034

1035
    @rtype: int
1036
    @return: job id
1037

1038
    """
1039
    query = []
1040
    if live:
1041
      query.append(("live", 1))
1042
    if dry_run:
1043
      query.append(("dry-run", 1))
1044

    
1045
    return self._SendRequest(HTTP_POST,
1046
                             ("/%s/nodes/%s/migrate" %
1047
                              (GANETI_RAPI_VERSION, node)), query, None)
1048

    
1049
  def GetNodeRole(self, node):
1050
    """Gets the current role for a node.
1051

1052
    @type node: str
1053
    @param node: node whose role to return
1054

1055
    @rtype: str
1056
    @return: the current role for a node
1057

1058
    """
1059
    return self._SendRequest(HTTP_GET,
1060
                             ("/%s/nodes/%s/role" %
1061
                              (GANETI_RAPI_VERSION, node)), None, None)
1062

    
1063
  def SetNodeRole(self, node, role, force=False):
1064
    """Sets the role for a node.
1065

1066
    @type node: str
1067
    @param node: the node whose role to set
1068
    @type role: str
1069
    @param role: the role to set for the node
1070
    @type force: bool
1071
    @param force: whether to force the role change
1072

1073
    @rtype: int
1074
    @return: job id
1075

1076
    """
1077
    query = [
1078
      ("force", force),
1079
      ]
1080

    
1081
    return self._SendRequest(HTTP_PUT,
1082
                             ("/%s/nodes/%s/role" %
1083
                              (GANETI_RAPI_VERSION, node)), query, role)
1084

    
1085
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1086
    """Gets the storage units for a node.
1087

1088
    @type node: str
1089
    @param node: the node whose storage units to return
1090
    @type storage_type: str
1091
    @param storage_type: storage type whose units to return
1092
    @type output_fields: str
1093
    @param output_fields: storage type fields to return
1094

1095
    @rtype: int
1096
    @return: job id where results can be retrieved
1097

1098
    """
1099
    query = [
1100
      ("storage_type", storage_type),
1101
      ("output_fields", output_fields),
1102
      ]
1103

    
1104
    return self._SendRequest(HTTP_GET,
1105
                             ("/%s/nodes/%s/storage" %
1106
                              (GANETI_RAPI_VERSION, node)), query, None)
1107

    
1108
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1109
    """Modifies parameters of storage units on the node.
1110

1111
    @type node: str
1112
    @param node: node whose storage units to modify
1113
    @type storage_type: str
1114
    @param storage_type: storage type whose units to modify
1115
    @type name: str
1116
    @param name: name of the storage unit
1117
    @type allocatable: bool or None
1118
    @param allocatable: Whether to set the "allocatable" flag on the storage
1119
                        unit (None=no modification, True=set, False=unset)
1120

1121
    @rtype: int
1122
    @return: job id
1123

1124
    """
1125
    query = [
1126
      ("storage_type", storage_type),
1127
      ("name", name),
1128
      ]
1129

    
1130
    if allocatable is not None:
1131
      query.append(("allocatable", allocatable))
1132

    
1133
    return self._SendRequest(HTTP_PUT,
1134
                             ("/%s/nodes/%s/storage/modify" %
1135
                              (GANETI_RAPI_VERSION, node)), query, None)
1136

    
1137
  def RepairNodeStorageUnits(self, node, storage_type, name):
1138
    """Repairs a storage unit on the node.
1139

1140
    @type node: str
1141
    @param node: node whose storage units to repair
1142
    @type storage_type: str
1143
    @param storage_type: storage type to repair
1144
    @type name: str
1145
    @param name: name of the storage unit to repair
1146

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

1150
    """
1151
    query = [
1152
      ("storage_type", storage_type),
1153
      ("name", name),
1154
      ]
1155

    
1156
    return self._SendRequest(HTTP_PUT,
1157
                             ("/%s/nodes/%s/storage/repair" %
1158
                              (GANETI_RAPI_VERSION, node)), query, None)
1159

    
1160
  def GetNodeTags(self, node):
1161
    """Gets the tags for a node.
1162

1163
    @type node: str
1164
    @param node: node whose tags to return
1165

1166
    @rtype: list of str
1167
    @return: tags for the node
1168

1169
    """
1170
    return self._SendRequest(HTTP_GET,
1171
                             ("/%s/nodes/%s/tags" %
1172
                              (GANETI_RAPI_VERSION, node)), None, None)
1173

    
1174
  def AddNodeTags(self, node, tags, dry_run=False):
1175
    """Adds tags to a node.
1176

1177
    @type node: str
1178
    @param node: node to add tags to
1179
    @type tags: list of str
1180
    @param tags: tags to add to the node
1181
    @type dry_run: bool
1182
    @param dry_run: whether to perform a dry run
1183

1184
    @rtype: int
1185
    @return: job id
1186

1187
    """
1188
    query = [("tag", t) for t in tags]
1189
    if dry_run:
1190
      query.append(("dry-run", 1))
1191

    
1192
    return self._SendRequest(HTTP_PUT,
1193
                             ("/%s/nodes/%s/tags" %
1194
                              (GANETI_RAPI_VERSION, node)), query, tags)
1195

    
1196
  def DeleteNodeTags(self, node, tags, dry_run=False):
1197
    """Delete tags from a node.
1198

1199
    @type node: str
1200
    @param node: node to remove tags from
1201
    @type tags: list of str
1202
    @param tags: tags to remove from the node
1203
    @type dry_run: bool
1204
    @param dry_run: whether to perform a dry run
1205

1206
    @rtype: int
1207
    @return: job id
1208

1209
    """
1210
    query = [("tag", t) for t in tags]
1211
    if dry_run:
1212
      query.append(("dry-run", 1))
1213

    
1214
    return self._SendRequest(HTTP_DELETE,
1215
                             ("/%s/nodes/%s/tags" %
1216
                              (GANETI_RAPI_VERSION, node)), query, None)