Statistics
| Branch: | Tag: | Revision:

root / lib / rapi / client.py @ b7a1c816

History | View | Annotate | Download (49.8 kB)

1
#
2
#
3

    
4
# Copyright (C) 2010, 2011 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 socket
39
import urllib
40
import threading
41
import pycurl
42
import time
43

    
44
try:
45
  from cStringIO import StringIO
46
except ImportError:
47
  from StringIO import StringIO
48

    
49

    
50
GANETI_RAPI_PORT = 5080
51
GANETI_RAPI_VERSION = 2
52

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

    
61
REPLACE_DISK_PRI = "replace_on_primary"
62
REPLACE_DISK_SECONDARY = "replace_on_secondary"
63
REPLACE_DISK_CHG = "replace_new_secondary"
64
REPLACE_DISK_AUTO = "replace_auto"
65

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

    
72
JOB_STATUS_QUEUED = "queued"
73
JOB_STATUS_WAITLOCK = "waiting"
74
JOB_STATUS_CANCELING = "canceling"
75
JOB_STATUS_RUNNING = "running"
76
JOB_STATUS_CANCELED = "canceled"
77
JOB_STATUS_SUCCESS = "success"
78
JOB_STATUS_ERROR = "error"
79
JOB_STATUS_FINALIZED = frozenset([
80
  JOB_STATUS_CANCELED,
81
  JOB_STATUS_SUCCESS,
82
  JOB_STATUS_ERROR,
83
  ])
84
JOB_STATUS_ALL = frozenset([
85
  JOB_STATUS_QUEUED,
86
  JOB_STATUS_WAITLOCK,
87
  JOB_STATUS_CANCELING,
88
  JOB_STATUS_RUNNING,
89
  ]) | JOB_STATUS_FINALIZED
90

    
91
# Internal constants
92
_REQ_DATA_VERSION_FIELD = "__version__"
93
_INST_CREATE_REQV1 = "instance-create-reqv1"
94
_INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
95
_NODE_MIGRATE_REQV1 = "node-migrate-reqv1"
96
_INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link"])
97
_INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
98
_INST_CREATE_V0_PARAMS = frozenset([
99
  "os", "pnode", "snode", "iallocator", "start", "ip_check", "name_check",
100
  "hypervisor", "file_storage_dir", "file_driver", "dry_run",
101
  ])
102
_INST_CREATE_V0_DPARAMS = frozenset(["beparams", "hvparams"])
103

    
104
# Older pycURL versions don't have all error constants
105
try:
106
  _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
107
  _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
108
except AttributeError:
109
  _CURLE_SSL_CACERT = 60
110
  _CURLE_SSL_CACERT_BADFILE = 77
111

    
112
_CURL_SSL_CERT_ERRORS = frozenset([
113
  _CURLE_SSL_CACERT,
114
  _CURLE_SSL_CACERT_BADFILE,
115
  ])
116

    
117

    
118
class Error(Exception):
119
  """Base error class for this module.
120

121
  """
122
  pass
123

    
124

    
125
class CertificateError(Error):
126
  """Raised when a problem is found with the SSL certificate.
127

128
  """
129
  pass
130

    
131

    
132
class GanetiApiError(Error):
133
  """Generic error raised from Ganeti API.
134

135
  """
136
  def __init__(self, msg, code=None):
137
    Error.__init__(self, msg)
138
    self.code = code
139

    
140

    
141
def UsesRapiClient(fn):
142
  """Decorator for code using RAPI client to initialize pycURL.
143

144
  """
145
  def wrapper(*args, **kwargs):
146
    # curl_global_init(3) and curl_global_cleanup(3) must be called with only
147
    # one thread running. This check is just a safety measure -- it doesn't
148
    # cover all cases.
149
    assert threading.activeCount() == 1, \
150
           "Found active threads when initializing pycURL"
151

    
152
    pycurl.global_init(pycurl.GLOBAL_ALL)
153
    try:
154
      return fn(*args, **kwargs)
155
    finally:
156
      pycurl.global_cleanup()
157

    
158
  return wrapper
159

    
160

    
161
def GenericCurlConfig(verbose=False, use_signal=False,
162
                      use_curl_cabundle=False, cafile=None, capath=None,
163
                      proxy=None, verify_hostname=False,
164
                      connect_timeout=None, timeout=None,
165
                      _pycurl_version_fn=pycurl.version_info):
166
  """Curl configuration function generator.
167

168
  @type verbose: bool
169
  @param verbose: Whether to set cURL to verbose mode
170
  @type use_signal: bool
171
  @param use_signal: Whether to allow cURL to use signals
172
  @type use_curl_cabundle: bool
173
  @param use_curl_cabundle: Whether to use cURL's default CA bundle
174
  @type cafile: string
175
  @param cafile: In which file we can find the certificates
176
  @type capath: string
177
  @param capath: In which directory we can find the certificates
178
  @type proxy: string
179
  @param proxy: Proxy to use, None for default behaviour and empty string for
180
                disabling proxies (see curl_easy_setopt(3))
181
  @type verify_hostname: bool
182
  @param verify_hostname: Whether to verify the remote peer certificate's
183
                          commonName
184
  @type connect_timeout: number
185
  @param connect_timeout: Timeout for establishing connection in seconds
186
  @type timeout: number
187
  @param timeout: Timeout for complete transfer in seconds (see
188
                  curl_easy_setopt(3)).
189

190
  """
191
  if use_curl_cabundle and (cafile or capath):
192
    raise Error("Can not use default CA bundle when CA file or path is set")
193

    
194
  def _ConfigCurl(curl, logger):
195
    """Configures a cURL object
196

197
    @type curl: pycurl.Curl
198
    @param curl: cURL object
199

200
    """
201
    logger.debug("Using cURL version %s", pycurl.version)
202

    
203
    # pycurl.version_info returns a tuple with information about the used
204
    # version of libcurl. Item 5 is the SSL library linked to it.
205
    # e.g.: (3, '7.18.0', 463360, 'x86_64-pc-linux-gnu', 1581, 'GnuTLS/2.0.4',
206
    # 0, '1.2.3.3', ...)
207
    sslver = _pycurl_version_fn()[5]
208
    if not sslver:
209
      raise Error("No SSL support in cURL")
210

    
211
    lcsslver = sslver.lower()
212
    if lcsslver.startswith("openssl/"):
213
      pass
214
    elif lcsslver.startswith("gnutls/"):
215
      if capath:
216
        raise Error("cURL linked against GnuTLS has no support for a"
217
                    " CA path (%s)" % (pycurl.version, ))
218
    else:
219
      raise NotImplementedError("cURL uses unsupported SSL version '%s'" %
220
                                sslver)
221

    
222
    curl.setopt(pycurl.VERBOSE, verbose)
223
    curl.setopt(pycurl.NOSIGNAL, not use_signal)
224

    
225
    # Whether to verify remote peer's CN
226
    if verify_hostname:
227
      # curl_easy_setopt(3): "When CURLOPT_SSL_VERIFYHOST is 2, that
228
      # certificate must indicate that the server is the server to which you
229
      # meant to connect, or the connection fails. [...] When the value is 1,
230
      # the certificate must contain a Common Name field, but it doesn't matter
231
      # what name it says. [...]"
232
      curl.setopt(pycurl.SSL_VERIFYHOST, 2)
233
    else:
234
      curl.setopt(pycurl.SSL_VERIFYHOST, 0)
235

    
236
    if cafile or capath or use_curl_cabundle:
237
      # Require certificates to be checked
238
      curl.setopt(pycurl.SSL_VERIFYPEER, True)
239
      if cafile:
240
        curl.setopt(pycurl.CAINFO, str(cafile))
241
      if capath:
242
        curl.setopt(pycurl.CAPATH, str(capath))
243
      # Not changing anything for using default CA bundle
244
    else:
245
      # Disable SSL certificate verification
246
      curl.setopt(pycurl.SSL_VERIFYPEER, False)
247

    
248
    if proxy is not None:
249
      curl.setopt(pycurl.PROXY, str(proxy))
250

    
251
    # Timeouts
252
    if connect_timeout is not None:
253
      curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
254
    if timeout is not None:
255
      curl.setopt(pycurl.TIMEOUT, timeout)
256

    
257
  return _ConfigCurl
258

    
259

    
260
class GanetiRapiClient(object): # pylint: disable-msg=R0904
261
  """Ganeti RAPI client.
262

263
  """
264
  USER_AGENT = "Ganeti RAPI Client"
265
  _json_encoder = simplejson.JSONEncoder(sort_keys=True)
266

    
267
  def __init__(self, host, port=GANETI_RAPI_PORT,
268
               username=None, password=None, logger=logging,
269
               curl_config_fn=None, curl_factory=None):
270
    """Initializes this class.
271

272
    @type host: string
273
    @param host: the ganeti cluster master to interact with
274
    @type port: int
275
    @param port: the port on which the RAPI is running (default is 5080)
276
    @type username: string
277
    @param username: the username to connect with
278
    @type password: string
279
    @param password: the password to connect with
280
    @type curl_config_fn: callable
281
    @param curl_config_fn: Function to configure C{pycurl.Curl} object
282
    @param logger: Logging object
283

284
    """
285
    self._username = username
286
    self._password = password
287
    self._logger = logger
288
    self._curl_config_fn = curl_config_fn
289
    self._curl_factory = curl_factory
290

    
291
    try:
292
      socket.inet_pton(socket.AF_INET6, host)
293
      address = "[%s]:%s" % (host, port)
294
    except socket.error:
295
      address = "%s:%s" % (host, port)
296

    
297
    self._base_url = "https://%s" % address
298

    
299
    if username is not None:
300
      if password is None:
301
        raise Error("Password not specified")
302
    elif password:
303
      raise Error("Specified password without username")
304

    
305
  def _CreateCurl(self):
306
    """Creates a cURL object.
307

308
    """
309
    # Create pycURL object if no factory is provided
310
    if self._curl_factory:
311
      curl = self._curl_factory()
312
    else:
313
      curl = pycurl.Curl()
314

    
315
    # Default cURL settings
316
    curl.setopt(pycurl.VERBOSE, False)
317
    curl.setopt(pycurl.FOLLOWLOCATION, False)
318
    curl.setopt(pycurl.MAXREDIRS, 5)
319
    curl.setopt(pycurl.NOSIGNAL, True)
320
    curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
321
    curl.setopt(pycurl.SSL_VERIFYHOST, 0)
322
    curl.setopt(pycurl.SSL_VERIFYPEER, False)
323
    curl.setopt(pycurl.HTTPHEADER, [
324
      "Accept: %s" % HTTP_APP_JSON,
325
      "Content-type: %s" % HTTP_APP_JSON,
326
      ])
327

    
328
    assert ((self._username is None and self._password is None) ^
329
            (self._username is not None and self._password is not None))
330

    
331
    if self._username:
332
      # Setup authentication
333
      curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
334
      curl.setopt(pycurl.USERPWD,
335
                  str("%s:%s" % (self._username, self._password)))
336

    
337
    # Call external configuration function
338
    if self._curl_config_fn:
339
      self._curl_config_fn(curl, self._logger)
340

    
341
    return curl
342

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

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

352
    """
353
    result = []
354

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

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

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

    
366
      else:
367
        result.append((name, value))
368

    
369
    return result
370

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

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

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

386
    @rtype: str
387
    @return: JSON-Decoded response
388

389
    @raises CertificateError: If an invalid SSL certificate is found
390
    @raises GanetiApiError: If an invalid response is returned
391

392
    """
393
    assert path.startswith("/")
394

    
395
    curl = self._CreateCurl()
396

    
397
    if content is not None:
398
      encoded_content = self._json_encoder.encode(content)
399
    else:
400
      encoded_content = ""
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 (content=%r)",
411
                       method, url, encoded_content)
412

    
413
    # Buffer for response
414
    encoded_resp_body = StringIO()
415

    
416
    # Configure cURL
417
    curl.setopt(pycurl.CUSTOMREQUEST, str(method))
418
    curl.setopt(pycurl.URL, str(url))
419
    curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
420
    curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
421

    
422
    try:
423
      # Send request and wait for response
424
      try:
425
        curl.perform()
426
      except pycurl.error, err:
427
        if err.args[0] in _CURL_SSL_CERT_ERRORS:
428
          raise CertificateError("SSL certificate error %s" % err)
429

    
430
        raise GanetiApiError(str(err))
431
    finally:
432
      # Reset settings to not keep references to large objects in memory
433
      # between requests
434
      curl.setopt(pycurl.POSTFIELDS, "")
435
      curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)
436

    
437
    # Get HTTP response code
438
    http_code = curl.getinfo(pycurl.RESPONSE_CODE)
439

    
440
    # Was anything written to the response buffer?
441
    if encoded_resp_body.tell():
442
      response_content = simplejson.loads(encoded_resp_body.getvalue())
443
    else:
444
      response_content = None
445

    
446
    if http_code != HTTP_OK:
447
      if isinstance(response_content, dict):
448
        msg = ("%s %s: %s" %
449
               (response_content["code"],
450
                response_content["message"],
451
                response_content["explain"]))
452
      else:
453
        msg = str(response_content)
454

    
455
      raise GanetiApiError(msg, code=http_code)
456

    
457
    return response_content
458

    
459
  def GetVersion(self):
460
    """Gets the Remote API version running on the cluster.
461

462
    @rtype: int
463
    @return: Ganeti Remote API version
464

465
    """
466
    return self._SendRequest(HTTP_GET, "/version", None, None)
467

    
468
  def GetFeatures(self):
469
    """Gets the list of optional features supported by RAPI server.
470

471
    @rtype: list
472
    @return: List of optional features
473

474
    """
475
    try:
476
      return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
477
                               None, None)
478
    except GanetiApiError, err:
479
      # Older RAPI servers don't support this resource
480
      if err.code == HTTP_NOT_FOUND:
481
        return []
482

    
483
      raise
484

    
485
  def GetOperatingSystems(self):
486
    """Gets the Operating Systems running in the Ganeti cluster.
487

488
    @rtype: list of str
489
    @return: operating systems
490

491
    """
492
    return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
493
                             None, None)
494

    
495
  def GetInfo(self):
496
    """Gets info about the cluster.
497

498
    @rtype: dict
499
    @return: information about the cluster
500

501
    """
502
    return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
503
                             None, None)
504

    
505
  def RedistributeConfig(self):
506
    """Tells the cluster to redistribute its configuration files.
507

508
    @rtype: string
509
    @return: job id
510

511
    """
512
    return self._SendRequest(HTTP_PUT,
513
                             "/%s/redistribute-config" % GANETI_RAPI_VERSION,
514
                             None, None)
515

    
516
  def ModifyCluster(self, **kwargs):
517
    """Modifies cluster parameters.
518

519
    More details for parameters can be found in the RAPI documentation.
520

521
    @rtype: string
522
    @return: job id
523

524
    """
525
    body = kwargs
526

    
527
    return self._SendRequest(HTTP_PUT,
528
                             "/%s/modify" % GANETI_RAPI_VERSION, None, body)
529

    
530
  def GetClusterTags(self):
531
    """Gets the cluster tags.
532

533
    @rtype: list of str
534
    @return: cluster tags
535

536
    """
537
    return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
538
                             None, None)
539

    
540
  def AddClusterTags(self, tags, dry_run=False):
541
    """Adds tags to the cluster.
542

543
    @type tags: list of str
544
    @param tags: tags to add to the cluster
545
    @type dry_run: bool
546
    @param dry_run: whether to perform a dry run
547

548
    @rtype: string
549
    @return: job id
550

551
    """
552
    query = [("tag", t) for t in tags]
553
    if dry_run:
554
      query.append(("dry-run", 1))
555

    
556
    return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
557
                             query, None)
558

    
559
  def DeleteClusterTags(self, tags, dry_run=False):
560
    """Deletes tags from the cluster.
561

562
    @type tags: list of str
563
    @param tags: tags to delete
564
    @type dry_run: bool
565
    @param dry_run: whether to perform a dry run
566
    @rtype: string
567
    @return: job id
568

569
    """
570
    query = [("tag", t) for t in tags]
571
    if dry_run:
572
      query.append(("dry-run", 1))
573

    
574
    return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
575
                             query, None)
576

    
577
  def GetInstances(self, bulk=False):
578
    """Gets information about instances on the cluster.
579

580
    @type bulk: bool
581
    @param bulk: whether to return all information about all instances
582

583
    @rtype: list of dict or list of str
584
    @return: if bulk is True, info about the instances, else a list of instances
585

586
    """
587
    query = []
588
    if bulk:
589
      query.append(("bulk", 1))
590

    
591
    instances = self._SendRequest(HTTP_GET,
592
                                  "/%s/instances" % GANETI_RAPI_VERSION,
593
                                  query, None)
594
    if bulk:
595
      return instances
596
    else:
597
      return [i["id"] for i in instances]
598

    
599
  def GetInstance(self, instance):
600
    """Gets information about an instance.
601

602
    @type instance: str
603
    @param instance: instance whose info to return
604

605
    @rtype: dict
606
    @return: info about the instance
607

608
    """
609
    return self._SendRequest(HTTP_GET,
610
                             ("/%s/instances/%s" %
611
                              (GANETI_RAPI_VERSION, instance)), None, None)
612

    
613
  def GetInstanceInfo(self, instance, static=None):
614
    """Gets information about an instance.
615

616
    @type instance: string
617
    @param instance: Instance name
618
    @rtype: string
619
    @return: Job ID
620

621
    """
622
    if static is not None:
623
      query = [("static", static)]
624
    else:
625
      query = None
626

    
627
    return self._SendRequest(HTTP_GET,
628
                             ("/%s/instances/%s/info" %
629
                              (GANETI_RAPI_VERSION, instance)), query, None)
630

    
631
  def CreateInstance(self, mode, name, disk_template, disks, nics,
632
                     **kwargs):
633
    """Creates a new instance.
634

635
    More details for parameters can be found in the RAPI documentation.
636

637
    @type mode: string
638
    @param mode: Instance creation mode
639
    @type name: string
640
    @param name: Hostname of the instance to create
641
    @type disk_template: string
642
    @param disk_template: Disk template for instance (e.g. plain, diskless,
643
                          file, or drbd)
644
    @type disks: list of dicts
645
    @param disks: List of disk definitions
646
    @type nics: list of dicts
647
    @param nics: List of NIC definitions
648
    @type dry_run: bool
649
    @keyword dry_run: whether to perform a dry run
650

651
    @rtype: string
652
    @return: job id
653

654
    """
655
    query = []
656

    
657
    if kwargs.get("dry_run"):
658
      query.append(("dry-run", 1))
659

    
660
    if _INST_CREATE_REQV1 in self.GetFeatures():
661
      # All required fields for request data version 1
662
      body = {
663
        _REQ_DATA_VERSION_FIELD: 1,
664
        "mode": mode,
665
        "name": name,
666
        "disk_template": disk_template,
667
        "disks": disks,
668
        "nics": nics,
669
        }
670

    
671
      conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
672
      if conflicts:
673
        raise GanetiApiError("Required fields can not be specified as"
674
                             " keywords: %s" % ", ".join(conflicts))
675

    
676
      body.update((key, value) for key, value in kwargs.iteritems()
677
                  if key != "dry_run")
678
    else:
679
      raise GanetiApiError("Server does not support new-style (version 1)"
680
                           " instance creation requests")
681

    
682
    return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
683
                             query, body)
684

    
685
  def DeleteInstance(self, instance, dry_run=False):
686
    """Deletes an instance.
687

688
    @type instance: str
689
    @param instance: the instance to delete
690

691
    @rtype: string
692
    @return: job id
693

694
    """
695
    query = []
696
    if dry_run:
697
      query.append(("dry-run", 1))
698

    
699
    return self._SendRequest(HTTP_DELETE,
700
                             ("/%s/instances/%s" %
701
                              (GANETI_RAPI_VERSION, instance)), query, None)
702

    
703
  def ModifyInstance(self, instance, **kwargs):
704
    """Modifies an instance.
705

706
    More details for parameters can be found in the RAPI documentation.
707

708
    @type instance: string
709
    @param instance: Instance name
710
    @rtype: string
711
    @return: job id
712

713
    """
714
    body = kwargs
715

    
716
    return self._SendRequest(HTTP_PUT,
717
                             ("/%s/instances/%s/modify" %
718
                              (GANETI_RAPI_VERSION, instance)), None, body)
719

    
720
  def ActivateInstanceDisks(self, instance, ignore_size=None):
721
    """Activates an instance's disks.
722

723
    @type instance: string
724
    @param instance: Instance name
725
    @type ignore_size: bool
726
    @param ignore_size: Whether to ignore recorded size
727
    @rtype: string
728
    @return: job id
729

730
    """
731
    query = []
732
    if ignore_size:
733
      query.append(("ignore_size", 1))
734

    
735
    return self._SendRequest(HTTP_PUT,
736
                             ("/%s/instances/%s/activate-disks" %
737
                              (GANETI_RAPI_VERSION, instance)), query, None)
738

    
739
  def DeactivateInstanceDisks(self, instance):
740
    """Deactivates an instance's disks.
741

742
    @type instance: string
743
    @param instance: Instance name
744
    @rtype: string
745
    @return: job id
746

747
    """
748
    return self._SendRequest(HTTP_PUT,
749
                             ("/%s/instances/%s/deactivate-disks" %
750
                              (GANETI_RAPI_VERSION, instance)), None, None)
751

    
752
  def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
753
    """Grows a disk of an instance.
754

755
    More details for parameters can be found in the RAPI documentation.
756

757
    @type instance: string
758
    @param instance: Instance name
759
    @type disk: integer
760
    @param disk: Disk index
761
    @type amount: integer
762
    @param amount: Grow disk by this amount (MiB)
763
    @type wait_for_sync: bool
764
    @param wait_for_sync: Wait for disk to synchronize
765
    @rtype: string
766
    @return: job id
767

768
    """
769
    body = {
770
      "amount": amount,
771
      }
772

    
773
    if wait_for_sync is not None:
774
      body["wait_for_sync"] = wait_for_sync
775

    
776
    return self._SendRequest(HTTP_POST,
777
                             ("/%s/instances/%s/disk/%s/grow" %
778
                              (GANETI_RAPI_VERSION, instance, disk)),
779
                             None, body)
780

    
781
  def GetInstanceTags(self, instance):
782
    """Gets tags for an instance.
783

784
    @type instance: str
785
    @param instance: instance whose tags to return
786

787
    @rtype: list of str
788
    @return: tags for the instance
789

790
    """
791
    return self._SendRequest(HTTP_GET,
792
                             ("/%s/instances/%s/tags" %
793
                              (GANETI_RAPI_VERSION, instance)), None, None)
794

    
795
  def AddInstanceTags(self, instance, tags, dry_run=False):
796
    """Adds tags to an instance.
797

798
    @type instance: str
799
    @param instance: instance to add tags to
800
    @type tags: list of str
801
    @param tags: tags to add to the instance
802
    @type dry_run: bool
803
    @param dry_run: whether to perform a dry run
804

805
    @rtype: string
806
    @return: job id
807

808
    """
809
    query = [("tag", t) for t in tags]
810
    if dry_run:
811
      query.append(("dry-run", 1))
812

    
813
    return self._SendRequest(HTTP_PUT,
814
                             ("/%s/instances/%s/tags" %
815
                              (GANETI_RAPI_VERSION, instance)), query, None)
816

    
817
  def DeleteInstanceTags(self, instance, tags, dry_run=False):
818
    """Deletes tags from an instance.
819

820
    @type instance: str
821
    @param instance: instance to delete tags from
822
    @type tags: list of str
823
    @param tags: tags to delete
824
    @type dry_run: bool
825
    @param dry_run: whether to perform a dry run
826
    @rtype: string
827
    @return: job id
828

829
    """
830
    query = [("tag", t) for t in tags]
831
    if dry_run:
832
      query.append(("dry-run", 1))
833

    
834
    return self._SendRequest(HTTP_DELETE,
835
                             ("/%s/instances/%s/tags" %
836
                              (GANETI_RAPI_VERSION, instance)), query, None)
837

    
838
  def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
839
                     dry_run=False):
840
    """Reboots an instance.
841

842
    @type instance: str
843
    @param instance: instance to rebot
844
    @type reboot_type: str
845
    @param reboot_type: one of: hard, soft, full
846
    @type ignore_secondaries: bool
847
    @param ignore_secondaries: if True, ignores errors for the secondary node
848
        while re-assembling disks (in hard-reboot mode only)
849
    @type dry_run: bool
850
    @param dry_run: whether to perform a dry run
851
    @rtype: string
852
    @return: job id
853

854
    """
855
    query = []
856
    if reboot_type:
857
      query.append(("type", reboot_type))
858
    if ignore_secondaries is not None:
859
      query.append(("ignore_secondaries", ignore_secondaries))
860
    if dry_run:
861
      query.append(("dry-run", 1))
862

    
863
    return self._SendRequest(HTTP_POST,
864
                             ("/%s/instances/%s/reboot" %
865
                              (GANETI_RAPI_VERSION, instance)), query, None)
866

    
867
  def ShutdownInstance(self, instance, dry_run=False, no_remember=False):
868
    """Shuts down an instance.
869

870
    @type instance: str
871
    @param instance: the instance to shut down
872
    @type dry_run: bool
873
    @param dry_run: whether to perform a dry run
874
    @type no_remember: bool
875
    @param no_remember: if true, will not record the state change
876
    @rtype: string
877
    @return: job id
878

879
    """
880
    query = []
881
    if dry_run:
882
      query.append(("dry-run", 1))
883
    if no_remember:
884
      query.append(("no-remember", 1))
885

    
886
    return self._SendRequest(HTTP_PUT,
887
                             ("/%s/instances/%s/shutdown" %
888
                              (GANETI_RAPI_VERSION, instance)), query, None)
889

    
890
  def StartupInstance(self, instance, dry_run=False, no_remember=False):
891
    """Starts up an instance.
892

893
    @type instance: str
894
    @param instance: the instance to start up
895
    @type dry_run: bool
896
    @param dry_run: whether to perform a dry run
897
    @type no_remember: bool
898
    @param no_remember: if true, will not record the state change
899
    @rtype: string
900
    @return: job id
901

902
    """
903
    query = []
904
    if dry_run:
905
      query.append(("dry-run", 1))
906
    if no_remember:
907
      query.append(("no-remember", 1))
908

    
909
    return self._SendRequest(HTTP_PUT,
910
                             ("/%s/instances/%s/startup" %
911
                              (GANETI_RAPI_VERSION, instance)), query, None)
912

    
913
  def ReinstallInstance(self, instance, os=None, no_startup=False,
914
                        osparams=None):
915
    """Reinstalls an instance.
916

917
    @type instance: str
918
    @param instance: The instance to reinstall
919
    @type os: str or None
920
    @param os: The operating system to reinstall. If None, the instance's
921
        current operating system will be installed again
922
    @type no_startup: bool
923
    @param no_startup: Whether to start the instance automatically
924
    @rtype: string
925
    @return: job id
926

927
    """
928
    if _INST_REINSTALL_REQV1 in self.GetFeatures():
929
      body = {
930
        "start": not no_startup,
931
        }
932
      if os is not None:
933
        body["os"] = os
934
      if osparams is not None:
935
        body["osparams"] = osparams
936
      return self._SendRequest(HTTP_POST,
937
                               ("/%s/instances/%s/reinstall" %
938
                                (GANETI_RAPI_VERSION, instance)), None, body)
939

    
940
    # Use old request format
941
    if osparams:
942
      raise GanetiApiError("Server does not support specifying OS parameters"
943
                           " for instance reinstallation")
944

    
945
    query = []
946
    if os:
947
      query.append(("os", os))
948
    if no_startup:
949
      query.append(("nostartup", 1))
950
    return self._SendRequest(HTTP_POST,
951
                             ("/%s/instances/%s/reinstall" %
952
                              (GANETI_RAPI_VERSION, instance)), query, None)
953

    
954
  def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
955
                           remote_node=None, iallocator=None, dry_run=False):
956
    """Replaces disks on an instance.
957

958
    @type instance: str
959
    @param instance: instance whose disks to replace
960
    @type disks: list of ints
961
    @param disks: Indexes of disks to replace
962
    @type mode: str
963
    @param mode: replacement mode to use (defaults to replace_auto)
964
    @type remote_node: str or None
965
    @param remote_node: new secondary node to use (for use with
966
        replace_new_secondary mode)
967
    @type iallocator: str or None
968
    @param iallocator: instance allocator plugin to use (for use with
969
                       replace_auto mode)
970
    @type dry_run: bool
971
    @param dry_run: whether to perform a dry run
972

973
    @rtype: string
974
    @return: job id
975

976
    """
977
    query = [
978
      ("mode", mode),
979
      ]
980

    
981
    if disks:
982
      query.append(("disks", ",".join(str(idx) for idx in disks)))
983

    
984
    if remote_node:
985
      query.append(("remote_node", remote_node))
986

    
987
    if iallocator:
988
      query.append(("iallocator", iallocator))
989

    
990
    if dry_run:
991
      query.append(("dry-run", 1))
992

    
993
    return self._SendRequest(HTTP_POST,
994
                             ("/%s/instances/%s/replace-disks" %
995
                              (GANETI_RAPI_VERSION, instance)), query, None)
996

    
997
  def PrepareExport(self, instance, mode):
998
    """Prepares an instance for an export.
999

1000
    @type instance: string
1001
    @param instance: Instance name
1002
    @type mode: string
1003
    @param mode: Export mode
1004
    @rtype: string
1005
    @return: Job ID
1006

1007
    """
1008
    query = [("mode", mode)]
1009
    return self._SendRequest(HTTP_PUT,
1010
                             ("/%s/instances/%s/prepare-export" %
1011
                              (GANETI_RAPI_VERSION, instance)), query, None)
1012

    
1013
  def ExportInstance(self, instance, mode, destination, shutdown=None,
1014
                     remove_instance=None,
1015
                     x509_key_name=None, destination_x509_ca=None):
1016
    """Exports an instance.
1017

1018
    @type instance: string
1019
    @param instance: Instance name
1020
    @type mode: string
1021
    @param mode: Export mode
1022
    @rtype: string
1023
    @return: Job ID
1024

1025
    """
1026
    body = {
1027
      "destination": destination,
1028
      "mode": mode,
1029
      }
1030

    
1031
    if shutdown is not None:
1032
      body["shutdown"] = shutdown
1033

    
1034
    if remove_instance is not None:
1035
      body["remove_instance"] = remove_instance
1036

    
1037
    if x509_key_name is not None:
1038
      body["x509_key_name"] = x509_key_name
1039

    
1040
    if destination_x509_ca is not None:
1041
      body["destination_x509_ca"] = destination_x509_ca
1042

    
1043
    return self._SendRequest(HTTP_PUT,
1044
                             ("/%s/instances/%s/export" %
1045
                              (GANETI_RAPI_VERSION, instance)), None, body)
1046

    
1047
  def MigrateInstance(self, instance, mode=None, cleanup=None):
1048
    """Migrates an instance.
1049

1050
    @type instance: string
1051
    @param instance: Instance name
1052
    @type mode: string
1053
    @param mode: Migration mode
1054
    @type cleanup: bool
1055
    @param cleanup: Whether to clean up a previously failed migration
1056
    @rtype: string
1057
    @return: job id
1058

1059
    """
1060
    body = {}
1061

    
1062
    if mode is not None:
1063
      body["mode"] = mode
1064

    
1065
    if cleanup is not None:
1066
      body["cleanup"] = cleanup
1067

    
1068
    return self._SendRequest(HTTP_PUT,
1069
                             ("/%s/instances/%s/migrate" %
1070
                              (GANETI_RAPI_VERSION, instance)), None, body)
1071

    
1072
  def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
1073
    """Changes the name of an instance.
1074

1075
    @type instance: string
1076
    @param instance: Instance name
1077
    @type new_name: string
1078
    @param new_name: New instance name
1079
    @type ip_check: bool
1080
    @param ip_check: Whether to ensure instance's IP address is inactive
1081
    @type name_check: bool
1082
    @param name_check: Whether to ensure instance's name is resolvable
1083
    @rtype: string
1084
    @return: job id
1085

1086
    """
1087
    body = {
1088
      "new_name": new_name,
1089
      }
1090

    
1091
    if ip_check is not None:
1092
      body["ip_check"] = ip_check
1093

    
1094
    if name_check is not None:
1095
      body["name_check"] = name_check
1096

    
1097
    return self._SendRequest(HTTP_PUT,
1098
                             ("/%s/instances/%s/rename" %
1099
                              (GANETI_RAPI_VERSION, instance)), None, body)
1100

    
1101
  def GetInstanceConsole(self, instance):
1102
    """Request information for connecting to instance's console.
1103

1104
    @type instance: string
1105
    @param instance: Instance name
1106
    @rtype: dict
1107
    @return: dictionary containing information about instance's console
1108

1109
    """
1110
    return self._SendRequest(HTTP_GET,
1111
                             ("/%s/instances/%s/console" %
1112
                              (GANETI_RAPI_VERSION, instance)), None, None)
1113

    
1114
  def GetJobs(self):
1115
    """Gets all jobs for the cluster.
1116

1117
    @rtype: list of int
1118
    @return: job ids for the cluster
1119

1120
    """
1121
    return [int(j["id"])
1122
            for j in self._SendRequest(HTTP_GET,
1123
                                       "/%s/jobs" % GANETI_RAPI_VERSION,
1124
                                       None, None)]
1125

    
1126
  def GetJobStatus(self, job_id):
1127
    """Gets the status of a job.
1128

1129
    @type job_id: string
1130
    @param job_id: job id whose status to query
1131

1132
    @rtype: dict
1133
    @return: job status
1134

1135
    """
1136
    return self._SendRequest(HTTP_GET,
1137
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1138
                             None, None)
1139

    
1140
  def WaitForJobCompletion(self, job_id, period=5, retries=-1):
1141
    """Polls cluster for job status until completion.
1142

1143
    Completion is defined as any of the following states listed in
1144
    L{JOB_STATUS_FINALIZED}.
1145

1146
    @type job_id: string
1147
    @param job_id: job id to watch
1148
    @type period: int
1149
    @param period: how often to poll for status (optional, default 5s)
1150
    @type retries: int
1151
    @param retries: how many time to poll before giving up
1152
                    (optional, default -1 means unlimited)
1153

1154
    @rtype: bool
1155
    @return: C{True} if job succeeded or C{False} if failed/status timeout
1156
    @deprecated: It is recommended to use L{WaitForJobChange} wherever
1157
      possible; L{WaitForJobChange} returns immediately after a job changed and
1158
      does not use polling
1159

1160
    """
1161
    while retries != 0:
1162
      job_result = self.GetJobStatus(job_id)
1163

    
1164
      if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
1165
        return True
1166
      elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
1167
        return False
1168

    
1169
      if period:
1170
        time.sleep(period)
1171

    
1172
      if retries > 0:
1173
        retries -= 1
1174

    
1175
    return False
1176

    
1177
  def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1178
    """Waits for job changes.
1179

1180
    @type job_id: string
1181
    @param job_id: Job ID for which to wait
1182
    @return: C{None} if no changes have been detected and a dict with two keys,
1183
      C{job_info} and C{log_entries} otherwise.
1184
    @rtype: dict
1185

1186
    """
1187
    body = {
1188
      "fields": fields,
1189
      "previous_job_info": prev_job_info,
1190
      "previous_log_serial": prev_log_serial,
1191
      }
1192

    
1193
    return self._SendRequest(HTTP_GET,
1194
                             "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1195
                             None, body)
1196

    
1197
  def CancelJob(self, job_id, dry_run=False):
1198
    """Cancels a job.
1199

1200
    @type job_id: string
1201
    @param job_id: id of the job to delete
1202
    @type dry_run: bool
1203
    @param dry_run: whether to perform a dry run
1204
    @rtype: tuple
1205
    @return: tuple containing the result, and a message (bool, string)
1206

1207
    """
1208
    query = []
1209
    if dry_run:
1210
      query.append(("dry-run", 1))
1211

    
1212
    return self._SendRequest(HTTP_DELETE,
1213
                             "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1214
                             query, None)
1215

    
1216
  def GetNodes(self, bulk=False):
1217
    """Gets all nodes in the cluster.
1218

1219
    @type bulk: bool
1220
    @param bulk: whether to return all information about all instances
1221

1222
    @rtype: list of dict or str
1223
    @return: if bulk is true, info about nodes in the cluster,
1224
        else list of nodes in the cluster
1225

1226
    """
1227
    query = []
1228
    if bulk:
1229
      query.append(("bulk", 1))
1230

    
1231
    nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1232
                              query, None)
1233
    if bulk:
1234
      return nodes
1235
    else:
1236
      return [n["id"] for n in nodes]
1237

    
1238
  def GetNode(self, node):
1239
    """Gets information about a node.
1240

1241
    @type node: str
1242
    @param node: node whose info to return
1243

1244
    @rtype: dict
1245
    @return: info about the node
1246

1247
    """
1248
    return self._SendRequest(HTTP_GET,
1249
                             "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1250
                             None, None)
1251

    
1252
  def EvacuateNode(self, node, iallocator=None, remote_node=None,
1253
                   dry_run=False, early_release=False):
1254
    """Evacuates instances from a Ganeti node.
1255

1256
    @type node: str
1257
    @param node: node to evacuate
1258
    @type iallocator: str or None
1259
    @param iallocator: instance allocator to use
1260
    @type remote_node: str
1261
    @param remote_node: node to evaucate to
1262
    @type dry_run: bool
1263
    @param dry_run: whether to perform a dry run
1264
    @type early_release: bool
1265
    @param early_release: whether to enable parallelization
1266

1267
    @rtype: list
1268
    @return: list of (job ID, instance name, new secondary node); if
1269
        dry_run was specified, then the actual move jobs were not
1270
        submitted and the job IDs will be C{None}
1271

1272
    @raises GanetiApiError: if an iallocator and remote_node are both
1273
        specified
1274

1275
    """
1276
    if iallocator and remote_node:
1277
      raise GanetiApiError("Only one of iallocator or remote_node can be used")
1278

    
1279
    query = []
1280
    if iallocator:
1281
      query.append(("iallocator", iallocator))
1282
    if remote_node:
1283
      query.append(("remote_node", remote_node))
1284
    if dry_run:
1285
      query.append(("dry-run", 1))
1286
    if early_release:
1287
      query.append(("early_release", 1))
1288

    
1289
    return self._SendRequest(HTTP_POST,
1290
                             ("/%s/nodes/%s/evacuate" %
1291
                              (GANETI_RAPI_VERSION, node)), query, None)
1292

    
1293
  def MigrateNode(self, node, mode=None, dry_run=False, iallocator=None,
1294
                  target_node=None):
1295
    """Migrates all primary instances from a node.
1296

1297
    @type node: str
1298
    @param node: node to migrate
1299
    @type mode: string
1300
    @param mode: if passed, it will overwrite the live migration type,
1301
        otherwise the hypervisor default will be used
1302
    @type dry_run: bool
1303
    @param dry_run: whether to perform a dry run
1304
    @type iallocator: string
1305
    @param iallocator: instance allocator to use
1306
    @type target_node: string
1307
    @param target_node: Target node for shared-storage instances
1308

1309
    @rtype: string
1310
    @return: job id
1311

1312
    """
1313
    query = []
1314
    if dry_run:
1315
      query.append(("dry-run", 1))
1316

    
1317
    if _NODE_MIGRATE_REQV1 in self.GetFeatures():
1318
      body = {}
1319

    
1320
      if mode is not None:
1321
        body["mode"] = mode
1322
      if iallocator is not None:
1323
        body["iallocator"] = iallocator
1324
      if target_node is not None:
1325
        body["target_node"] = target_node
1326

    
1327
      assert len(query) <= 1
1328

    
1329
      return self._SendRequest(HTTP_POST,
1330
                               ("/%s/nodes/%s/migrate" %
1331
                                (GANETI_RAPI_VERSION, node)), query, body)
1332
    else:
1333
      # Use old request format
1334
      if target_node is not None:
1335
        raise GanetiApiError("Server does not support specifying target node"
1336
                             " for node migration")
1337

    
1338
      if mode is not None:
1339
        query.append(("mode", mode))
1340

    
1341
      return self._SendRequest(HTTP_POST,
1342
                               ("/%s/nodes/%s/migrate" %
1343
                                (GANETI_RAPI_VERSION, node)), query, None)
1344

    
1345
  def GetNodeRole(self, node):
1346
    """Gets the current role for a node.
1347

1348
    @type node: str
1349
    @param node: node whose role to return
1350

1351
    @rtype: str
1352
    @return: the current role for a node
1353

1354
    """
1355
    return self._SendRequest(HTTP_GET,
1356
                             ("/%s/nodes/%s/role" %
1357
                              (GANETI_RAPI_VERSION, node)), None, None)
1358

    
1359
  def SetNodeRole(self, node, role, force=False):
1360
    """Sets the role for a node.
1361

1362
    @type node: str
1363
    @param node: the node whose role to set
1364
    @type role: str
1365
    @param role: the role to set for the node
1366
    @type force: bool
1367
    @param force: whether to force the role change
1368

1369
    @rtype: string
1370
    @return: job id
1371

1372
    """
1373
    query = [
1374
      ("force", force),
1375
      ]
1376

    
1377
    return self._SendRequest(HTTP_PUT,
1378
                             ("/%s/nodes/%s/role" %
1379
                              (GANETI_RAPI_VERSION, node)), query, role)
1380

    
1381
  def GetNodeStorageUnits(self, node, storage_type, output_fields):
1382
    """Gets the storage units for a node.
1383

1384
    @type node: str
1385
    @param node: the node whose storage units to return
1386
    @type storage_type: str
1387
    @param storage_type: storage type whose units to return
1388
    @type output_fields: str
1389
    @param output_fields: storage type fields to return
1390

1391
    @rtype: string
1392
    @return: job id where results can be retrieved
1393

1394
    """
1395
    query = [
1396
      ("storage_type", storage_type),
1397
      ("output_fields", output_fields),
1398
      ]
1399

    
1400
    return self._SendRequest(HTTP_GET,
1401
                             ("/%s/nodes/%s/storage" %
1402
                              (GANETI_RAPI_VERSION, node)), query, None)
1403

    
1404
  def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1405
    """Modifies parameters of storage units on the node.
1406

1407
    @type node: str
1408
    @param node: node whose storage units to modify
1409
    @type storage_type: str
1410
    @param storage_type: storage type whose units to modify
1411
    @type name: str
1412
    @param name: name of the storage unit
1413
    @type allocatable: bool or None
1414
    @param allocatable: Whether to set the "allocatable" flag on the storage
1415
                        unit (None=no modification, True=set, False=unset)
1416

1417
    @rtype: string
1418
    @return: job id
1419

1420
    """
1421
    query = [
1422
      ("storage_type", storage_type),
1423
      ("name", name),
1424
      ]
1425

    
1426
    if allocatable is not None:
1427
      query.append(("allocatable", allocatable))
1428

    
1429
    return self._SendRequest(HTTP_PUT,
1430
                             ("/%s/nodes/%s/storage/modify" %
1431
                              (GANETI_RAPI_VERSION, node)), query, None)
1432

    
1433
  def RepairNodeStorageUnits(self, node, storage_type, name):
1434
    """Repairs a storage unit on the node.
1435

1436
    @type node: str
1437
    @param node: node whose storage units to repair
1438
    @type storage_type: str
1439
    @param storage_type: storage type to repair
1440
    @type name: str
1441
    @param name: name of the storage unit to repair
1442

1443
    @rtype: string
1444
    @return: job id
1445

1446
    """
1447
    query = [
1448
      ("storage_type", storage_type),
1449
      ("name", name),
1450
      ]
1451

    
1452
    return self._SendRequest(HTTP_PUT,
1453
                             ("/%s/nodes/%s/storage/repair" %
1454
                              (GANETI_RAPI_VERSION, node)), query, None)
1455

    
1456
  def GetNodeTags(self, node):
1457
    """Gets the tags for a node.
1458

1459
    @type node: str
1460
    @param node: node whose tags to return
1461

1462
    @rtype: list of str
1463
    @return: tags for the node
1464

1465
    """
1466
    return self._SendRequest(HTTP_GET,
1467
                             ("/%s/nodes/%s/tags" %
1468
                              (GANETI_RAPI_VERSION, node)), None, None)
1469

    
1470
  def AddNodeTags(self, node, tags, dry_run=False):
1471
    """Adds tags to a node.
1472

1473
    @type node: str
1474
    @param node: node to add tags to
1475
    @type tags: list of str
1476
    @param tags: tags to add to the node
1477
    @type dry_run: bool
1478
    @param dry_run: whether to perform a dry run
1479

1480
    @rtype: string
1481
    @return: job id
1482

1483
    """
1484
    query = [("tag", t) for t in tags]
1485
    if dry_run:
1486
      query.append(("dry-run", 1))
1487

    
1488
    return self._SendRequest(HTTP_PUT,
1489
                             ("/%s/nodes/%s/tags" %
1490
                              (GANETI_RAPI_VERSION, node)), query, tags)
1491

    
1492
  def DeleteNodeTags(self, node, tags, dry_run=False):
1493
    """Delete tags from a node.
1494

1495
    @type node: str
1496
    @param node: node to remove tags from
1497
    @type tags: list of str
1498
    @param tags: tags to remove from the node
1499
    @type dry_run: bool
1500
    @param dry_run: whether to perform a dry run
1501

1502
    @rtype: string
1503
    @return: job id
1504

1505
    """
1506
    query = [("tag", t) for t in tags]
1507
    if dry_run:
1508
      query.append(("dry-run", 1))
1509

    
1510
    return self._SendRequest(HTTP_DELETE,
1511
                             ("/%s/nodes/%s/tags" %
1512
                              (GANETI_RAPI_VERSION, node)), query, None)
1513

    
1514
  def GetGroups(self, bulk=False):
1515
    """Gets all node groups in the cluster.
1516

1517
    @type bulk: bool
1518
    @param bulk: whether to return all information about the groups
1519

1520
    @rtype: list of dict or str
1521
    @return: if bulk is true, a list of dictionaries with info about all node
1522
        groups in the cluster, else a list of names of those node groups
1523

1524
    """
1525
    query = []
1526
    if bulk:
1527
      query.append(("bulk", 1))
1528

    
1529
    groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1530
                               query, None)
1531
    if bulk:
1532
      return groups
1533
    else:
1534
      return [g["name"] for g in groups]
1535

    
1536
  def GetGroup(self, group):
1537
    """Gets information about a node group.
1538

1539
    @type group: str
1540
    @param group: name of the node group whose info to return
1541

1542
    @rtype: dict
1543
    @return: info about the node group
1544

1545
    """
1546
    return self._SendRequest(HTTP_GET,
1547
                             "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
1548
                             None, None)
1549

    
1550
  def CreateGroup(self, name, alloc_policy=None, dry_run=False):
1551
    """Creates a new node group.
1552

1553
    @type name: str
1554
    @param name: the name of node group to create
1555
    @type alloc_policy: str
1556
    @param alloc_policy: the desired allocation policy for the group, if any
1557
    @type dry_run: bool
1558
    @param dry_run: whether to peform a dry run
1559

1560
    @rtype: string
1561
    @return: job id
1562

1563
    """
1564
    query = []
1565
    if dry_run:
1566
      query.append(("dry-run", 1))
1567

    
1568
    body = {
1569
      "name": name,
1570
      "alloc_policy": alloc_policy
1571
      }
1572

    
1573
    return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1574
                             query, body)
1575

    
1576
  def ModifyGroup(self, group, **kwargs):
1577
    """Modifies a node group.
1578

1579
    More details for parameters can be found in the RAPI documentation.
1580

1581
    @type group: string
1582
    @param group: Node group name
1583
    @rtype: string
1584
    @return: job id
1585

1586
    """
1587
    return self._SendRequest(HTTP_PUT,
1588
                             ("/%s/groups/%s/modify" %
1589
                              (GANETI_RAPI_VERSION, group)), None, kwargs)
1590

    
1591
  def DeleteGroup(self, group, dry_run=False):
1592
    """Deletes a node group.
1593

1594
    @type group: str
1595
    @param group: the node group to delete
1596
    @type dry_run: bool
1597
    @param dry_run: whether to peform a dry run
1598

1599
    @rtype: string
1600
    @return: job id
1601

1602
    """
1603
    query = []
1604
    if dry_run:
1605
      query.append(("dry-run", 1))
1606

    
1607
    return self._SendRequest(HTTP_DELETE,
1608
                             ("/%s/groups/%s" %
1609
                              (GANETI_RAPI_VERSION, group)), query, None)
1610

    
1611
  def RenameGroup(self, group, new_name):
1612
    """Changes the name of a node group.
1613

1614
    @type group: string
1615
    @param group: Node group name
1616
    @type new_name: string
1617
    @param new_name: New node group name
1618

1619
    @rtype: string
1620
    @return: job id
1621

1622
    """
1623
    body = {
1624
      "new_name": new_name,
1625
      }
1626

    
1627
    return self._SendRequest(HTTP_PUT,
1628
                             ("/%s/groups/%s/rename" %
1629
                              (GANETI_RAPI_VERSION, group)), None, body)
1630

    
1631
  def AssignGroupNodes(self, group, nodes, force=False, dry_run=False):
1632
    """Assigns nodes to a group.
1633

1634
    @type group: string
1635
    @param group: Node gropu name
1636
    @type nodes: list of strings
1637
    @param nodes: List of nodes to assign to the group
1638

1639
    @rtype: string
1640
    @return: job id
1641

1642
    """
1643
    query = []
1644

    
1645
    if force:
1646
      query.append(("force", 1))
1647

    
1648
    if dry_run:
1649
      query.append(("dry-run", 1))
1650

    
1651
    body = {
1652
      "nodes": nodes,
1653
      }
1654

    
1655
    return self._SendRequest(HTTP_PUT,
1656
                             ("/%s/groups/%s/assign-nodes" %
1657
                             (GANETI_RAPI_VERSION, group)), query, body)
1658

    
1659
  def GetGroupTags(self, group):
1660
    """Gets tags for a node group.
1661

1662
    @type group: string
1663
    @param group: Node group whose tags to return
1664

1665
    @rtype: list of strings
1666
    @return: tags for the group
1667

1668
    """
1669
    return self._SendRequest(HTTP_GET,
1670
                             ("/%s/groups/%s/tags" %
1671
                              (GANETI_RAPI_VERSION, group)), None, None)
1672

    
1673
  def AddGroupTags(self, group, tags, dry_run=False):
1674
    """Adds tags to a node group.
1675

1676
    @type group: str
1677
    @param group: group to add tags to
1678
    @type tags: list of string
1679
    @param tags: tags to add to the group
1680
    @type dry_run: bool
1681
    @param dry_run: whether to perform a dry run
1682

1683
    @rtype: string
1684
    @return: job id
1685

1686
    """
1687
    query = [("tag", t) for t in tags]
1688
    if dry_run:
1689
      query.append(("dry-run", 1))
1690

    
1691
    return self._SendRequest(HTTP_PUT,
1692
                             ("/%s/groups/%s/tags" %
1693
                              (GANETI_RAPI_VERSION, group)), query, None)
1694

    
1695
  def DeleteGroupTags(self, group, tags, dry_run=False):
1696
    """Deletes tags from a node group.
1697

1698
    @type group: str
1699
    @param group: group to delete tags from
1700
    @type tags: list of string
1701
    @param tags: tags to delete
1702
    @type dry_run: bool
1703
    @param dry_run: whether to perform a dry run
1704
    @rtype: string
1705
    @return: job id
1706

1707
    """
1708
    query = [("tag", t) for t in tags]
1709
    if dry_run:
1710
      query.append(("dry-run", 1))
1711

    
1712
    return self._SendRequest(HTTP_DELETE,
1713
                             ("/%s/groups/%s/tags" %
1714
                              (GANETI_RAPI_VERSION, group)), query, None)
1715

    
1716
  def Query(self, what, fields, filter_=None):
1717
    """Retrieves information about resources.
1718

1719
    @type what: string
1720
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1721
    @type fields: list of string
1722
    @param fields: Requested fields
1723
    @type filter_: None or list
1724
    @param filter_: Query filter
1725

1726
    @rtype: string
1727
    @return: job id
1728

1729
    """
1730
    body = {
1731
      "fields": fields,
1732
      }
1733

    
1734
    if filter_ is not None:
1735
      body["filter"] = filter_
1736

    
1737
    return self._SendRequest(HTTP_PUT,
1738
                             ("/%s/query/%s" %
1739
                              (GANETI_RAPI_VERSION, what)), None, body)
1740

    
1741
  def QueryFields(self, what, fields=None):
1742
    """Retrieves available fields for a resource.
1743

1744
    @type what: string
1745
    @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1746
    @type fields: list of string
1747
    @param fields: Requested fields
1748

1749
    @rtype: string
1750
    @return: job id
1751

1752
    """
1753
    query = []
1754

    
1755
    if fields is not None:
1756
      query.append(("fields", ",".join(fields)))
1757

    
1758
    return self._SendRequest(HTTP_GET,
1759
                             ("/%s/query/%s/fields" %
1760
                              (GANETI_RAPI_VERSION, what)), query, None)