4 # Copyright (C) 2010, 2011 Google Inc.
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.
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.
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
22 """Ganeti RAPI client.
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}
33 # No Ganeti-specific modules should be imported. The RAPI client is supposed to
45 from cStringIO import StringIO
47 from StringIO import StringIO
50 GANETI_RAPI_PORT = 5080
51 GANETI_RAPI_VERSION = 2
53 HTTP_DELETE = "DELETE"
59 HTTP_APP_JSON = "application/json"
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"
66 NODE_EVAC_PRI = "primary-only"
67 NODE_EVAC_SEC = "secondary-only"
70 NODE_ROLE_DRAINED = "drained"
71 NODE_ROLE_MASTER_CANDIATE = "master-candidate"
72 NODE_ROLE_MASTER = "master"
73 NODE_ROLE_OFFLINE = "offline"
74 NODE_ROLE_REGULAR = "regular"
76 JOB_STATUS_QUEUED = "queued"
77 JOB_STATUS_WAITING = "waiting"
78 JOB_STATUS_CANCELING = "canceling"
79 JOB_STATUS_RUNNING = "running"
80 JOB_STATUS_CANCELED = "canceled"
81 JOB_STATUS_SUCCESS = "success"
82 JOB_STATUS_ERROR = "error"
83 JOB_STATUS_FINALIZED = frozenset([
88 JOB_STATUS_ALL = frozenset([
93 ]) | JOB_STATUS_FINALIZED
96 JOB_STATUS_WAITLOCK = JOB_STATUS_WAITING
99 _REQ_DATA_VERSION_FIELD = "__version__"
100 _INST_CREATE_REQV1 = "instance-create-reqv1"
101 _INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
102 _NODE_MIGRATE_REQV1 = "node-migrate-reqv1"
103 _NODE_EVAC_RES1 = "node-evac-res1"
104 _INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link"])
105 _INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
106 _INST_CREATE_V0_PARAMS = frozenset([
107 "os", "pnode", "snode", "iallocator", "start", "ip_check", "name_check",
108 "hypervisor", "file_storage_dir", "file_driver", "dry_run",
110 _INST_CREATE_V0_DPARAMS = frozenset(["beparams", "hvparams"])
112 # Older pycURL versions don't have all error constants
114 _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
115 _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
116 except AttributeError:
117 _CURLE_SSL_CACERT = 60
118 _CURLE_SSL_CACERT_BADFILE = 77
120 _CURL_SSL_CERT_ERRORS = frozenset([
122 _CURLE_SSL_CACERT_BADFILE,
126 class Error(Exception):
127 """Base error class for this module.
133 class CertificateError(Error):
134 """Raised when a problem is found with the SSL certificate.
140 class GanetiApiError(Error):
141 """Generic error raised from Ganeti API.
144 def __init__(self, msg, code=None):
145 Error.__init__(self, msg)
149 def UsesRapiClient(fn):
150 """Decorator for code using RAPI client to initialize pycURL.
153 def wrapper(*args, **kwargs):
154 # curl_global_init(3) and curl_global_cleanup(3) must be called with only
155 # one thread running. This check is just a safety measure -- it doesn't
157 assert threading.activeCount() == 1, \
158 "Found active threads when initializing pycURL"
160 pycurl.global_init(pycurl.GLOBAL_ALL)
162 return fn(*args, **kwargs)
164 pycurl.global_cleanup()
169 def GenericCurlConfig(verbose=False, use_signal=False,
170 use_curl_cabundle=False, cafile=None, capath=None,
171 proxy=None, verify_hostname=False,
172 connect_timeout=None, timeout=None,
173 _pycurl_version_fn=pycurl.version_info):
174 """Curl configuration function generator.
177 @param verbose: Whether to set cURL to verbose mode
178 @type use_signal: bool
179 @param use_signal: Whether to allow cURL to use signals
180 @type use_curl_cabundle: bool
181 @param use_curl_cabundle: Whether to use cURL's default CA bundle
183 @param cafile: In which file we can find the certificates
185 @param capath: In which directory we can find the certificates
187 @param proxy: Proxy to use, None for default behaviour and empty string for
188 disabling proxies (see curl_easy_setopt(3))
189 @type verify_hostname: bool
190 @param verify_hostname: Whether to verify the remote peer certificate's
192 @type connect_timeout: number
193 @param connect_timeout: Timeout for establishing connection in seconds
194 @type timeout: number
195 @param timeout: Timeout for complete transfer in seconds (see
196 curl_easy_setopt(3)).
199 if use_curl_cabundle and (cafile or capath):
200 raise Error("Can not use default CA bundle when CA file or path is set")
202 def _ConfigCurl(curl, logger):
203 """Configures a cURL object
205 @type curl: pycurl.Curl
206 @param curl: cURL object
209 logger.debug("Using cURL version %s", pycurl.version)
211 # pycurl.version_info returns a tuple with information about the used
212 # version of libcurl. Item 5 is the SSL library linked to it.
213 # e.g.: (3, '7.18.0', 463360, 'x86_64-pc-linux-gnu', 1581, 'GnuTLS/2.0.4',
215 sslver = _pycurl_version_fn()[5]
217 raise Error("No SSL support in cURL")
219 lcsslver = sslver.lower()
220 if lcsslver.startswith("openssl/"):
222 elif lcsslver.startswith("gnutls/"):
224 raise Error("cURL linked against GnuTLS has no support for a"
225 " CA path (%s)" % (pycurl.version, ))
227 raise NotImplementedError("cURL uses unsupported SSL version '%s'" %
230 curl.setopt(pycurl.VERBOSE, verbose)
231 curl.setopt(pycurl.NOSIGNAL, not use_signal)
233 # Whether to verify remote peer's CN
235 # curl_easy_setopt(3): "When CURLOPT_SSL_VERIFYHOST is 2, that
236 # certificate must indicate that the server is the server to which you
237 # meant to connect, or the connection fails. [...] When the value is 1,
238 # the certificate must contain a Common Name field, but it doesn't matter
239 # what name it says. [...]"
240 curl.setopt(pycurl.SSL_VERIFYHOST, 2)
242 curl.setopt(pycurl.SSL_VERIFYHOST, 0)
244 if cafile or capath or use_curl_cabundle:
245 # Require certificates to be checked
246 curl.setopt(pycurl.SSL_VERIFYPEER, True)
248 curl.setopt(pycurl.CAINFO, str(cafile))
250 curl.setopt(pycurl.CAPATH, str(capath))
251 # Not changing anything for using default CA bundle
253 # Disable SSL certificate verification
254 curl.setopt(pycurl.SSL_VERIFYPEER, False)
256 if proxy is not None:
257 curl.setopt(pycurl.PROXY, str(proxy))
260 if connect_timeout is not None:
261 curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
262 if timeout is not None:
263 curl.setopt(pycurl.TIMEOUT, timeout)
268 class GanetiRapiClient(object): # pylint: disable=R0904
269 """Ganeti RAPI client.
272 USER_AGENT = "Ganeti RAPI Client"
273 _json_encoder = simplejson.JSONEncoder(sort_keys=True)
275 def __init__(self, host, port=GANETI_RAPI_PORT,
276 username=None, password=None, logger=logging,
277 curl_config_fn=None, curl_factory=None):
278 """Initializes this class.
281 @param host: the ganeti cluster master to interact with
283 @param port: the port on which the RAPI is running (default is 5080)
284 @type username: string
285 @param username: the username to connect with
286 @type password: string
287 @param password: the password to connect with
288 @type curl_config_fn: callable
289 @param curl_config_fn: Function to configure C{pycurl.Curl} object
290 @param logger: Logging object
293 self._username = username
294 self._password = password
295 self._logger = logger
296 self._curl_config_fn = curl_config_fn
297 self._curl_factory = curl_factory
300 socket.inet_pton(socket.AF_INET6, host)
301 address = "[%s]:%s" % (host, port)
303 address = "%s:%s" % (host, port)
305 self._base_url = "https://%s" % address
307 if username is not None:
309 raise Error("Password not specified")
311 raise Error("Specified password without username")
313 def _CreateCurl(self):
314 """Creates a cURL object.
317 # Create pycURL object if no factory is provided
318 if self._curl_factory:
319 curl = self._curl_factory()
323 # Default cURL settings
324 curl.setopt(pycurl.VERBOSE, False)
325 curl.setopt(pycurl.FOLLOWLOCATION, False)
326 curl.setopt(pycurl.MAXREDIRS, 5)
327 curl.setopt(pycurl.NOSIGNAL, True)
328 curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
329 curl.setopt(pycurl.SSL_VERIFYHOST, 0)
330 curl.setopt(pycurl.SSL_VERIFYPEER, False)
331 curl.setopt(pycurl.HTTPHEADER, [
332 "Accept: %s" % HTTP_APP_JSON,
333 "Content-type: %s" % HTTP_APP_JSON,
336 assert ((self._username is None and self._password is None) ^
337 (self._username is not None and self._password is not None))
340 # Setup authentication
341 curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
342 curl.setopt(pycurl.USERPWD,
343 str("%s:%s" % (self._username, self._password)))
345 # Call external configuration function
346 if self._curl_config_fn:
347 self._curl_config_fn(curl, self._logger)
352 def _EncodeQuery(query):
353 """Encode query values for RAPI URL.
355 @type query: list of two-tuples
356 @param query: Query arguments
358 @return: Query list with encoded values
363 for name, value in query:
365 result.append((name, ""))
367 elif isinstance(value, bool):
368 # Boolean values must be encoded as 0 or 1
369 result.append((name, int(value)))
371 elif isinstance(value, (list, tuple, dict)):
372 raise ValueError("Invalid query data type %r" % type(value).__name__)
375 result.append((name, value))
379 def _SendRequest(self, method, path, query, content):
380 """Sends an HTTP request.
382 This constructs a full URL, encodes and decodes HTTP bodies, and
383 handles invalid responses in a pythonic way.
386 @param method: HTTP method to use
388 @param path: HTTP URL path
389 @type query: list of two-tuples
390 @param query: query arguments to pass to urllib.urlencode
391 @type content: str or None
392 @param content: HTTP body content
395 @return: JSON-Decoded response
397 @raises CertificateError: If an invalid SSL certificate is found
398 @raises GanetiApiError: If an invalid response is returned
401 assert path.startswith("/")
403 curl = self._CreateCurl()
405 if content is not None:
406 encoded_content = self._json_encoder.encode(content)
411 urlparts = [self._base_url, path]
414 urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
416 url = "".join(urlparts)
418 self._logger.debug("Sending request %s %s (content=%r)",
419 method, url, encoded_content)
421 # Buffer for response
422 encoded_resp_body = StringIO()
425 curl.setopt(pycurl.CUSTOMREQUEST, str(method))
426 curl.setopt(pycurl.URL, str(url))
427 curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
428 curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
431 # Send request and wait for response
434 except pycurl.error, err:
435 if err.args[0] in _CURL_SSL_CERT_ERRORS:
436 raise CertificateError("SSL certificate error %s" % err)
438 raise GanetiApiError(str(err))
440 # Reset settings to not keep references to large objects in memory
442 curl.setopt(pycurl.POSTFIELDS, "")
443 curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)
445 # Get HTTP response code
446 http_code = curl.getinfo(pycurl.RESPONSE_CODE)
448 # Was anything written to the response buffer?
449 if encoded_resp_body.tell():
450 response_content = simplejson.loads(encoded_resp_body.getvalue())
452 response_content = None
454 if http_code != HTTP_OK:
455 if isinstance(response_content, dict):
457 (response_content["code"],
458 response_content["message"],
459 response_content["explain"]))
461 msg = str(response_content)
463 raise GanetiApiError(msg, code=http_code)
465 return response_content
467 def GetVersion(self):
468 """Gets the Remote API version running on the cluster.
471 @return: Ganeti Remote API version
474 return self._SendRequest(HTTP_GET, "/version", None, None)
476 def GetFeatures(self):
477 """Gets the list of optional features supported by RAPI server.
480 @return: List of optional features
484 return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
486 except GanetiApiError, err:
487 # Older RAPI servers don't support this resource
488 if err.code == HTTP_NOT_FOUND:
493 def GetOperatingSystems(self):
494 """Gets the Operating Systems running in the Ganeti cluster.
497 @return: operating systems
500 return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
504 """Gets info about the cluster.
507 @return: information about the cluster
510 return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
513 def RedistributeConfig(self):
514 """Tells the cluster to redistribute its configuration files.
520 return self._SendRequest(HTTP_PUT,
521 "/%s/redistribute-config" % GANETI_RAPI_VERSION,
524 def ModifyCluster(self, **kwargs):
525 """Modifies cluster parameters.
527 More details for parameters can be found in the RAPI documentation.
535 return self._SendRequest(HTTP_PUT,
536 "/%s/modify" % GANETI_RAPI_VERSION, None, body)
538 def GetClusterTags(self):
539 """Gets the cluster tags.
542 @return: cluster tags
545 return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
548 def AddClusterTags(self, tags, dry_run=False):
549 """Adds tags to the cluster.
551 @type tags: list of str
552 @param tags: tags to add to the cluster
554 @param dry_run: whether to perform a dry run
560 query = [("tag", t) for t in tags]
562 query.append(("dry-run", 1))
564 return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
567 def DeleteClusterTags(self, tags, dry_run=False):
568 """Deletes tags from the cluster.
570 @type tags: list of str
571 @param tags: tags to delete
573 @param dry_run: whether to perform a dry run
578 query = [("tag", t) for t in tags]
580 query.append(("dry-run", 1))
582 return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
585 def GetInstances(self, bulk=False):
586 """Gets information about instances on the cluster.
589 @param bulk: whether to return all information about all instances
591 @rtype: list of dict or list of str
592 @return: if bulk is True, info about the instances, else a list of instances
597 query.append(("bulk", 1))
599 instances = self._SendRequest(HTTP_GET,
600 "/%s/instances" % GANETI_RAPI_VERSION,
605 return [i["id"] for i in instances]
607 def GetInstance(self, instance):
608 """Gets information about an instance.
611 @param instance: instance whose info to return
614 @return: info about the instance
617 return self._SendRequest(HTTP_GET,
618 ("/%s/instances/%s" %
619 (GANETI_RAPI_VERSION, instance)), None, None)
621 def GetInstanceInfo(self, instance, static=None):
622 """Gets information about an instance.
624 @type instance: string
625 @param instance: Instance name
630 if static is not None:
631 query = [("static", static)]
635 return self._SendRequest(HTTP_GET,
636 ("/%s/instances/%s/info" %
637 (GANETI_RAPI_VERSION, instance)), query, None)
639 def CreateInstance(self, mode, name, disk_template, disks, nics,
641 """Creates a new instance.
643 More details for parameters can be found in the RAPI documentation.
646 @param mode: Instance creation mode
648 @param name: Hostname of the instance to create
649 @type disk_template: string
650 @param disk_template: Disk template for instance (e.g. plain, diskless,
652 @type disks: list of dicts
653 @param disks: List of disk definitions
654 @type nics: list of dicts
655 @param nics: List of NIC definitions
657 @keyword dry_run: whether to perform a dry run
665 if kwargs.get("dry_run"):
666 query.append(("dry-run", 1))
668 if _INST_CREATE_REQV1 in self.GetFeatures():
669 # All required fields for request data version 1
671 _REQ_DATA_VERSION_FIELD: 1,
674 "disk_template": disk_template,
679 conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
681 raise GanetiApiError("Required fields can not be specified as"
682 " keywords: %s" % ", ".join(conflicts))
684 body.update((key, value) for key, value in kwargs.iteritems()
687 raise GanetiApiError("Server does not support new-style (version 1)"
688 " instance creation requests")
690 return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
693 def DeleteInstance(self, instance, dry_run=False):
694 """Deletes an instance.
697 @param instance: the instance to delete
705 query.append(("dry-run", 1))
707 return self._SendRequest(HTTP_DELETE,
708 ("/%s/instances/%s" %
709 (GANETI_RAPI_VERSION, instance)), query, None)
711 def ModifyInstance(self, instance, **kwargs):
712 """Modifies an instance.
714 More details for parameters can be found in the RAPI documentation.
716 @type instance: string
717 @param instance: Instance name
724 return self._SendRequest(HTTP_PUT,
725 ("/%s/instances/%s/modify" %
726 (GANETI_RAPI_VERSION, instance)), None, body)
728 def ActivateInstanceDisks(self, instance, ignore_size=None):
729 """Activates an instance's disks.
731 @type instance: string
732 @param instance: Instance name
733 @type ignore_size: bool
734 @param ignore_size: Whether to ignore recorded size
741 query.append(("ignore_size", 1))
743 return self._SendRequest(HTTP_PUT,
744 ("/%s/instances/%s/activate-disks" %
745 (GANETI_RAPI_VERSION, instance)), query, None)
747 def DeactivateInstanceDisks(self, instance):
748 """Deactivates an instance's disks.
750 @type instance: string
751 @param instance: Instance name
756 return self._SendRequest(HTTP_PUT,
757 ("/%s/instances/%s/deactivate-disks" %
758 (GANETI_RAPI_VERSION, instance)), None, None)
760 def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
761 """Grows a disk of an instance.
763 More details for parameters can be found in the RAPI documentation.
765 @type instance: string
766 @param instance: Instance name
768 @param disk: Disk index
769 @type amount: integer
770 @param amount: Grow disk by this amount (MiB)
771 @type wait_for_sync: bool
772 @param wait_for_sync: Wait for disk to synchronize
781 if wait_for_sync is not None:
782 body["wait_for_sync"] = wait_for_sync
784 return self._SendRequest(HTTP_POST,
785 ("/%s/instances/%s/disk/%s/grow" %
786 (GANETI_RAPI_VERSION, instance, disk)),
789 def GetInstanceTags(self, instance):
790 """Gets tags for an instance.
793 @param instance: instance whose tags to return
796 @return: tags for the instance
799 return self._SendRequest(HTTP_GET,
800 ("/%s/instances/%s/tags" %
801 (GANETI_RAPI_VERSION, instance)), None, None)
803 def AddInstanceTags(self, instance, tags, dry_run=False):
804 """Adds tags to an instance.
807 @param instance: instance to add tags to
808 @type tags: list of str
809 @param tags: tags to add to the instance
811 @param dry_run: whether to perform a dry run
817 query = [("tag", t) for t in tags]
819 query.append(("dry-run", 1))
821 return self._SendRequest(HTTP_PUT,
822 ("/%s/instances/%s/tags" %
823 (GANETI_RAPI_VERSION, instance)), query, None)
825 def DeleteInstanceTags(self, instance, tags, dry_run=False):
826 """Deletes tags from an instance.
829 @param instance: instance to delete tags from
830 @type tags: list of str
831 @param tags: tags to delete
833 @param dry_run: whether to perform a dry run
838 query = [("tag", t) for t in tags]
840 query.append(("dry-run", 1))
842 return self._SendRequest(HTTP_DELETE,
843 ("/%s/instances/%s/tags" %
844 (GANETI_RAPI_VERSION, instance)), query, None)
846 def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
848 """Reboots an instance.
851 @param instance: instance to rebot
852 @type reboot_type: str
853 @param reboot_type: one of: hard, soft, full
854 @type ignore_secondaries: bool
855 @param ignore_secondaries: if True, ignores errors for the secondary node
856 while re-assembling disks (in hard-reboot mode only)
858 @param dry_run: whether to perform a dry run
865 query.append(("type", reboot_type))
866 if ignore_secondaries is not None:
867 query.append(("ignore_secondaries", ignore_secondaries))
869 query.append(("dry-run", 1))
871 return self._SendRequest(HTTP_POST,
872 ("/%s/instances/%s/reboot" %
873 (GANETI_RAPI_VERSION, instance)), query, None)
875 def ShutdownInstance(self, instance, dry_run=False, no_remember=False):
876 """Shuts down an instance.
879 @param instance: the instance to shut down
881 @param dry_run: whether to perform a dry run
882 @type no_remember: bool
883 @param no_remember: if true, will not record the state change
890 query.append(("dry-run", 1))
892 query.append(("no-remember", 1))
894 return self._SendRequest(HTTP_PUT,
895 ("/%s/instances/%s/shutdown" %
896 (GANETI_RAPI_VERSION, instance)), query, None)
898 def StartupInstance(self, instance, dry_run=False, no_remember=False):
899 """Starts up an instance.
902 @param instance: the instance to start up
904 @param dry_run: whether to perform a dry run
905 @type no_remember: bool
906 @param no_remember: if true, will not record the state change
913 query.append(("dry-run", 1))
915 query.append(("no-remember", 1))
917 return self._SendRequest(HTTP_PUT,
918 ("/%s/instances/%s/startup" %
919 (GANETI_RAPI_VERSION, instance)), query, None)
921 def ReinstallInstance(self, instance, os=None, no_startup=False,
923 """Reinstalls an instance.
926 @param instance: The instance to reinstall
927 @type os: str or None
928 @param os: The operating system to reinstall. If None, the instance's
929 current operating system will be installed again
930 @type no_startup: bool
931 @param no_startup: Whether to start the instance automatically
936 if _INST_REINSTALL_REQV1 in self.GetFeatures():
938 "start": not no_startup,
942 if osparams is not None:
943 body["osparams"] = osparams
944 return self._SendRequest(HTTP_POST,
945 ("/%s/instances/%s/reinstall" %
946 (GANETI_RAPI_VERSION, instance)), None, body)
948 # Use old request format
950 raise GanetiApiError("Server does not support specifying OS parameters"
951 " for instance reinstallation")
955 query.append(("os", os))
957 query.append(("nostartup", 1))
958 return self._SendRequest(HTTP_POST,
959 ("/%s/instances/%s/reinstall" %
960 (GANETI_RAPI_VERSION, instance)), query, None)
962 def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
963 remote_node=None, iallocator=None):
964 """Replaces disks on an instance.
967 @param instance: instance whose disks to replace
968 @type disks: list of ints
969 @param disks: Indexes of disks to replace
971 @param mode: replacement mode to use (defaults to replace_auto)
972 @type remote_node: str or None
973 @param remote_node: new secondary node to use (for use with
974 replace_new_secondary mode)
975 @type iallocator: str or None
976 @param iallocator: instance allocator plugin to use (for use with
987 # TODO: Convert to body parameters
989 if disks is not None:
990 query.append(("disks", ",".join(str(idx) for idx in disks)))
992 if remote_node is not None:
993 query.append(("remote_node", remote_node))
995 if iallocator is not None:
996 query.append(("iallocator", iallocator))
998 return self._SendRequest(HTTP_POST,
999 ("/%s/instances/%s/replace-disks" %
1000 (GANETI_RAPI_VERSION, instance)), query, None)
1002 def PrepareExport(self, instance, mode):
1003 """Prepares an instance for an export.
1005 @type instance: string
1006 @param instance: Instance name
1008 @param mode: Export mode
1013 query = [("mode", mode)]
1014 return self._SendRequest(HTTP_PUT,
1015 ("/%s/instances/%s/prepare-export" %
1016 (GANETI_RAPI_VERSION, instance)), query, None)
1018 def ExportInstance(self, instance, mode, destination, shutdown=None,
1019 remove_instance=None,
1020 x509_key_name=None, destination_x509_ca=None):
1021 """Exports an instance.
1023 @type instance: string
1024 @param instance: Instance name
1026 @param mode: Export mode
1032 "destination": destination,
1036 if shutdown is not None:
1037 body["shutdown"] = shutdown
1039 if remove_instance is not None:
1040 body["remove_instance"] = remove_instance
1042 if x509_key_name is not None:
1043 body["x509_key_name"] = x509_key_name
1045 if destination_x509_ca is not None:
1046 body["destination_x509_ca"] = destination_x509_ca
1048 return self._SendRequest(HTTP_PUT,
1049 ("/%s/instances/%s/export" %
1050 (GANETI_RAPI_VERSION, instance)), None, body)
1052 def MigrateInstance(self, instance, mode=None, cleanup=None):
1053 """Migrates an instance.
1055 @type instance: string
1056 @param instance: Instance name
1058 @param mode: Migration mode
1060 @param cleanup: Whether to clean up a previously failed migration
1067 if mode is not None:
1070 if cleanup is not None:
1071 body["cleanup"] = cleanup
1073 return self._SendRequest(HTTP_PUT,
1074 ("/%s/instances/%s/migrate" %
1075 (GANETI_RAPI_VERSION, instance)), None, body)
1077 def FailoverInstance(self, instance, iallocator=None,
1078 ignore_consistency=None, target_node=None):
1079 """Does a failover of an instance.
1081 @type instance: string
1082 @param instance: Instance name
1083 @type iallocator: string
1084 @param iallocator: Iallocator for deciding the target node for
1085 shared-storage instances
1086 @type ignore_consistency: bool
1087 @param ignore_consistency: Whether to ignore disk consistency
1088 @type target_node: string
1089 @param target_node: Target node for shared-storage instances
1096 if iallocator is not None:
1097 body["iallocator"] = iallocator
1099 if ignore_consistency is not None:
1100 body["ignore_consistency"] = ignore_consistency
1102 if target_node is not None:
1103 body["target_node"] = target_node
1105 return self._SendRequest(HTTP_PUT,
1106 ("/%s/instances/%s/failover" %
1107 (GANETI_RAPI_VERSION, instance)), None, body)
1109 def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
1110 """Changes the name of an instance.
1112 @type instance: string
1113 @param instance: Instance name
1114 @type new_name: string
1115 @param new_name: New instance name
1116 @type ip_check: bool
1117 @param ip_check: Whether to ensure instance's IP address is inactive
1118 @type name_check: bool
1119 @param name_check: Whether to ensure instance's name is resolvable
1125 "new_name": new_name,
1128 if ip_check is not None:
1129 body["ip_check"] = ip_check
1131 if name_check is not None:
1132 body["name_check"] = name_check
1134 return self._SendRequest(HTTP_PUT,
1135 ("/%s/instances/%s/rename" %
1136 (GANETI_RAPI_VERSION, instance)), None, body)
1138 def GetInstanceConsole(self, instance):
1139 """Request information for connecting to instance's console.
1141 @type instance: string
1142 @param instance: Instance name
1144 @return: dictionary containing information about instance's console
1147 return self._SendRequest(HTTP_GET,
1148 ("/%s/instances/%s/console" %
1149 (GANETI_RAPI_VERSION, instance)), None, None)
1152 """Gets all jobs for the cluster.
1155 @return: job ids for the cluster
1158 return [int(j["id"])
1159 for j in self._SendRequest(HTTP_GET,
1160 "/%s/jobs" % GANETI_RAPI_VERSION,
1163 def GetJobStatus(self, job_id):
1164 """Gets the status of a job.
1166 @type job_id: string
1167 @param job_id: job id whose status to query
1173 return self._SendRequest(HTTP_GET,
1174 "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1177 def WaitForJobCompletion(self, job_id, period=5, retries=-1):
1178 """Polls cluster for job status until completion.
1180 Completion is defined as any of the following states listed in
1181 L{JOB_STATUS_FINALIZED}.
1183 @type job_id: string
1184 @param job_id: job id to watch
1186 @param period: how often to poll for status (optional, default 5s)
1188 @param retries: how many time to poll before giving up
1189 (optional, default -1 means unlimited)
1192 @return: C{True} if job succeeded or C{False} if failed/status timeout
1193 @deprecated: It is recommended to use L{WaitForJobChange} wherever
1194 possible; L{WaitForJobChange} returns immediately after a job changed and
1195 does not use polling
1199 job_result = self.GetJobStatus(job_id)
1201 if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
1203 elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
1214 def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1215 """Waits for job changes.
1217 @type job_id: string
1218 @param job_id: Job ID for which to wait
1219 @return: C{None} if no changes have been detected and a dict with two keys,
1220 C{job_info} and C{log_entries} otherwise.
1226 "previous_job_info": prev_job_info,
1227 "previous_log_serial": prev_log_serial,
1230 return self._SendRequest(HTTP_GET,
1231 "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1234 def CancelJob(self, job_id, dry_run=False):
1237 @type job_id: string
1238 @param job_id: id of the job to delete
1240 @param dry_run: whether to perform a dry run
1242 @return: tuple containing the result, and a message (bool, string)
1247 query.append(("dry-run", 1))
1249 return self._SendRequest(HTTP_DELETE,
1250 "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1253 def GetNodes(self, bulk=False):
1254 """Gets all nodes in the cluster.
1257 @param bulk: whether to return all information about all instances
1259 @rtype: list of dict or str
1260 @return: if bulk is true, info about nodes in the cluster,
1261 else list of nodes in the cluster
1266 query.append(("bulk", 1))
1268 nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1273 return [n["id"] for n in nodes]
1275 def GetNode(self, node):
1276 """Gets information about a node.
1279 @param node: node whose info to return
1282 @return: info about the node
1285 return self._SendRequest(HTTP_GET,
1286 "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1289 def EvacuateNode(self, node, iallocator=None, remote_node=None,
1290 dry_run=False, early_release=None,
1291 mode=None, accept_old=False):
1292 """Evacuates instances from a Ganeti node.
1295 @param node: node to evacuate
1296 @type iallocator: str or None
1297 @param iallocator: instance allocator to use
1298 @type remote_node: str
1299 @param remote_node: node to evaucate to
1301 @param dry_run: whether to perform a dry run
1302 @type early_release: bool
1303 @param early_release: whether to enable parallelization
1305 @param mode: Node evacuation mode
1306 @type accept_old: bool
1307 @param accept_old: Whether caller is ready to accept old-style (pre-2.5)
1310 @rtype: string, or a list for pre-2.5 results
1311 @return: Job ID or, if C{accept_old} is set and server is pre-2.5,
1312 list of (job ID, instance name, new secondary node); if dry_run was
1313 specified, then the actual move jobs were not submitted and the job IDs
1316 @raises GanetiApiError: if an iallocator and remote_node are both
1320 if iallocator and remote_node:
1321 raise GanetiApiError("Only one of iallocator or remote_node can be used")
1325 query.append(("dry-run", 1))
1327 if _NODE_EVAC_RES1 in self.GetFeatures():
1328 # Server supports body parameters
1331 if iallocator is not None:
1332 body["iallocator"] = iallocator
1333 if remote_node is not None:
1334 body["remote_node"] = remote_node
1335 if early_release is not None:
1336 body["early_release"] = early_release
1337 if mode is not None:
1340 # Pre-2.5 request format
1344 raise GanetiApiError("Server is version 2.4 or earlier and caller does"
1345 " not accept old-style results (parameter"
1348 # Pre-2.5 servers can only evacuate secondaries
1349 if mode is not None and mode != NODE_EVAC_SEC:
1350 raise GanetiApiError("Server can only evacuate secondary instances")
1353 query.append(("iallocator", iallocator))
1355 query.append(("remote_node", remote_node))
1357 query.append(("early_release", 1))
1359 return self._SendRequest(HTTP_POST,
1360 ("/%s/nodes/%s/evacuate" %
1361 (GANETI_RAPI_VERSION, node)), query, body)
1363 def MigrateNode(self, node, mode=None, dry_run=False, iallocator=None,
1365 """Migrates all primary instances from a node.
1368 @param node: node to migrate
1370 @param mode: if passed, it will overwrite the live migration type,
1371 otherwise the hypervisor default will be used
1373 @param dry_run: whether to perform a dry run
1374 @type iallocator: string
1375 @param iallocator: instance allocator to use
1376 @type target_node: string
1377 @param target_node: Target node for shared-storage instances
1385 query.append(("dry-run", 1))
1387 if _NODE_MIGRATE_REQV1 in self.GetFeatures():
1390 if mode is not None:
1392 if iallocator is not None:
1393 body["iallocator"] = iallocator
1394 if target_node is not None:
1395 body["target_node"] = target_node
1397 assert len(query) <= 1
1399 return self._SendRequest(HTTP_POST,
1400 ("/%s/nodes/%s/migrate" %
1401 (GANETI_RAPI_VERSION, node)), query, body)
1403 # Use old request format
1404 if target_node is not None:
1405 raise GanetiApiError("Server does not support specifying target node"
1406 " for node migration")
1408 if mode is not None:
1409 query.append(("mode", mode))
1411 return self._SendRequest(HTTP_POST,
1412 ("/%s/nodes/%s/migrate" %
1413 (GANETI_RAPI_VERSION, node)), query, None)
1415 def GetNodeRole(self, node):
1416 """Gets the current role for a node.
1419 @param node: node whose role to return
1422 @return: the current role for a node
1425 return self._SendRequest(HTTP_GET,
1426 ("/%s/nodes/%s/role" %
1427 (GANETI_RAPI_VERSION, node)), None, None)
1429 def SetNodeRole(self, node, role, force=False, auto_promote=None):
1430 """Sets the role for a node.
1433 @param node: the node whose role to set
1435 @param role: the role to set for the node
1437 @param force: whether to force the role change
1438 @type auto_promote: bool
1439 @param auto_promote: Whether node(s) should be promoted to master candidate
1450 if auto_promote is not None:
1451 query.append(("auto-promote", auto_promote))
1453 return self._SendRequest(HTTP_PUT,
1454 ("/%s/nodes/%s/role" %
1455 (GANETI_RAPI_VERSION, node)), query, role)
1457 def ModifyNode(self, node, **kwargs):
1460 More details for parameters can be found in the RAPI documentation.
1463 @param node: Node name
1468 return self._SendRequest(HTTP_POST,
1469 ("/%s/nodes/%s/modify" %
1470 (GANETI_RAPI_VERSION, node)), None, kwargs)
1472 def GetNodeStorageUnits(self, node, storage_type, output_fields):
1473 """Gets the storage units for a node.
1476 @param node: the node whose storage units to return
1477 @type storage_type: str
1478 @param storage_type: storage type whose units to return
1479 @type output_fields: str
1480 @param output_fields: storage type fields to return
1483 @return: job id where results can be retrieved
1487 ("storage_type", storage_type),
1488 ("output_fields", output_fields),
1491 return self._SendRequest(HTTP_GET,
1492 ("/%s/nodes/%s/storage" %
1493 (GANETI_RAPI_VERSION, node)), query, None)
1495 def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1496 """Modifies parameters of storage units on the node.
1499 @param node: node whose storage units to modify
1500 @type storage_type: str
1501 @param storage_type: storage type whose units to modify
1503 @param name: name of the storage unit
1504 @type allocatable: bool or None
1505 @param allocatable: Whether to set the "allocatable" flag on the storage
1506 unit (None=no modification, True=set, False=unset)
1513 ("storage_type", storage_type),
1517 if allocatable is not None:
1518 query.append(("allocatable", allocatable))
1520 return self._SendRequest(HTTP_PUT,
1521 ("/%s/nodes/%s/storage/modify" %
1522 (GANETI_RAPI_VERSION, node)), query, None)
1524 def RepairNodeStorageUnits(self, node, storage_type, name):
1525 """Repairs a storage unit on the node.
1528 @param node: node whose storage units to repair
1529 @type storage_type: str
1530 @param storage_type: storage type to repair
1532 @param name: name of the storage unit to repair
1539 ("storage_type", storage_type),
1543 return self._SendRequest(HTTP_PUT,
1544 ("/%s/nodes/%s/storage/repair" %
1545 (GANETI_RAPI_VERSION, node)), query, None)
1547 def GetNodeTags(self, node):
1548 """Gets the tags for a node.
1551 @param node: node whose tags to return
1554 @return: tags for the node
1557 return self._SendRequest(HTTP_GET,
1558 ("/%s/nodes/%s/tags" %
1559 (GANETI_RAPI_VERSION, node)), None, None)
1561 def AddNodeTags(self, node, tags, dry_run=False):
1562 """Adds tags to a node.
1565 @param node: node to add tags to
1566 @type tags: list of str
1567 @param tags: tags to add to the node
1569 @param dry_run: whether to perform a dry run
1575 query = [("tag", t) for t in tags]
1577 query.append(("dry-run", 1))
1579 return self._SendRequest(HTTP_PUT,
1580 ("/%s/nodes/%s/tags" %
1581 (GANETI_RAPI_VERSION, node)), query, tags)
1583 def DeleteNodeTags(self, node, tags, dry_run=False):
1584 """Delete tags from a node.
1587 @param node: node to remove tags from
1588 @type tags: list of str
1589 @param tags: tags to remove from the node
1591 @param dry_run: whether to perform a dry run
1597 query = [("tag", t) for t in tags]
1599 query.append(("dry-run", 1))
1601 return self._SendRequest(HTTP_DELETE,
1602 ("/%s/nodes/%s/tags" %
1603 (GANETI_RAPI_VERSION, node)), query, None)
1605 def GetGroups(self, bulk=False):
1606 """Gets all node groups in the cluster.
1609 @param bulk: whether to return all information about the groups
1611 @rtype: list of dict or str
1612 @return: if bulk is true, a list of dictionaries with info about all node
1613 groups in the cluster, else a list of names of those node groups
1618 query.append(("bulk", 1))
1620 groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1625 return [g["name"] for g in groups]
1627 def GetGroup(self, group):
1628 """Gets information about a node group.
1631 @param group: name of the node group whose info to return
1634 @return: info about the node group
1637 return self._SendRequest(HTTP_GET,
1638 "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
1641 def CreateGroup(self, name, alloc_policy=None, dry_run=False):
1642 """Creates a new node group.
1645 @param name: the name of node group to create
1646 @type alloc_policy: str
1647 @param alloc_policy: the desired allocation policy for the group, if any
1649 @param dry_run: whether to peform a dry run
1657 query.append(("dry-run", 1))
1661 "alloc_policy": alloc_policy
1664 return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1667 def ModifyGroup(self, group, **kwargs):
1668 """Modifies a node group.
1670 More details for parameters can be found in the RAPI documentation.
1673 @param group: Node group name
1678 return self._SendRequest(HTTP_PUT,
1679 ("/%s/groups/%s/modify" %
1680 (GANETI_RAPI_VERSION, group)), None, kwargs)
1682 def DeleteGroup(self, group, dry_run=False):
1683 """Deletes a node group.
1686 @param group: the node group to delete
1688 @param dry_run: whether to peform a dry run
1696 query.append(("dry-run", 1))
1698 return self._SendRequest(HTTP_DELETE,
1700 (GANETI_RAPI_VERSION, group)), query, None)
1702 def RenameGroup(self, group, new_name):
1703 """Changes the name of a node group.
1706 @param group: Node group name
1707 @type new_name: string
1708 @param new_name: New node group name
1715 "new_name": new_name,
1718 return self._SendRequest(HTTP_PUT,
1719 ("/%s/groups/%s/rename" %
1720 (GANETI_RAPI_VERSION, group)), None, body)
1722 def AssignGroupNodes(self, group, nodes, force=False, dry_run=False):
1723 """Assigns nodes to a group.
1726 @param group: Node gropu name
1727 @type nodes: list of strings
1728 @param nodes: List of nodes to assign to the group
1737 query.append(("force", 1))
1740 query.append(("dry-run", 1))
1746 return self._SendRequest(HTTP_PUT,
1747 ("/%s/groups/%s/assign-nodes" %
1748 (GANETI_RAPI_VERSION, group)), query, body)
1750 def GetGroupTags(self, group):
1751 """Gets tags for a node group.
1754 @param group: Node group whose tags to return
1756 @rtype: list of strings
1757 @return: tags for the group
1760 return self._SendRequest(HTTP_GET,
1761 ("/%s/groups/%s/tags" %
1762 (GANETI_RAPI_VERSION, group)), None, None)
1764 def AddGroupTags(self, group, tags, dry_run=False):
1765 """Adds tags to a node group.
1768 @param group: group to add tags to
1769 @type tags: list of string
1770 @param tags: tags to add to the group
1772 @param dry_run: whether to perform a dry run
1778 query = [("tag", t) for t in tags]
1780 query.append(("dry-run", 1))
1782 return self._SendRequest(HTTP_PUT,
1783 ("/%s/groups/%s/tags" %
1784 (GANETI_RAPI_VERSION, group)), query, None)
1786 def DeleteGroupTags(self, group, tags, dry_run=False):
1787 """Deletes tags from a node group.
1790 @param group: group to delete tags from
1791 @type tags: list of string
1792 @param tags: tags to delete
1794 @param dry_run: whether to perform a dry run
1799 query = [("tag", t) for t in tags]
1801 query.append(("dry-run", 1))
1803 return self._SendRequest(HTTP_DELETE,
1804 ("/%s/groups/%s/tags" %
1805 (GANETI_RAPI_VERSION, group)), query, None)
1807 def Query(self, what, fields, filter_=None):
1808 """Retrieves information about resources.
1811 @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1812 @type fields: list of string
1813 @param fields: Requested fields
1814 @type filter_: None or list
1815 @param filter_: Query filter
1825 if filter_ is not None:
1826 body["filter"] = filter_
1828 return self._SendRequest(HTTP_PUT,
1830 (GANETI_RAPI_VERSION, what)), None, body)
1832 def QueryFields(self, what, fields=None):
1833 """Retrieves available fields for a resource.
1836 @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1837 @type fields: list of string
1838 @param fields: Requested fields
1846 if fields is not None:
1847 query.append(("fields", ",".join(fields)))
1849 return self._SendRequest(HTTP_GET,
1850 ("/%s/query/%s/fields" %
1851 (GANETI_RAPI_VERSION, what)), query, None)