#
#
-# Copyright (C) 2010 Google Inc.
+# Copyright (C) 2010, 2011 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# 02110-1301, USA.
-"""Ganeti RAPI client."""
+"""Ganeti RAPI client.
-import httplib
-import httplib2
+@attention: To use the RAPI client, the application B{must} call
+ C{pycurl.global_init} during initialization and
+ C{pycurl.global_cleanup} before exiting the process. This is very
+ important in multi-threaded programs. See curl_global_init(3) and
+ curl_global_cleanup(3) for details. The decorator L{UsesRapiClient}
+ can be used.
+
+"""
+
+# No Ganeti-specific modules should be imported. The RAPI client is supposed to
+# be standalone.
+
+import logging
import simplejson
import socket
import urllib
-from OpenSSL import SSL
-from OpenSSL import crypto
+import threading
+import pycurl
+import time
+
+try:
+ from cStringIO import StringIO
+except ImportError:
+ from StringIO import StringIO
+
+GANETI_RAPI_PORT = 5080
+GANETI_RAPI_VERSION = 2
HTTP_DELETE = "DELETE"
HTTP_GET = "GET"
HTTP_PUT = "PUT"
HTTP_POST = "POST"
+HTTP_OK = 200
+HTTP_NOT_FOUND = 404
+HTTP_APP_JSON = "application/json"
+
REPLACE_DISK_PRI = "replace_on_primary"
REPLACE_DISK_SECONDARY = "replace_on_secondary"
REPLACE_DISK_CHG = "replace_new_secondary"
REPLACE_DISK_AUTO = "replace_auto"
-VALID_REPLACEMENT_MODES = frozenset([
- REPLACE_DISK_PRI, REPLACE_DISK_SECONDARY, REPLACE_DISK_CHG,
- REPLACE_DISK_AUTO
- ])
-VALID_NODE_ROLES = frozenset([
- "drained", "master", "master-candidate", "offline", "regular"
- ])
-VALID_STORAGE_TYPES = frozenset(["file", "lvm-pv", "lvm-vg"])
+
+NODE_ROLE_DRAINED = "drained"
+NODE_ROLE_MASTER_CANDIATE = "master-candidate"
+NODE_ROLE_MASTER = "master"
+NODE_ROLE_OFFLINE = "offline"
+NODE_ROLE_REGULAR = "regular"
+
+JOB_STATUS_QUEUED = "queued"
+JOB_STATUS_WAITING = "waiting"
+JOB_STATUS_CANCELING = "canceling"
+JOB_STATUS_RUNNING = "running"
+JOB_STATUS_CANCELED = "canceled"
+JOB_STATUS_SUCCESS = "success"
+JOB_STATUS_ERROR = "error"
+JOB_STATUS_FINALIZED = frozenset([
+ JOB_STATUS_CANCELED,
+ JOB_STATUS_SUCCESS,
+ JOB_STATUS_ERROR,
+ ])
+JOB_STATUS_ALL = frozenset([
+ JOB_STATUS_QUEUED,
+ JOB_STATUS_WAITING,
+ JOB_STATUS_CANCELING,
+ JOB_STATUS_RUNNING,
+ ]) | JOB_STATUS_FINALIZED
+
+# Legacy name
+JOB_STATUS_WAITLOCK = JOB_STATUS_WAITING
+
+# Internal constants
+_REQ_DATA_VERSION_FIELD = "__version__"
+_INST_CREATE_REQV1 = "instance-create-reqv1"
+_INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
+_NODE_MIGRATE_REQV1 = "node-migrate-reqv1"
+_NODE_EVAC_RES1 = "node-evac-res1"
+_INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link"])
+_INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
+_INST_CREATE_V0_PARAMS = frozenset([
+ "os", "pnode", "snode", "iallocator", "start", "ip_check", "name_check",
+ "hypervisor", "file_storage_dir", "file_driver", "dry_run",
+ ])
+_INST_CREATE_V0_DPARAMS = frozenset(["beparams", "hvparams"])
+
+# Older pycURL versions don't have all error constants
+try:
+ _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
+ _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
+except AttributeError:
+ _CURLE_SSL_CACERT = 60
+ _CURLE_SSL_CACERT_BADFILE = 77
+
+_CURL_SSL_CERT_ERRORS = frozenset([
+ _CURLE_SSL_CACERT,
+ _CURLE_SSL_CACERT_BADFILE,
+ ])
class Error(Exception):
"""Generic error raised from Ganeti API.
"""
- pass
+ def __init__(self, msg, code=None):
+ Error.__init__(self, msg)
+ self.code = code
-class InvalidReplacementMode(Error):
- """Raised when an invalid disk replacement mode is attempted.
+def UsesRapiClient(fn):
+ """Decorator for code using RAPI client to initialize pycURL.
"""
- pass
+ def wrapper(*args, **kwargs):
+ # curl_global_init(3) and curl_global_cleanup(3) must be called with only
+ # one thread running. This check is just a safety measure -- it doesn't
+ # cover all cases.
+ assert threading.activeCount() == 1, \
+ "Found active threads when initializing pycURL"
+
+ pycurl.global_init(pycurl.GLOBAL_ALL)
+ try:
+ return fn(*args, **kwargs)
+ finally:
+ pycurl.global_cleanup()
+
+ return wrapper
+
+
+def GenericCurlConfig(verbose=False, use_signal=False,
+ use_curl_cabundle=False, cafile=None, capath=None,
+ proxy=None, verify_hostname=False,
+ connect_timeout=None, timeout=None,
+ _pycurl_version_fn=pycurl.version_info):
+ """Curl configuration function generator.
+
+ @type verbose: bool
+ @param verbose: Whether to set cURL to verbose mode
+ @type use_signal: bool
+ @param use_signal: Whether to allow cURL to use signals
+ @type use_curl_cabundle: bool
+ @param use_curl_cabundle: Whether to use cURL's default CA bundle
+ @type cafile: string
+ @param cafile: In which file we can find the certificates
+ @type capath: string
+ @param capath: In which directory we can find the certificates
+ @type proxy: string
+ @param proxy: Proxy to use, None for default behaviour and empty string for
+ disabling proxies (see curl_easy_setopt(3))
+ @type verify_hostname: bool
+ @param verify_hostname: Whether to verify the remote peer certificate's
+ commonName
+ @type connect_timeout: number
+ @param connect_timeout: Timeout for establishing connection in seconds
+ @type timeout: number
+ @param timeout: Timeout for complete transfer in seconds (see
+ curl_easy_setopt(3)).
+ """
+ if use_curl_cabundle and (cafile or capath):
+ raise Error("Can not use default CA bundle when CA file or path is set")
-class InvalidStorageType(Error):
- """Raised when an invalid storage type is used.
+ def _ConfigCurl(curl, logger):
+ """Configures a cURL object
- """
- pass
+ @type curl: pycurl.Curl
+ @param curl: cURL object
+
+ """
+ logger.debug("Using cURL version %s", pycurl.version)
+
+ # pycurl.version_info returns a tuple with information about the used
+ # version of libcurl. Item 5 is the SSL library linked to it.
+ # e.g.: (3, '7.18.0', 463360, 'x86_64-pc-linux-gnu', 1581, 'GnuTLS/2.0.4',
+ # 0, '1.2.3.3', ...)
+ sslver = _pycurl_version_fn()[5]
+ if not sslver:
+ raise Error("No SSL support in cURL")
+
+ lcsslver = sslver.lower()
+ if lcsslver.startswith("openssl/"):
+ pass
+ elif lcsslver.startswith("gnutls/"):
+ if capath:
+ raise Error("cURL linked against GnuTLS has no support for a"
+ " CA path (%s)" % (pycurl.version, ))
+ else:
+ raise NotImplementedError("cURL uses unsupported SSL version '%s'" %
+ sslver)
+
+ curl.setopt(pycurl.VERBOSE, verbose)
+ curl.setopt(pycurl.NOSIGNAL, not use_signal)
+
+ # Whether to verify remote peer's CN
+ if verify_hostname:
+ # curl_easy_setopt(3): "When CURLOPT_SSL_VERIFYHOST is 2, that
+ # certificate must indicate that the server is the server to which you
+ # meant to connect, or the connection fails. [...] When the value is 1,
+ # the certificate must contain a Common Name field, but it doesn't matter
+ # what name it says. [...]"
+ curl.setopt(pycurl.SSL_VERIFYHOST, 2)
+ else:
+ curl.setopt(pycurl.SSL_VERIFYHOST, 0)
+
+ if cafile or capath or use_curl_cabundle:
+ # Require certificates to be checked
+ curl.setopt(pycurl.SSL_VERIFYPEER, True)
+ if cafile:
+ curl.setopt(pycurl.CAINFO, str(cafile))
+ if capath:
+ curl.setopt(pycurl.CAPATH, str(capath))
+ # Not changing anything for using default CA bundle
+ else:
+ # Disable SSL certificate verification
+ curl.setopt(pycurl.SSL_VERIFYPEER, False)
+ if proxy is not None:
+ curl.setopt(pycurl.PROXY, str(proxy))
-class InvalidNodeRole(Error):
- """Raised when an invalid node role is used.
+ # Timeouts
+ if connect_timeout is not None:
+ curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
+ if timeout is not None:
+ curl.setopt(pycurl.TIMEOUT, timeout)
- """
- pass
+ return _ConfigCurl
-class GanetiRapiClient(object):
+class GanetiRapiClient(object): # pylint: disable-msg=R0904
"""Ganeti RAPI client.
"""
-
USER_AGENT = "Ganeti RAPI Client"
+ _json_encoder = simplejson.JSONEncoder(sort_keys=True)
- def __init__(self, master_hostname, port=5080, username=None, password=None,
- ssl_cert_file=None):
- """Constructor.
+ def __init__(self, host, port=GANETI_RAPI_PORT,
+ username=None, password=None, logger=logging,
+ curl_config_fn=None, curl_factory=None):
+ """Initializes this class.
- @type master_hostname: str
- @param master_hostname: the ganeti cluster master to interact with
+ @type host: string
+ @param host: the ganeti cluster master to interact with
@type port: int
- @param port: the port on which the RAPI is running. (default is 5080)
- @type username: str
+ @param port: the port on which the RAPI is running (default is 5080)
+ @type username: string
@param username: the username to connect with
- @type password: str
+ @type password: string
@param password: the password to connect with
- @type ssl_cert_file: str or None
- @param ssl_cert_file: path to the expected SSL certificate. if None, SSL
- certificate will not be verified
+ @type curl_config_fn: callable
+ @param curl_config_fn: Function to configure C{pycurl.Curl} object
+ @param logger: Logging object
"""
- self._master_hostname = master_hostname
- self._port = port
+ self._username = username
+ self._password = password
+ self._logger = logger
+ self._curl_config_fn = curl_config_fn
+ self._curl_factory = curl_factory
- self._version = None
- self._http = httplib2.Http()
+ try:
+ socket.inet_pton(socket.AF_INET6, host)
+ address = "[%s]:%s" % (host, port)
+ except socket.error:
+ address = "%s:%s" % (host, port)
- # Older versions of httplib2 don't support the connection_type argument
- # to request(), so we have to manually specify the connection object in the
- # internal dict.
- base_url = self._MakeUrl("/", prepend_version=False)
- scheme, authority, _, _, _ = httplib2.parse_uri(base_url)
- conn_key = "%s:%s" % (scheme, authority)
- self._http.connections[conn_key] = \
- HTTPSConnectionOpenSSL(master_hostname, port, cert_file=ssl_cert_file)
+ self._base_url = "https://%s" % address
- self._headers = {
- "Accept": "text/plain",
- "Content-type": "application/x-www-form-urlencoded",
- "User-Agent": self.USER_AGENT}
+ if username is not None:
+ if password is None:
+ raise Error("Password not specified")
+ elif password:
+ raise Error("Specified password without username")
- if username is not None and password is not None:
- self._http.add_credentials(username, password)
+ def _CreateCurl(self):
+ """Creates a cURL object.
- def _MakeUrl(self, path, query=None, prepend_version=True):
- """Constructs the URL to pass to the HTTP client.
+ """
+ # Create pycURL object if no factory is provided
+ if self._curl_factory:
+ curl = self._curl_factory()
+ else:
+ curl = pycurl.Curl()
+
+ # Default cURL settings
+ curl.setopt(pycurl.VERBOSE, False)
+ curl.setopt(pycurl.FOLLOWLOCATION, False)
+ curl.setopt(pycurl.MAXREDIRS, 5)
+ curl.setopt(pycurl.NOSIGNAL, True)
+ curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
+ curl.setopt(pycurl.SSL_VERIFYHOST, 0)
+ curl.setopt(pycurl.SSL_VERIFYPEER, False)
+ curl.setopt(pycurl.HTTPHEADER, [
+ "Accept: %s" % HTTP_APP_JSON,
+ "Content-type: %s" % HTTP_APP_JSON,
+ ])
+
+ assert ((self._username is None and self._password is None) ^
+ (self._username is not None and self._password is not None))
+
+ if self._username:
+ # Setup authentication
+ curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
+ curl.setopt(pycurl.USERPWD,
+ str("%s:%s" % (self._username, self._password)))
+
+ # Call external configuration function
+ if self._curl_config_fn:
+ self._curl_config_fn(curl, self._logger)
+
+ return curl
+
+ @staticmethod
+ def _EncodeQuery(query):
+ """Encode query values for RAPI URL.
- @type path: str
- @param path: HTTP URL path
@type query: list of two-tuples
- @param query: query arguments to pass to urllib.urlencode
- @type prepend_version: bool
- @param prepend_version: whether to automatically fetch and prepend the
- Ganeti RAPI version to the URL path
-
- @rtype: str
- @return: URL path
+ @param query: Query arguments
+ @rtype: list
+ @return: Query list with encoded values
"""
- if prepend_version:
- path = "/%d%s" % (self.GetVersion(), path)
+ result = []
+
+ for name, value in query:
+ if value is None:
+ result.append((name, ""))
- return "https://%(host)s:%(port)d%(path)s?%(query)s" % {
- "host": self._master_hostname,
- "port": self._port,
- "path": path,
- "query": urllib.urlencode(query or [])}
+ elif isinstance(value, bool):
+ # Boolean values must be encoded as 0 or 1
+ result.append((name, int(value)))
- def _SendRequest(self, method, path, query=None, content=None,
- prepend_version=True):
+ elif isinstance(value, (list, tuple, dict)):
+ raise ValueError("Invalid query data type %r" % type(value).__name__)
+
+ else:
+ result.append((name, value))
+
+ return result
+
+ def _SendRequest(self, method, path, query, content):
"""Sends an HTTP request.
This constructs a full URL, encodes and decodes HTTP bodies, and
handles invalid responses in a pythonic way.
- @type method: str
+ @type method: string
@param method: HTTP method to use
- @type path: str
+ @type path: string
@param path: HTTP URL path
@type query: list of two-tuples
@param query: query arguments to pass to urllib.urlencode
@type content: str or None
@param content: HTTP body content
- @type prepend_version: bool
- @param prepend_version: whether to automatically fetch and prepend the
- Ganeti RAPI version to the URL path
@rtype: str
@return: JSON-Decoded response
@raises GanetiApiError: If an invalid response is returned
"""
- if content:
- content = simplejson.JSONEncoder(sort_keys=True).encode(content)
+ assert path.startswith("/")
- url = self._MakeUrl(path, query, prepend_version)
- try:
- resp_headers, resp_content = self._http.request(url, method,
- body=content, headers=self._headers)
- except (crypto.Error, SSL.Error):
- raise CertificateError("Invalid SSL certificate.")
+ curl = self._CreateCurl()
+
+ if content is not None:
+ encoded_content = self._json_encoder.encode(content)
+ else:
+ encoded_content = ""
+
+ # Build URL
+ urlparts = [self._base_url, path]
+ if query:
+ urlparts.append("?")
+ urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
+
+ url = "".join(urlparts)
+
+ self._logger.debug("Sending request %s %s (content=%r)",
+ method, url, encoded_content)
+
+ # Buffer for response
+ encoded_resp_body = StringIO()
- if resp_content:
- resp_content = simplejson.loads(resp_content)
+ # Configure cURL
+ curl.setopt(pycurl.CUSTOMREQUEST, str(method))
+ curl.setopt(pycurl.URL, str(url))
+ curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
+ curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
- # TODO: Are there other status codes that are valid? (redirect?)
- if resp_headers.status != 200:
- if isinstance(resp_content, dict):
+ try:
+ # Send request and wait for response
+ try:
+ curl.perform()
+ except pycurl.error, err:
+ if err.args[0] in _CURL_SSL_CERT_ERRORS:
+ raise CertificateError("SSL certificate error %s" % err)
+
+ raise GanetiApiError(str(err))
+ finally:
+ # Reset settings to not keep references to large objects in memory
+ # between requests
+ curl.setopt(pycurl.POSTFIELDS, "")
+ curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)
+
+ # Get HTTP response code
+ http_code = curl.getinfo(pycurl.RESPONSE_CODE)
+
+ # Was anything written to the response buffer?
+ if encoded_resp_body.tell():
+ response_content = simplejson.loads(encoded_resp_body.getvalue())
+ else:
+ response_content = None
+
+ if http_code != HTTP_OK:
+ if isinstance(response_content, dict):
msg = ("%s %s: %s" %
- (resp_content["code"], resp_content["message"],
- resp_content["explain"]))
+ (response_content["code"],
+ response_content["message"],
+ response_content["explain"]))
else:
- msg = resp_content
- raise GanetiApiError(msg)
+ msg = str(response_content)
- return resp_content
+ raise GanetiApiError(msg, code=http_code)
+
+ return response_content
def GetVersion(self):
"""Gets the Remote API version running on the cluster.
@return: Ganeti Remote API version
"""
- if self._version is None:
- self._version = self._SendRequest(HTTP_GET, "/version",
- prepend_version=False)
- return self._version
+ return self._SendRequest(HTTP_GET, "/version", None, None)
+
+ def GetFeatures(self):
+ """Gets the list of optional features supported by RAPI server.
+
+ @rtype: list
+ @return: List of optional features
+
+ """
+ try:
+ return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
+ None, None)
+ except GanetiApiError, err:
+ # Older RAPI servers don't support this resource
+ if err.code == HTTP_NOT_FOUND:
+ return []
+
+ raise
def GetOperatingSystems(self):
"""Gets the Operating Systems running in the Ganeti cluster.
@return: operating systems
"""
- return self._SendRequest(HTTP_GET, "/os")
+ return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
+ None, None)
def GetInfo(self):
"""Gets info about the cluster.
@return: information about the cluster
"""
- return self._SendRequest(HTTP_GET, "/info")
+ return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
+ None, None)
+
+ def RedistributeConfig(self):
+ """Tells the cluster to redistribute its configuration files.
+
+ @rtype: string
+ @return: job id
+
+ """
+ return self._SendRequest(HTTP_PUT,
+ "/%s/redistribute-config" % GANETI_RAPI_VERSION,
+ None, None)
+
+ def ModifyCluster(self, **kwargs):
+ """Modifies cluster parameters.
+
+ More details for parameters can be found in the RAPI documentation.
+
+ @rtype: string
+ @return: job id
+
+ """
+ body = kwargs
+
+ return self._SendRequest(HTTP_PUT,
+ "/%s/modify" % GANETI_RAPI_VERSION, None, body)
def GetClusterTags(self):
"""Gets the cluster tags.
@return: cluster tags
"""
- return self._SendRequest(HTTP_GET, "/tags")
+ return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
+ None, None)
def AddClusterTags(self, tags, dry_run=False):
"""Adds tags to the cluster.
@type dry_run: bool
@param dry_run: whether to perform a dry run
- @rtype: int
+ @rtype: string
@return: job id
"""
if dry_run:
query.append(("dry-run", 1))
- return self._SendRequest(HTTP_PUT, "/tags", query)
+ return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
+ query, None)
def DeleteClusterTags(self, tags, dry_run=False):
"""Deletes tags from the cluster.
@param tags: tags to delete
@type dry_run: bool
@param dry_run: whether to perform a dry run
+ @rtype: string
+ @return: job id
"""
query = [("tag", t) for t in tags]
if dry_run:
query.append(("dry-run", 1))
- self._SendRequest(HTTP_DELETE, "/tags", query)
+ return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
+ query, None)
def GetInstances(self, bulk=False):
"""Gets information about instances on the cluster.
if bulk:
query.append(("bulk", 1))
- instances = self._SendRequest(HTTP_GET, "/instances", query)
+ instances = self._SendRequest(HTTP_GET,
+ "/%s/instances" % GANETI_RAPI_VERSION,
+ query, None)
if bulk:
return instances
else:
return [i["id"] for i in instances]
-
- def GetInstanceInfo(self, instance):
+ def GetInstance(self, instance):
"""Gets information about an instance.
@type instance: str
@return: info about the instance
"""
- return self._SendRequest(HTTP_GET, "/instances/%s" % instance)
+ return self._SendRequest(HTTP_GET,
+ ("/%s/instances/%s" %
+ (GANETI_RAPI_VERSION, instance)), None, None)
- def CreateInstance(self, dry_run=False):
+ def GetInstanceInfo(self, instance, static=None):
+ """Gets information about an instance.
+
+ @type instance: string
+ @param instance: Instance name
+ @rtype: string
+ @return: Job ID
+
+ """
+ if static is not None:
+ query = [("static", static)]
+ else:
+ query = None
+
+ return self._SendRequest(HTTP_GET,
+ ("/%s/instances/%s/info" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
+
+ def CreateInstance(self, mode, name, disk_template, disks, nics,
+ **kwargs):
"""Creates a new instance.
+ More details for parameters can be found in the RAPI documentation.
+
+ @type mode: string
+ @param mode: Instance creation mode
+ @type name: string
+ @param name: Hostname of the instance to create
+ @type disk_template: string
+ @param disk_template: Disk template for instance (e.g. plain, diskless,
+ file, or drbd)
+ @type disks: list of dicts
+ @param disks: List of disk definitions
+ @type nics: list of dicts
+ @param nics: List of NIC definitions
@type dry_run: bool
- @param dry_run: whether to perform a dry run
+ @keyword dry_run: whether to perform a dry run
- @rtype: int
+ @rtype: string
@return: job id
"""
- # TODO: Pass arguments needed to actually create an instance.
query = []
- if dry_run:
+
+ if kwargs.get("dry_run"):
query.append(("dry-run", 1))
- return self._SendRequest(HTTP_POST, "/instances", query)
+ if _INST_CREATE_REQV1 in self.GetFeatures():
+ # All required fields for request data version 1
+ body = {
+ _REQ_DATA_VERSION_FIELD: 1,
+ "mode": mode,
+ "name": name,
+ "disk_template": disk_template,
+ "disks": disks,
+ "nics": nics,
+ }
+
+ conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
+ if conflicts:
+ raise GanetiApiError("Required fields can not be specified as"
+ " keywords: %s" % ", ".join(conflicts))
+
+ body.update((key, value) for key, value in kwargs.iteritems()
+ if key != "dry_run")
+ else:
+ raise GanetiApiError("Server does not support new-style (version 1)"
+ " instance creation requests")
+
+ return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
+ query, body)
def DeleteInstance(self, instance, dry_run=False):
"""Deletes an instance.
@type instance: str
@param instance: the instance to delete
- @rtype: int
+ @rtype: string
@return: job id
"""
if dry_run:
query.append(("dry-run", 1))
- return self._SendRequest(HTTP_DELETE, "/instances/%s" % instance, query)
+ return self._SendRequest(HTTP_DELETE,
+ ("/%s/instances/%s" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
+
+ def ModifyInstance(self, instance, **kwargs):
+ """Modifies an instance.
+
+ More details for parameters can be found in the RAPI documentation.
+
+ @type instance: string
+ @param instance: Instance name
+ @rtype: string
+ @return: job id
+
+ """
+ body = kwargs
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/modify" %
+ (GANETI_RAPI_VERSION, instance)), None, body)
+
+ def ActivateInstanceDisks(self, instance, ignore_size=None):
+ """Activates an instance's disks.
+
+ @type instance: string
+ @param instance: Instance name
+ @type ignore_size: bool
+ @param ignore_size: Whether to ignore recorded size
+ @rtype: string
+ @return: job id
+
+ """
+ query = []
+ if ignore_size:
+ query.append(("ignore_size", 1))
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/activate-disks" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
+
+ def DeactivateInstanceDisks(self, instance):
+ """Deactivates an instance's disks.
+
+ @type instance: string
+ @param instance: Instance name
+ @rtype: string
+ @return: job id
+
+ """
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/deactivate-disks" %
+ (GANETI_RAPI_VERSION, instance)), None, None)
+
+ def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
+ """Grows a disk of an instance.
+
+ More details for parameters can be found in the RAPI documentation.
+
+ @type instance: string
+ @param instance: Instance name
+ @type disk: integer
+ @param disk: Disk index
+ @type amount: integer
+ @param amount: Grow disk by this amount (MiB)
+ @type wait_for_sync: bool
+ @param wait_for_sync: Wait for disk to synchronize
+ @rtype: string
+ @return: job id
+
+ """
+ body = {
+ "amount": amount,
+ }
+
+ if wait_for_sync is not None:
+ body["wait_for_sync"] = wait_for_sync
+
+ return self._SendRequest(HTTP_POST,
+ ("/%s/instances/%s/disk/%s/grow" %
+ (GANETI_RAPI_VERSION, instance, disk)),
+ None, body)
def GetInstanceTags(self, instance):
"""Gets tags for an instance.
@return: tags for the instance
"""
- return self._SendRequest(HTTP_GET, "/instances/%s/tags" % instance)
+ return self._SendRequest(HTTP_GET,
+ ("/%s/instances/%s/tags" %
+ (GANETI_RAPI_VERSION, instance)), None, None)
def AddInstanceTags(self, instance, tags, dry_run=False):
"""Adds tags to an instance.
@type dry_run: bool
@param dry_run: whether to perform a dry run
- @rtype: int
+ @rtype: string
@return: job id
"""
if dry_run:
query.append(("dry-run", 1))
- return self._SendRequest(HTTP_PUT, "/instances/%s/tags" % instance, query)
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/tags" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
def DeleteInstanceTags(self, instance, tags, dry_run=False):
"""Deletes tags from an instance.
@param tags: tags to delete
@type dry_run: bool
@param dry_run: whether to perform a dry run
+ @rtype: string
+ @return: job id
"""
query = [("tag", t) for t in tags]
if dry_run:
query.append(("dry-run", 1))
- self._SendRequest(HTTP_DELETE, "/instances/%s/tags" % instance, query)
+ return self._SendRequest(HTTP_DELETE,
+ ("/%s/instances/%s/tags" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
dry_run=False):
while re-assembling disks (in hard-reboot mode only)
@type dry_run: bool
@param dry_run: whether to perform a dry run
+ @rtype: string
+ @return: job id
"""
query = []
if dry_run:
query.append(("dry-run", 1))
- self._SendRequest(HTTP_POST, "/instances/%s/reboot" % instance, query)
+ return self._SendRequest(HTTP_POST,
+ ("/%s/instances/%s/reboot" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
- def ShutdownInstance(self, instance, dry_run=False):
+ def ShutdownInstance(self, instance, dry_run=False, no_remember=False):
"""Shuts down an instance.
@type instance: str
@param instance: the instance to shut down
@type dry_run: bool
@param dry_run: whether to perform a dry run
+ @type no_remember: bool
+ @param no_remember: if true, will not record the state change
+ @rtype: string
+ @return: job id
"""
query = []
if dry_run:
query.append(("dry-run", 1))
+ if no_remember:
+ query.append(("no-remember", 1))
- self._SendRequest(HTTP_PUT, "/instances/%s/shutdown" % instance, query)
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/shutdown" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
- def StartupInstance(self, instance, dry_run=False):
+ def StartupInstance(self, instance, dry_run=False, no_remember=False):
"""Starts up an instance.
@type instance: str
@param instance: the instance to start up
@type dry_run: bool
@param dry_run: whether to perform a dry run
+ @type no_remember: bool
+ @param no_remember: if true, will not record the state change
+ @rtype: string
+ @return: job id
"""
query = []
if dry_run:
query.append(("dry-run", 1))
+ if no_remember:
+ query.append(("no-remember", 1))
- self._SendRequest(HTTP_PUT, "/instances/%s/startup" % instance, query)
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/startup" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
- def ReinstallInstance(self, instance, os, no_startup=False):
+ def ReinstallInstance(self, instance, os=None, no_startup=False,
+ osparams=None):
"""Reinstalls an instance.
@type instance: str
- @param instance: the instance to reinstall
- @type os: str
- @param os: the os to reinstall
+ @param instance: The instance to reinstall
+ @type os: str or None
+ @param os: The operating system to reinstall. If None, the instance's
+ current operating system will be installed again
@type no_startup: bool
- @param no_startup: whether to start the instance automatically
+ @param no_startup: Whether to start the instance automatically
+ @rtype: string
+ @return: job id
"""
- query = [("os", os)]
+ if _INST_REINSTALL_REQV1 in self.GetFeatures():
+ body = {
+ "start": not no_startup,
+ }
+ if os is not None:
+ body["os"] = os
+ if osparams is not None:
+ body["osparams"] = osparams
+ return self._SendRequest(HTTP_POST,
+ ("/%s/instances/%s/reinstall" %
+ (GANETI_RAPI_VERSION, instance)), None, body)
+
+ # Use old request format
+ if osparams:
+ raise GanetiApiError("Server does not support specifying OS parameters"
+ " for instance reinstallation")
+
+ query = []
+ if os:
+ query.append(("os", os))
if no_startup:
query.append(("nostartup", 1))
- self._SendRequest(HTTP_POST, "/instances/%s/reinstall" % instance, query)
+ return self._SendRequest(HTTP_POST,
+ ("/%s/instances/%s/reinstall" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
- def ReplaceInstanceDisks(self, instance, disks, mode="replace_auto",
- remote_node=None, iallocator="hail", dry_run=False):
+ def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
+ remote_node=None, iallocator=None, dry_run=False):
"""Replaces disks on an instance.
@type instance: str
@param instance: instance whose disks to replace
- @type disks: list of str
- @param disks: disks to replace
+ @type disks: list of ints
+ @param disks: Indexes of disks to replace
@type mode: str
- @param mode: replacement mode to use. defaults to replace_auto
+ @param mode: replacement mode to use (defaults to replace_auto)
@type remote_node: str or None
@param remote_node: new secondary node to use (for use with
- replace_new_secondary mdoe)
+ replace_new_secondary mode)
@type iallocator: str or None
@param iallocator: instance allocator plugin to use (for use with
- replace_auto mdoe). default is hail
+ replace_auto mode)
@type dry_run: bool
@param dry_run: whether to perform a dry run
- @rtype: int
+ @rtype: string
@return: job id
- @raises InvalidReplacementMode: If an invalid disk replacement mode is given
- @raises GanetiApiError: If no secondary node is given with a non-auto
- replacement mode is requested.
-
"""
- if mode not in VALID_REPLACEMENT_MODES:
- raise InvalidReplacementMode("%s is not a valid disk replacement mode.",
- mode)
+ query = [
+ ("mode", mode),
+ ]
- query = [("mode", mode), ("disks", ",".join(disks))]
+ if disks:
+ query.append(("disks", ",".join(str(idx) for idx in disks)))
- if mode is REPLACE_DISK_AUTO:
- query.append(("iallocator", iallocator))
- elif mode is REPLACE_DISK_SECONDARY:
- if remote_node is None:
- raise GanetiApiError("You must supply a new secondary node.")
+ if remote_node:
query.append(("remote_node", remote_node))
+ if iallocator:
+ query.append(("iallocator", iallocator))
+
if dry_run:
query.append(("dry-run", 1))
return self._SendRequest(HTTP_POST,
- "/instances/%s/replace-disks" % instance, query)
+ ("/%s/instances/%s/replace-disks" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
+
+ def PrepareExport(self, instance, mode):
+ """Prepares an instance for an export.
+
+ @type instance: string
+ @param instance: Instance name
+ @type mode: string
+ @param mode: Export mode
+ @rtype: string
+ @return: Job ID
+
+ """
+ query = [("mode", mode)]
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/prepare-export" %
+ (GANETI_RAPI_VERSION, instance)), query, None)
+
+ def ExportInstance(self, instance, mode, destination, shutdown=None,
+ remove_instance=None,
+ x509_key_name=None, destination_x509_ca=None):
+ """Exports an instance.
+
+ @type instance: string
+ @param instance: Instance name
+ @type mode: string
+ @param mode: Export mode
+ @rtype: string
+ @return: Job ID
+
+ """
+ body = {
+ "destination": destination,
+ "mode": mode,
+ }
+
+ if shutdown is not None:
+ body["shutdown"] = shutdown
+
+ if remove_instance is not None:
+ body["remove_instance"] = remove_instance
+
+ if x509_key_name is not None:
+ body["x509_key_name"] = x509_key_name
+
+ if destination_x509_ca is not None:
+ body["destination_x509_ca"] = destination_x509_ca
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/export" %
+ (GANETI_RAPI_VERSION, instance)), None, body)
+
+ def MigrateInstance(self, instance, mode=None, cleanup=None):
+ """Migrates an instance.
+
+ @type instance: string
+ @param instance: Instance name
+ @type mode: string
+ @param mode: Migration mode
+ @type cleanup: bool
+ @param cleanup: Whether to clean up a previously failed migration
+ @rtype: string
+ @return: job id
+
+ """
+ body = {}
+
+ if mode is not None:
+ body["mode"] = mode
+
+ if cleanup is not None:
+ body["cleanup"] = cleanup
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/migrate" %
+ (GANETI_RAPI_VERSION, instance)), None, body)
+
+ def FailoverInstance(self, instance, iallocator=None,
+ ignore_consistency=None, target_node=None):
+ """Does a failover of an instance.
+
+ @type instance: string
+ @param instance: Instance name
+ @type iallocator: string
+ @param iallocator: Iallocator for deciding the target node for
+ shared-storage instances
+ @type ignore_consistency: bool
+ @param ignore_consistency: Whether to ignore disk consistency
+ @type target_node: string
+ @param target_node: Target node for shared-storage instances
+ @rtype: string
+ @return: job id
+
+ """
+ body = {}
+
+ if iallocator is not None:
+ body["iallocator"] = iallocator
+
+ if ignore_consistency is not None:
+ body["ignore_consistency"] = ignore_consistency
+
+ if target_node is not None:
+ body["target_node"] = target_node
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/failover" %
+ (GANETI_RAPI_VERSION, instance)), None, body)
+
+ def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
+ """Changes the name of an instance.
+
+ @type instance: string
+ @param instance: Instance name
+ @type new_name: string
+ @param new_name: New instance name
+ @type ip_check: bool
+ @param ip_check: Whether to ensure instance's IP address is inactive
+ @type name_check: bool
+ @param name_check: Whether to ensure instance's name is resolvable
+ @rtype: string
+ @return: job id
+
+ """
+ body = {
+ "new_name": new_name,
+ }
+
+ if ip_check is not None:
+ body["ip_check"] = ip_check
+
+ if name_check is not None:
+ body["name_check"] = name_check
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/instances/%s/rename" %
+ (GANETI_RAPI_VERSION, instance)), None, body)
+
+ def GetInstanceConsole(self, instance):
+ """Request information for connecting to instance's console.
+
+ @type instance: string
+ @param instance: Instance name
+ @rtype: dict
+ @return: dictionary containing information about instance's console
+
+ """
+ return self._SendRequest(HTTP_GET,
+ ("/%s/instances/%s/console" %
+ (GANETI_RAPI_VERSION, instance)), None, None)
def GetJobs(self):
"""Gets all jobs for the cluster.
@return: job ids for the cluster
"""
- return [int(j["id"]) for j in self._SendRequest(HTTP_GET, "/jobs")]
+ return [int(j["id"])
+ for j in self._SendRequest(HTTP_GET,
+ "/%s/jobs" % GANETI_RAPI_VERSION,
+ None, None)]
def GetJobStatus(self, job_id):
"""Gets the status of a job.
- @type job_id: int
+ @type job_id: string
@param job_id: job id whose status to query
@rtype: dict
@return: job status
"""
- return self._SendRequest(HTTP_GET, "/jobs/%d" % job_id)
+ return self._SendRequest(HTTP_GET,
+ "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
+ None, None)
+
+ def WaitForJobCompletion(self, job_id, period=5, retries=-1):
+ """Polls cluster for job status until completion.
+
+ Completion is defined as any of the following states listed in
+ L{JOB_STATUS_FINALIZED}.
+
+ @type job_id: string
+ @param job_id: job id to watch
+ @type period: int
+ @param period: how often to poll for status (optional, default 5s)
+ @type retries: int
+ @param retries: how many time to poll before giving up
+ (optional, default -1 means unlimited)
+
+ @rtype: bool
+ @return: C{True} if job succeeded or C{False} if failed/status timeout
+ @deprecated: It is recommended to use L{WaitForJobChange} wherever
+ possible; L{WaitForJobChange} returns immediately after a job changed and
+ does not use polling
+
+ """
+ while retries != 0:
+ job_result = self.GetJobStatus(job_id)
+
+ if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
+ return True
+ elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
+ return False
+
+ if period:
+ time.sleep(period)
+
+ if retries > 0:
+ retries -= 1
+
+ return False
+
+ def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
+ """Waits for job changes.
+
+ @type job_id: string
+ @param job_id: Job ID for which to wait
+ @return: C{None} if no changes have been detected and a dict with two keys,
+ C{job_info} and C{log_entries} otherwise.
+ @rtype: dict
+
+ """
+ body = {
+ "fields": fields,
+ "previous_job_info": prev_job_info,
+ "previous_log_serial": prev_log_serial,
+ }
- def DeleteJob(self, job_id, dry_run=False):
- """Deletes a job.
+ return self._SendRequest(HTTP_GET,
+ "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
+ None, body)
- @type job_id: int
+ def CancelJob(self, job_id, dry_run=False):
+ """Cancels a job.
+
+ @type job_id: string
@param job_id: id of the job to delete
@type dry_run: bool
@param dry_run: whether to perform a dry run
+ @rtype: tuple
+ @return: tuple containing the result, and a message (bool, string)
"""
query = []
if dry_run:
query.append(("dry-run", 1))
- self._SendRequest(HTTP_DELETE, "/jobs/%d" % job_id, query)
+ return self._SendRequest(HTTP_DELETE,
+ "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
+ query, None)
def GetNodes(self, bulk=False):
"""Gets all nodes in the cluster.
if bulk:
query.append(("bulk", 1))
- nodes = self._SendRequest(HTTP_GET, "/nodes", query)
+ nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
+ query, None)
if bulk:
return nodes
else:
return [n["id"] for n in nodes]
- def GetNodeInfo(self, node):
+ def GetNode(self, node):
"""Gets information about a node.
@type node: str
@return: info about the node
"""
- return self._SendRequest(HTTP_GET, "/nodes/%s" % node)
+ return self._SendRequest(HTTP_GET,
+ "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
+ None, None)
def EvacuateNode(self, node, iallocator=None, remote_node=None,
- dry_run=False):
+ dry_run=False, early_release=None,
+ primary=None, secondary=None, accept_old=False):
"""Evacuates instances from a Ganeti node.
@type node: str
@param remote_node: node to evaucate to
@type dry_run: bool
@param dry_run: whether to perform a dry run
-
- @rtype: int
- @return: job id
-
- @raises GanetiApiError: if an iallocator and remote_node are both specified
+ @type early_release: bool
+ @param early_release: whether to enable parallelization
+ @type primary: bool
+ @param primary: Whether to evacuate primary instances
+ @type secondary: bool
+ @param secondary: Whether to evacuate secondary instances
+ @type accept_old: bool
+ @param accept_old: Whether caller is ready to accept old-style (pre-2.5)
+ results
+
+ @rtype: string, or a list for pre-2.5 results
+ @return: Job ID or, if C{accept_old} is set and server is pre-2.5,
+ list of (job ID, instance name, new secondary node); if dry_run was
+ specified, then the actual move jobs were not submitted and the job IDs
+ will be C{None}
+
+ @raises GanetiApiError: if an iallocator and remote_node are both
+ specified
"""
- query = []
if iallocator and remote_node:
- raise GanetiApiError("Only one of iallocator or remote_node can be used.")
+ raise GanetiApiError("Only one of iallocator or remote_node can be used")
- if iallocator:
- query.append(("iallocator", iallocator))
- if remote_node:
- query.append(("remote_node", remote_node))
+ query = []
if dry_run:
query.append(("dry-run", 1))
- return self._SendRequest(HTTP_POST, "/nodes/%s/evacuate" % node, query)
+ if _NODE_EVAC_RES1 in self.GetFeatures():
+ body = {}
+
+ if iallocator is not None:
+ body["iallocator"] = iallocator
+ if remote_node is not None:
+ body["remote_node"] = remote_node
+ if early_release is not None:
+ body["early_release"] = early_release
+ if primary is not None:
+ body["primary"] = primary
+ if secondary is not None:
+ body["secondary"] = secondary
+ else:
+ # Pre-2.5 request format
+ body = None
+
+ if not accept_old:
+ raise GanetiApiError("Server is version 2.4 or earlier and caller does"
+ " not accept old-style results (parameter"
+ " accept_old)")
+
+ if primary or primary is None or not (secondary is None or secondary):
+ raise GanetiApiError("Server can only evacuate secondary instances")
+
+ if iallocator:
+ query.append(("iallocator", iallocator))
+ if remote_node:
+ query.append(("remote_node", remote_node))
+ if early_release:
+ query.append(("early_release", 1))
+
+ return self._SendRequest(HTTP_POST,
+ ("/%s/nodes/%s/evacuate" %
+ (GANETI_RAPI_VERSION, node)), query, body)
- def MigrateNode(self, node, live=True, dry_run=False):
+ def MigrateNode(self, node, mode=None, dry_run=False, iallocator=None,
+ target_node=None):
"""Migrates all primary instances from a node.
@type node: str
@param node: node to migrate
- @type live: bool
- @param live: whether to use live migration
+ @type mode: string
+ @param mode: if passed, it will overwrite the live migration type,
+ otherwise the hypervisor default will be used
@type dry_run: bool
@param dry_run: whether to perform a dry run
+ @type iallocator: string
+ @param iallocator: instance allocator to use
+ @type target_node: string
+ @param target_node: Target node for shared-storage instances
- @rtype: int
+ @rtype: string
@return: job id
"""
query = []
- if live:
- query.append(("live", 1))
if dry_run:
query.append(("dry-run", 1))
- return self._SendRequest(HTTP_POST, "/nodes/%s/migrate" % node, query)
+ if _NODE_MIGRATE_REQV1 in self.GetFeatures():
+ body = {}
+
+ if mode is not None:
+ body["mode"] = mode
+ if iallocator is not None:
+ body["iallocator"] = iallocator
+ if target_node is not None:
+ body["target_node"] = target_node
+
+ assert len(query) <= 1
+
+ return self._SendRequest(HTTP_POST,
+ ("/%s/nodes/%s/migrate" %
+ (GANETI_RAPI_VERSION, node)), query, body)
+ else:
+ # Use old request format
+ if target_node is not None:
+ raise GanetiApiError("Server does not support specifying target node"
+ " for node migration")
+
+ if mode is not None:
+ query.append(("mode", mode))
+
+ return self._SendRequest(HTTP_POST,
+ ("/%s/nodes/%s/migrate" %
+ (GANETI_RAPI_VERSION, node)), query, None)
def GetNodeRole(self, node):
"""Gets the current role for a node.
@return: the current role for a node
"""
- return self._SendRequest(HTTP_GET, "/nodes/%s/role" % node)
+ return self._SendRequest(HTTP_GET,
+ ("/%s/nodes/%s/role" %
+ (GANETI_RAPI_VERSION, node)), None, None)
def SetNodeRole(self, node, role, force=False):
"""Sets the role for a node.
@type force: bool
@param force: whether to force the role change
- @rtype: int
+ @rtype: string
@return: job id
- @raise InvalidNodeRole: If an invalid node role is specified
-
"""
- if role not in VALID_NODE_ROLES:
- raise InvalidNodeRole("%s is not a valid node role.", role)
+ query = [
+ ("force", force),
+ ]
- query = [("force", force)]
- return self._SendRequest(HTTP_PUT, "/nodes/%s/role" % node, query,
- content=role)
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/nodes/%s/role" %
+ (GANETI_RAPI_VERSION, node)), query, role)
def GetNodeStorageUnits(self, node, storage_type, output_fields):
"""Gets the storage units for a node.
@type output_fields: str
@param output_fields: storage type fields to return
- @rtype: int
+ @rtype: string
@return: job id where results can be retrieved
- @raise InvalidStorageType: If an invalid storage type is specified
-
"""
- # TODO: Add default for storage_type & output_fields
- if storage_type not in VALID_STORAGE_TYPES:
- raise InvalidStorageType("%s is an invalid storage type.", storage_type)
+ query = [
+ ("storage_type", storage_type),
+ ("output_fields", output_fields),
+ ]
- query = [("storage_type", storage_type), ("output_fields", output_fields)]
- return self._SendRequest(HTTP_GET, "/nodes/%s/storage" % node, query)
+ return self._SendRequest(HTTP_GET,
+ ("/%s/nodes/%s/storage" %
+ (GANETI_RAPI_VERSION, node)), query, None)
- def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=True):
+ def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
"""Modifies parameters of storage units on the node.
@type node: str
@param storage_type: storage type whose units to modify
@type name: str
@param name: name of the storage unit
- @type allocatable: bool
- @param allocatable: TODO: Document me
+ @type allocatable: bool or None
+ @param allocatable: Whether to set the "allocatable" flag on the storage
+ unit (None=no modification, True=set, False=unset)
- @rtype: int
+ @rtype: string
@return: job id
- @raise InvalidStorageType: If an invalid storage type is specified
-
"""
- if storage_type not in VALID_STORAGE_TYPES:
- raise InvalidStorageType("%s is an invalid storage type.", storage_type)
-
query = [
- ("storage_type", storage_type), ("name", name),
- ("allocatable", allocatable)
- ]
- return self._SendRequest(HTTP_PUT, "/nodes/%s/storage/modify" % node, query)
+ ("storage_type", storage_type),
+ ("name", name),
+ ]
+
+ if allocatable is not None:
+ query.append(("allocatable", allocatable))
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/nodes/%s/storage/modify" %
+ (GANETI_RAPI_VERSION, node)), query, None)
def RepairNodeStorageUnits(self, node, storage_type, name):
"""Repairs a storage unit on the node.
@type name: str
@param name: name of the storage unit to repair
- @rtype: int
+ @rtype: string
@return: job id
- @raise InvalidStorageType: If an invalid storage type is specified
-
"""
- if storage_type not in VALID_STORAGE_TYPES:
- raise InvalidStorageType("%s is an invalid storage type.", storage_type)
+ query = [
+ ("storage_type", storage_type),
+ ("name", name),
+ ]
- query = [("storage_type", storage_type), ("name", name)]
- return self._SendRequest(HTTP_PUT, "/nodes/%s/storage/repair" % node, query)
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/nodes/%s/storage/repair" %
+ (GANETI_RAPI_VERSION, node)), query, None)
def GetNodeTags(self, node):
"""Gets the tags for a node.
@return: tags for the node
"""
- return self._SendRequest(HTTP_GET, "/nodes/%s/tags" % node)
+ return self._SendRequest(HTTP_GET,
+ ("/%s/nodes/%s/tags" %
+ (GANETI_RAPI_VERSION, node)), None, None)
def AddNodeTags(self, node, tags, dry_run=False):
"""Adds tags to a node.
@type dry_run: bool
@param dry_run: whether to perform a dry run
- @rtype: int
+ @rtype: string
@return: job id
"""
if dry_run:
query.append(("dry-run", 1))
- return self._SendRequest(HTTP_PUT, "/nodes/%s/tags" % node, query,
- content=tags)
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/nodes/%s/tags" %
+ (GANETI_RAPI_VERSION, node)), query, tags)
def DeleteNodeTags(self, node, tags, dry_run=False):
"""Delete tags from a node.
@type dry_run: bool
@param dry_run: whether to perform a dry run
- @rtype: int
+ @rtype: string
@return: job id
"""
if dry_run:
query.append(("dry-run", 1))
- return self._SendRequest(HTTP_DELETE, "/nodes/%s/tags" % node, query)
+ return self._SendRequest(HTTP_DELETE,
+ ("/%s/nodes/%s/tags" %
+ (GANETI_RAPI_VERSION, node)), query, None)
+ def GetGroups(self, bulk=False):
+ """Gets all node groups in the cluster.
-class HTTPSConnectionOpenSSL(httplib.HTTPSConnection):
- """HTTPS Connection handler that verifies the SSL certificate.
+ @type bulk: bool
+ @param bulk: whether to return all information about the groups
- """
+ @rtype: list of dict or str
+ @return: if bulk is true, a list of dictionaries with info about all node
+ groups in the cluster, else a list of names of those node groups
- # pylint: disable-msg=W0142
- def __init__(self, *args, **kwargs):
- """Constructor.
+ """
+ query = []
+ if bulk:
+ query.append(("bulk", 1))
+
+ groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
+ query, None)
+ if bulk:
+ return groups
+ else:
+ return [g["name"] for g in groups]
+
+ def GetGroup(self, group):
+ """Gets information about a node group.
+
+ @type group: str
+ @param group: name of the node group whose info to return
+
+ @rtype: dict
+ @return: info about the node group
"""
- httplib.HTTPSConnection.__init__(self, *args, **kwargs)
+ return self._SendRequest(HTTP_GET,
+ "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
+ None, None)
- self._ssl_cert = None
- if self.cert_file:
- f = open(self.cert_file, "r")
- self._ssl_cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
- f.close()
+ def CreateGroup(self, name, alloc_policy=None, dry_run=False):
+ """Creates a new node group.
- # pylint: disable-msg=W0613
- def _VerifySSLCertCallback(self, conn, cert, errnum, errdepth, ok):
- """Verifies the SSL certificate provided by the peer.
+ @type name: str
+ @param name: the name of node group to create
+ @type alloc_policy: str
+ @param alloc_policy: the desired allocation policy for the group, if any
+ @type dry_run: bool
+ @param dry_run: whether to peform a dry run
+
+ @rtype: string
+ @return: job id
"""
- return (self._ssl_cert.digest("sha1") == cert.digest("sha1") and
- self._ssl_cert.digest("md5") == cert.digest("md5"))
+ query = []
+ if dry_run:
+ query.append(("dry-run", 1))
+
+ body = {
+ "name": name,
+ "alloc_policy": alloc_policy
+ }
- def connect(self):
- """Connect to the server specified when the object was created.
+ return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
+ query, body)
- This ensures that SSL certificates are verified.
+ def ModifyGroup(self, group, **kwargs):
+ """Modifies a node group.
+
+ More details for parameters can be found in the RAPI documentation.
+
+ @type group: string
+ @param group: Node group name
+ @rtype: string
+ @return: job id
+
+ """
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/groups/%s/modify" %
+ (GANETI_RAPI_VERSION, group)), None, kwargs)
+
+ def DeleteGroup(self, group, dry_run=False):
+ """Deletes a node group.
+
+ @type group: str
+ @param group: the node group to delete
+ @type dry_run: bool
+ @param dry_run: whether to peform a dry run
+
+ @rtype: string
+ @return: job id
+
+ """
+ query = []
+ if dry_run:
+ query.append(("dry-run", 1))
+
+ return self._SendRequest(HTTP_DELETE,
+ ("/%s/groups/%s" %
+ (GANETI_RAPI_VERSION, group)), query, None)
+
+ def RenameGroup(self, group, new_name):
+ """Changes the name of a node group.
+
+ @type group: string
+ @param group: Node group name
+ @type new_name: string
+ @param new_name: New node group name
+
+ @rtype: string
+ @return: job id
"""
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- ctx = SSL.Context(SSL.SSLv23_METHOD)
- ctx.set_options(SSL.OP_NO_SSLv2)
- ctx.use_certificate(self._ssl_cert)
- ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
- self._VerifySSLCertCallback)
+ body = {
+ "new_name": new_name,
+ }
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/groups/%s/rename" %
+ (GANETI_RAPI_VERSION, group)), None, body)
+
+ def AssignGroupNodes(self, group, nodes, force=False, dry_run=False):
+ """Assigns nodes to a group.
+
+ @type group: string
+ @param group: Node gropu name
+ @type nodes: list of strings
+ @param nodes: List of nodes to assign to the group
+
+ @rtype: string
+ @return: job id
+
+ """
+ query = []
+
+ if force:
+ query.append(("force", 1))
+
+ if dry_run:
+ query.append(("dry-run", 1))
+
+ body = {
+ "nodes": nodes,
+ }
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/groups/%s/assign-nodes" %
+ (GANETI_RAPI_VERSION, group)), query, body)
+
+ def GetGroupTags(self, group):
+ """Gets tags for a node group.
+
+ @type group: string
+ @param group: Node group whose tags to return
+
+ @rtype: list of strings
+ @return: tags for the group
+
+ """
+ return self._SendRequest(HTTP_GET,
+ ("/%s/groups/%s/tags" %
+ (GANETI_RAPI_VERSION, group)), None, None)
+
+ def AddGroupTags(self, group, tags, dry_run=False):
+ """Adds tags to a node group.
+
+ @type group: str
+ @param group: group to add tags to
+ @type tags: list of string
+ @param tags: tags to add to the group
+ @type dry_run: bool
+ @param dry_run: whether to perform a dry run
+
+ @rtype: string
+ @return: job id
+
+ """
+ query = [("tag", t) for t in tags]
+ if dry_run:
+ query.append(("dry-run", 1))
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/groups/%s/tags" %
+ (GANETI_RAPI_VERSION, group)), query, None)
+
+ def DeleteGroupTags(self, group, tags, dry_run=False):
+ """Deletes tags from a node group.
+
+ @type group: str
+ @param group: group to delete tags from
+ @type tags: list of string
+ @param tags: tags to delete
+ @type dry_run: bool
+ @param dry_run: whether to perform a dry run
+ @rtype: string
+ @return: job id
+
+ """
+ query = [("tag", t) for t in tags]
+ if dry_run:
+ query.append(("dry-run", 1))
+
+ return self._SendRequest(HTTP_DELETE,
+ ("/%s/groups/%s/tags" %
+ (GANETI_RAPI_VERSION, group)), query, None)
+
+ def Query(self, what, fields, filter_=None):
+ """Retrieves information about resources.
+
+ @type what: string
+ @param what: Resource name, one of L{constants.QR_VIA_RAPI}
+ @type fields: list of string
+ @param fields: Requested fields
+ @type filter_: None or list
+ @param filter_: Query filter
+
+ @rtype: string
+ @return: job id
+
+ """
+ body = {
+ "fields": fields,
+ }
+
+ if filter_ is not None:
+ body["filter"] = filter_
+
+ return self._SendRequest(HTTP_PUT,
+ ("/%s/query/%s" %
+ (GANETI_RAPI_VERSION, what)), None, body)
+
+ def QueryFields(self, what, fields=None):
+ """Retrieves available fields for a resource.
+
+ @type what: string
+ @param what: Resource name, one of L{constants.QR_VIA_RAPI}
+ @type fields: list of string
+ @param fields: Requested fields
+
+ @rtype: string
+ @return: job id
+
+ """
+ query = []
+
+ if fields is not None:
+ query.append(("fields", ",".join(fields)))
- ssl = SSL.Connection(ctx, sock)
- ssl.connect((self.host, self.port))
- self.sock = httplib.FakeSocket(sock, ssl)
+ return self._SendRequest(HTTP_GET,
+ ("/%s/query/%s/fields" %
+ (GANETI_RAPI_VERSION, what)), query, None)