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_ROLE_DRAINED = "drained"
67 NODE_ROLE_MASTER_CANDIATE = "master-candidate"
68 NODE_ROLE_MASTER = "master"
69 NODE_ROLE_OFFLINE = "offline"
70 NODE_ROLE_REGULAR = "regular"
72 JOB_STATUS_QUEUED = "queued"
73 JOB_STATUS_WAITLOCK = "waiting"
74 JOB_STATUS_CANCELING = "canceling"
75 JOB_STATUS_RUNNING = "running"
76 JOB_STATUS_CANCELED = "canceled"
77 JOB_STATUS_SUCCESS = "success"
78 JOB_STATUS_ERROR = "error"
79 JOB_STATUS_FINALIZED = frozenset([
84 JOB_STATUS_ALL = frozenset([
89 ]) | JOB_STATUS_FINALIZED
92 _REQ_DATA_VERSION_FIELD = "__version__"
93 _INST_CREATE_REQV1 = "instance-create-reqv1"
94 _INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
95 _INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link"])
96 _INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
97 _INST_CREATE_V0_PARAMS = frozenset([
98 "os", "pnode", "snode", "iallocator", "start", "ip_check", "name_check",
99 "hypervisor", "file_storage_dir", "file_driver", "dry_run",
101 _INST_CREATE_V0_DPARAMS = frozenset(["beparams", "hvparams"])
103 # Older pycURL versions don't have all error constants
105 _CURLE_SSL_CACERT = pycurl.E_SSL_CACERT
106 _CURLE_SSL_CACERT_BADFILE = pycurl.E_SSL_CACERT_BADFILE
107 except AttributeError:
108 _CURLE_SSL_CACERT = 60
109 _CURLE_SSL_CACERT_BADFILE = 77
111 _CURL_SSL_CERT_ERRORS = frozenset([
113 _CURLE_SSL_CACERT_BADFILE,
117 class Error(Exception):
118 """Base error class for this module.
124 class CertificateError(Error):
125 """Raised when a problem is found with the SSL certificate.
131 class GanetiApiError(Error):
132 """Generic error raised from Ganeti API.
135 def __init__(self, msg, code=None):
136 Error.__init__(self, msg)
140 def UsesRapiClient(fn):
141 """Decorator for code using RAPI client to initialize pycURL.
144 def wrapper(*args, **kwargs):
145 # curl_global_init(3) and curl_global_cleanup(3) must be called with only
146 # one thread running. This check is just a safety measure -- it doesn't
148 assert threading.activeCount() == 1, \
149 "Found active threads when initializing pycURL"
151 pycurl.global_init(pycurl.GLOBAL_ALL)
153 return fn(*args, **kwargs)
155 pycurl.global_cleanup()
160 def GenericCurlConfig(verbose=False, use_signal=False,
161 use_curl_cabundle=False, cafile=None, capath=None,
162 proxy=None, verify_hostname=False,
163 connect_timeout=None, timeout=None,
164 _pycurl_version_fn=pycurl.version_info):
165 """Curl configuration function generator.
168 @param verbose: Whether to set cURL to verbose mode
169 @type use_signal: bool
170 @param use_signal: Whether to allow cURL to use signals
171 @type use_curl_cabundle: bool
172 @param use_curl_cabundle: Whether to use cURL's default CA bundle
174 @param cafile: In which file we can find the certificates
176 @param capath: In which directory we can find the certificates
178 @param proxy: Proxy to use, None for default behaviour and empty string for
179 disabling proxies (see curl_easy_setopt(3))
180 @type verify_hostname: bool
181 @param verify_hostname: Whether to verify the remote peer certificate's
183 @type connect_timeout: number
184 @param connect_timeout: Timeout for establishing connection in seconds
185 @type timeout: number
186 @param timeout: Timeout for complete transfer in seconds (see
187 curl_easy_setopt(3)).
190 if use_curl_cabundle and (cafile or capath):
191 raise Error("Can not use default CA bundle when CA file or path is set")
193 def _ConfigCurl(curl, logger):
194 """Configures a cURL object
196 @type curl: pycurl.Curl
197 @param curl: cURL object
200 logger.debug("Using cURL version %s", pycurl.version)
202 # pycurl.version_info returns a tuple with information about the used
203 # version of libcurl. Item 5 is the SSL library linked to it.
204 # e.g.: (3, '7.18.0', 463360, 'x86_64-pc-linux-gnu', 1581, 'GnuTLS/2.0.4',
206 sslver = _pycurl_version_fn()[5]
208 raise Error("No SSL support in cURL")
210 lcsslver = sslver.lower()
211 if lcsslver.startswith("openssl/"):
213 elif lcsslver.startswith("gnutls/"):
215 raise Error("cURL linked against GnuTLS has no support for a"
216 " CA path (%s)" % (pycurl.version, ))
218 raise NotImplementedError("cURL uses unsupported SSL version '%s'" %
221 curl.setopt(pycurl.VERBOSE, verbose)
222 curl.setopt(pycurl.NOSIGNAL, not use_signal)
224 # Whether to verify remote peer's CN
226 # curl_easy_setopt(3): "When CURLOPT_SSL_VERIFYHOST is 2, that
227 # certificate must indicate that the server is the server to which you
228 # meant to connect, or the connection fails. [...] When the value is 1,
229 # the certificate must contain a Common Name field, but it doesn't matter
230 # what name it says. [...]"
231 curl.setopt(pycurl.SSL_VERIFYHOST, 2)
233 curl.setopt(pycurl.SSL_VERIFYHOST, 0)
235 if cafile or capath or use_curl_cabundle:
236 # Require certificates to be checked
237 curl.setopt(pycurl.SSL_VERIFYPEER, True)
239 curl.setopt(pycurl.CAINFO, str(cafile))
241 curl.setopt(pycurl.CAPATH, str(capath))
242 # Not changing anything for using default CA bundle
244 # Disable SSL certificate verification
245 curl.setopt(pycurl.SSL_VERIFYPEER, False)
247 if proxy is not None:
248 curl.setopt(pycurl.PROXY, str(proxy))
251 if connect_timeout is not None:
252 curl.setopt(pycurl.CONNECTTIMEOUT, connect_timeout)
253 if timeout is not None:
254 curl.setopt(pycurl.TIMEOUT, timeout)
259 class GanetiRapiClient(object): # pylint: disable-msg=R0904
260 """Ganeti RAPI client.
263 USER_AGENT = "Ganeti RAPI Client"
264 _json_encoder = simplejson.JSONEncoder(sort_keys=True)
266 def __init__(self, host, port=GANETI_RAPI_PORT,
267 username=None, password=None, logger=logging,
268 curl_config_fn=None, curl_factory=None):
269 """Initializes this class.
272 @param host: the ganeti cluster master to interact with
274 @param port: the port on which the RAPI is running (default is 5080)
275 @type username: string
276 @param username: the username to connect with
277 @type password: string
278 @param password: the password to connect with
279 @type curl_config_fn: callable
280 @param curl_config_fn: Function to configure C{pycurl.Curl} object
281 @param logger: Logging object
284 self._username = username
285 self._password = password
286 self._logger = logger
287 self._curl_config_fn = curl_config_fn
288 self._curl_factory = curl_factory
291 socket.inet_pton(socket.AF_INET6, host)
292 address = "[%s]:%s" % (host, port)
294 address = "%s:%s" % (host, port)
296 self._base_url = "https://%s" % address
298 if username is not None:
300 raise Error("Password not specified")
302 raise Error("Specified password without username")
304 def _CreateCurl(self):
305 """Creates a cURL object.
308 # Create pycURL object if no factory is provided
309 if self._curl_factory:
310 curl = self._curl_factory()
314 # Default cURL settings
315 curl.setopt(pycurl.VERBOSE, False)
316 curl.setopt(pycurl.FOLLOWLOCATION, False)
317 curl.setopt(pycurl.MAXREDIRS, 5)
318 curl.setopt(pycurl.NOSIGNAL, True)
319 curl.setopt(pycurl.USERAGENT, self.USER_AGENT)
320 curl.setopt(pycurl.SSL_VERIFYHOST, 0)
321 curl.setopt(pycurl.SSL_VERIFYPEER, False)
322 curl.setopt(pycurl.HTTPHEADER, [
323 "Accept: %s" % HTTP_APP_JSON,
324 "Content-type: %s" % HTTP_APP_JSON,
327 assert ((self._username is None and self._password is None) ^
328 (self._username is not None and self._password is not None))
331 # Setup authentication
332 curl.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
333 curl.setopt(pycurl.USERPWD,
334 str("%s:%s" % (self._username, self._password)))
336 # Call external configuration function
337 if self._curl_config_fn:
338 self._curl_config_fn(curl, self._logger)
343 def _EncodeQuery(query):
344 """Encode query values for RAPI URL.
346 @type query: list of two-tuples
347 @param query: Query arguments
349 @return: Query list with encoded values
354 for name, value in query:
356 result.append((name, ""))
358 elif isinstance(value, bool):
359 # Boolean values must be encoded as 0 or 1
360 result.append((name, int(value)))
362 elif isinstance(value, (list, tuple, dict)):
363 raise ValueError("Invalid query data type %r" % type(value).__name__)
366 result.append((name, value))
370 def _SendRequest(self, method, path, query, content):
371 """Sends an HTTP request.
373 This constructs a full URL, encodes and decodes HTTP bodies, and
374 handles invalid responses in a pythonic way.
377 @param method: HTTP method to use
379 @param path: HTTP URL path
380 @type query: list of two-tuples
381 @param query: query arguments to pass to urllib.urlencode
382 @type content: str or None
383 @param content: HTTP body content
386 @return: JSON-Decoded response
388 @raises CertificateError: If an invalid SSL certificate is found
389 @raises GanetiApiError: If an invalid response is returned
392 assert path.startswith("/")
394 curl = self._CreateCurl()
396 if content is not None:
397 encoded_content = self._json_encoder.encode(content)
402 urlparts = [self._base_url, path]
405 urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
407 url = "".join(urlparts)
409 self._logger.debug("Sending request %s %s (content=%r)",
410 method, url, encoded_content)
412 # Buffer for response
413 encoded_resp_body = StringIO()
416 curl.setopt(pycurl.CUSTOMREQUEST, str(method))
417 curl.setopt(pycurl.URL, str(url))
418 curl.setopt(pycurl.POSTFIELDS, str(encoded_content))
419 curl.setopt(pycurl.WRITEFUNCTION, encoded_resp_body.write)
422 # Send request and wait for response
425 except pycurl.error, err:
426 if err.args[0] in _CURL_SSL_CERT_ERRORS:
427 raise CertificateError("SSL certificate error %s" % err)
429 raise GanetiApiError(str(err))
431 # Reset settings to not keep references to large objects in memory
433 curl.setopt(pycurl.POSTFIELDS, "")
434 curl.setopt(pycurl.WRITEFUNCTION, lambda _: None)
436 # Get HTTP response code
437 http_code = curl.getinfo(pycurl.RESPONSE_CODE)
439 # Was anything written to the response buffer?
440 if encoded_resp_body.tell():
441 response_content = simplejson.loads(encoded_resp_body.getvalue())
443 response_content = None
445 if http_code != HTTP_OK:
446 if isinstance(response_content, dict):
448 (response_content["code"],
449 response_content["message"],
450 response_content["explain"]))
452 msg = str(response_content)
454 raise GanetiApiError(msg, code=http_code)
456 return response_content
458 def GetVersion(self):
459 """Gets the Remote API version running on the cluster.
462 @return: Ganeti Remote API version
465 return self._SendRequest(HTTP_GET, "/version", None, None)
467 def GetFeatures(self):
468 """Gets the list of optional features supported by RAPI server.
471 @return: List of optional features
475 return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION,
477 except GanetiApiError, err:
478 # Older RAPI servers don't support this resource
479 if err.code == HTTP_NOT_FOUND:
484 def GetOperatingSystems(self):
485 """Gets the Operating Systems running in the Ganeti cluster.
488 @return: operating systems
491 return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION,
495 """Gets info about the cluster.
498 @return: information about the cluster
501 return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION,
504 def RedistributeConfig(self):
505 """Tells the cluster to redistribute its configuration files.
511 return self._SendRequest(HTTP_PUT,
512 "/%s/redistribute-config" % GANETI_RAPI_VERSION,
515 def ModifyCluster(self, **kwargs):
516 """Modifies cluster parameters.
518 More details for parameters can be found in the RAPI documentation.
526 return self._SendRequest(HTTP_PUT,
527 "/%s/modify" % GANETI_RAPI_VERSION, None, body)
529 def GetClusterTags(self):
530 """Gets the cluster tags.
533 @return: cluster tags
536 return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION,
539 def AddClusterTags(self, tags, dry_run=False):
540 """Adds tags to the cluster.
542 @type tags: list of str
543 @param tags: tags to add to the cluster
545 @param dry_run: whether to perform a dry run
551 query = [("tag", t) for t in tags]
553 query.append(("dry-run", 1))
555 return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION,
558 def DeleteClusterTags(self, tags, dry_run=False):
559 """Deletes tags from the cluster.
561 @type tags: list of str
562 @param tags: tags to delete
564 @param dry_run: whether to perform a dry run
569 query = [("tag", t) for t in tags]
571 query.append(("dry-run", 1))
573 return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION,
576 def GetInstances(self, bulk=False):
577 """Gets information about instances on the cluster.
580 @param bulk: whether to return all information about all instances
582 @rtype: list of dict or list of str
583 @return: if bulk is True, info about the instances, else a list of instances
588 query.append(("bulk", 1))
590 instances = self._SendRequest(HTTP_GET,
591 "/%s/instances" % GANETI_RAPI_VERSION,
596 return [i["id"] for i in instances]
598 def GetInstance(self, instance):
599 """Gets information about an instance.
602 @param instance: instance whose info to return
605 @return: info about the instance
608 return self._SendRequest(HTTP_GET,
609 ("/%s/instances/%s" %
610 (GANETI_RAPI_VERSION, instance)), None, None)
612 def GetInstanceInfo(self, instance, static=None):
613 """Gets information about an instance.
615 @type instance: string
616 @param instance: Instance name
621 if static is not None:
622 query = [("static", static)]
626 return self._SendRequest(HTTP_GET,
627 ("/%s/instances/%s/info" %
628 (GANETI_RAPI_VERSION, instance)), query, None)
630 def CreateInstance(self, mode, name, disk_template, disks, nics,
632 """Creates a new instance.
634 More details for parameters can be found in the RAPI documentation.
637 @param mode: Instance creation mode
639 @param name: Hostname of the instance to create
640 @type disk_template: string
641 @param disk_template: Disk template for instance (e.g. plain, diskless,
643 @type disks: list of dicts
644 @param disks: List of disk definitions
645 @type nics: list of dicts
646 @param nics: List of NIC definitions
648 @keyword dry_run: whether to perform a dry run
656 if kwargs.get("dry_run"):
657 query.append(("dry-run", 1))
659 if _INST_CREATE_REQV1 in self.GetFeatures():
660 # All required fields for request data version 1
662 _REQ_DATA_VERSION_FIELD: 1,
665 "disk_template": disk_template,
670 conflicts = set(kwargs.iterkeys()) & set(body.iterkeys())
672 raise GanetiApiError("Required fields can not be specified as"
673 " keywords: %s" % ", ".join(conflicts))
675 body.update((key, value) for key, value in kwargs.iteritems()
678 raise GanetiApiError("Server does not support new-style (version 1)"
679 " instance creation requests")
681 return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
684 def DeleteInstance(self, instance, dry_run=False):
685 """Deletes an instance.
688 @param instance: the instance to delete
696 query.append(("dry-run", 1))
698 return self._SendRequest(HTTP_DELETE,
699 ("/%s/instances/%s" %
700 (GANETI_RAPI_VERSION, instance)), query, None)
702 def ModifyInstance(self, instance, **kwargs):
703 """Modifies an instance.
705 More details for parameters can be found in the RAPI documentation.
707 @type instance: string
708 @param instance: Instance name
715 return self._SendRequest(HTTP_PUT,
716 ("/%s/instances/%s/modify" %
717 (GANETI_RAPI_VERSION, instance)), None, body)
719 def ActivateInstanceDisks(self, instance, ignore_size=None):
720 """Activates an instance's disks.
722 @type instance: string
723 @param instance: Instance name
724 @type ignore_size: bool
725 @param ignore_size: Whether to ignore recorded size
732 query.append(("ignore_size", 1))
734 return self._SendRequest(HTTP_PUT,
735 ("/%s/instances/%s/activate-disks" %
736 (GANETI_RAPI_VERSION, instance)), query, None)
738 def DeactivateInstanceDisks(self, instance):
739 """Deactivates an instance's disks.
741 @type instance: string
742 @param instance: Instance name
747 return self._SendRequest(HTTP_PUT,
748 ("/%s/instances/%s/deactivate-disks" %
749 (GANETI_RAPI_VERSION, instance)), None, None)
751 def GrowInstanceDisk(self, instance, disk, amount, wait_for_sync=None):
752 """Grows a disk of an instance.
754 More details for parameters can be found in the RAPI documentation.
756 @type instance: string
757 @param instance: Instance name
759 @param disk: Disk index
760 @type amount: integer
761 @param amount: Grow disk by this amount (MiB)
762 @type wait_for_sync: bool
763 @param wait_for_sync: Wait for disk to synchronize
772 if wait_for_sync is not None:
773 body["wait_for_sync"] = wait_for_sync
775 return self._SendRequest(HTTP_POST,
776 ("/%s/instances/%s/disk/%s/grow" %
777 (GANETI_RAPI_VERSION, instance, disk)),
780 def GetInstanceTags(self, instance):
781 """Gets tags for an instance.
784 @param instance: instance whose tags to return
787 @return: tags for the instance
790 return self._SendRequest(HTTP_GET,
791 ("/%s/instances/%s/tags" %
792 (GANETI_RAPI_VERSION, instance)), None, None)
794 def AddInstanceTags(self, instance, tags, dry_run=False):
795 """Adds tags to an instance.
798 @param instance: instance to add tags to
799 @type tags: list of str
800 @param tags: tags to add to the instance
802 @param dry_run: whether to perform a dry run
808 query = [("tag", t) for t in tags]
810 query.append(("dry-run", 1))
812 return self._SendRequest(HTTP_PUT,
813 ("/%s/instances/%s/tags" %
814 (GANETI_RAPI_VERSION, instance)), query, None)
816 def DeleteInstanceTags(self, instance, tags, dry_run=False):
817 """Deletes tags from an instance.
820 @param instance: instance to delete tags from
821 @type tags: list of str
822 @param tags: tags to delete
824 @param dry_run: whether to perform a dry run
829 query = [("tag", t) for t in tags]
831 query.append(("dry-run", 1))
833 return self._SendRequest(HTTP_DELETE,
834 ("/%s/instances/%s/tags" %
835 (GANETI_RAPI_VERSION, instance)), query, None)
837 def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None,
839 """Reboots an instance.
842 @param instance: instance to rebot
843 @type reboot_type: str
844 @param reboot_type: one of: hard, soft, full
845 @type ignore_secondaries: bool
846 @param ignore_secondaries: if True, ignores errors for the secondary node
847 while re-assembling disks (in hard-reboot mode only)
849 @param dry_run: whether to perform a dry run
856 query.append(("type", reboot_type))
857 if ignore_secondaries is not None:
858 query.append(("ignore_secondaries", ignore_secondaries))
860 query.append(("dry-run", 1))
862 return self._SendRequest(HTTP_POST,
863 ("/%s/instances/%s/reboot" %
864 (GANETI_RAPI_VERSION, instance)), query, None)
866 def ShutdownInstance(self, instance, dry_run=False):
867 """Shuts down an instance.
870 @param instance: the instance to shut down
872 @param dry_run: whether to perform a dry run
879 query.append(("dry-run", 1))
881 return self._SendRequest(HTTP_PUT,
882 ("/%s/instances/%s/shutdown" %
883 (GANETI_RAPI_VERSION, instance)), query, None)
885 def StartupInstance(self, instance, dry_run=False):
886 """Starts up an instance.
889 @param instance: the instance to start up
891 @param dry_run: whether to perform a dry run
898 query.append(("dry-run", 1))
900 return self._SendRequest(HTTP_PUT,
901 ("/%s/instances/%s/startup" %
902 (GANETI_RAPI_VERSION, instance)), query, None)
904 def ReinstallInstance(self, instance, os=None, no_startup=False,
906 """Reinstalls an instance.
909 @param instance: The instance to reinstall
910 @type os: str or None
911 @param os: The operating system to reinstall. If None, the instance's
912 current operating system will be installed again
913 @type no_startup: bool
914 @param no_startup: Whether to start the instance automatically
919 if _INST_REINSTALL_REQV1 in self.GetFeatures():
921 "start": not no_startup,
925 if osparams is not None:
926 body["osparams"] = osparams
927 return self._SendRequest(HTTP_POST,
928 ("/%s/instances/%s/reinstall" %
929 (GANETI_RAPI_VERSION, instance)), None, body)
931 # Use old request format
933 raise GanetiApiError("Server does not support specifying OS parameters"
934 " for instance reinstallation")
938 query.append(("os", os))
940 query.append(("nostartup", 1))
941 return self._SendRequest(HTTP_POST,
942 ("/%s/instances/%s/reinstall" %
943 (GANETI_RAPI_VERSION, instance)), query, None)
945 def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
946 remote_node=None, iallocator=None, dry_run=False):
947 """Replaces disks on an instance.
950 @param instance: instance whose disks to replace
951 @type disks: list of ints
952 @param disks: Indexes of disks to replace
954 @param mode: replacement mode to use (defaults to replace_auto)
955 @type remote_node: str or None
956 @param remote_node: new secondary node to use (for use with
957 replace_new_secondary mode)
958 @type iallocator: str or None
959 @param iallocator: instance allocator plugin to use (for use with
962 @param dry_run: whether to perform a dry run
973 query.append(("disks", ",".join(str(idx) for idx in disks)))
976 query.append(("remote_node", remote_node))
979 query.append(("iallocator", iallocator))
982 query.append(("dry-run", 1))
984 return self._SendRequest(HTTP_POST,
985 ("/%s/instances/%s/replace-disks" %
986 (GANETI_RAPI_VERSION, instance)), query, None)
988 def PrepareExport(self, instance, mode):
989 """Prepares an instance for an export.
991 @type instance: string
992 @param instance: Instance name
994 @param mode: Export mode
999 query = [("mode", mode)]
1000 return self._SendRequest(HTTP_PUT,
1001 ("/%s/instances/%s/prepare-export" %
1002 (GANETI_RAPI_VERSION, instance)), query, None)
1004 def ExportInstance(self, instance, mode, destination, shutdown=None,
1005 remove_instance=None,
1006 x509_key_name=None, destination_x509_ca=None):
1007 """Exports an instance.
1009 @type instance: string
1010 @param instance: Instance name
1012 @param mode: Export mode
1018 "destination": destination,
1022 if shutdown is not None:
1023 body["shutdown"] = shutdown
1025 if remove_instance is not None:
1026 body["remove_instance"] = remove_instance
1028 if x509_key_name is not None:
1029 body["x509_key_name"] = x509_key_name
1031 if destination_x509_ca is not None:
1032 body["destination_x509_ca"] = destination_x509_ca
1034 return self._SendRequest(HTTP_PUT,
1035 ("/%s/instances/%s/export" %
1036 (GANETI_RAPI_VERSION, instance)), None, body)
1038 def MigrateInstance(self, instance, mode=None, cleanup=None):
1039 """Migrates an instance.
1041 @type instance: string
1042 @param instance: Instance name
1044 @param mode: Migration mode
1046 @param cleanup: Whether to clean up a previously failed migration
1053 if mode is not None:
1056 if cleanup is not None:
1057 body["cleanup"] = cleanup
1059 return self._SendRequest(HTTP_PUT,
1060 ("/%s/instances/%s/migrate" %
1061 (GANETI_RAPI_VERSION, instance)), None, body)
1063 def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
1064 """Changes the name of an instance.
1066 @type instance: string
1067 @param instance: Instance name
1068 @type new_name: string
1069 @param new_name: New instance name
1070 @type ip_check: bool
1071 @param ip_check: Whether to ensure instance's IP address is inactive
1072 @type name_check: bool
1073 @param name_check: Whether to ensure instance's name is resolvable
1079 "new_name": new_name,
1082 if ip_check is not None:
1083 body["ip_check"] = ip_check
1085 if name_check is not None:
1086 body["name_check"] = name_check
1088 return self._SendRequest(HTTP_PUT,
1089 ("/%s/instances/%s/rename" %
1090 (GANETI_RAPI_VERSION, instance)), None, body)
1092 def GetInstanceConsole(self, instance):
1093 """Request information for connecting to instance's console.
1095 @type instance: string
1096 @param instance: Instance name
1098 @return: dictionary containing information about instance's console
1101 return self._SendRequest(HTTP_GET,
1102 ("/%s/instances/%s/console" %
1103 (GANETI_RAPI_VERSION, instance)), None, None)
1106 """Gets all jobs for the cluster.
1109 @return: job ids for the cluster
1112 return [int(j["id"])
1113 for j in self._SendRequest(HTTP_GET,
1114 "/%s/jobs" % GANETI_RAPI_VERSION,
1117 def GetJobStatus(self, job_id):
1118 """Gets the status of a job.
1120 @type job_id: string
1121 @param job_id: job id whose status to query
1127 return self._SendRequest(HTTP_GET,
1128 "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1131 def WaitForJobCompletion(self, job_id, period=5, retries=-1):
1132 """Polls cluster for job status until completion.
1134 Completion is defined as any of the following states listed in
1135 L{JOB_STATUS_FINALIZED}.
1137 @type job_id: string
1138 @param job_id: job id to watch
1140 @param period: how often to poll for status (optional, default 5s)
1142 @param retries: how many time to poll before giving up
1143 (optional, default -1 means unlimited)
1146 @return: C{True} if job succeeded or C{False} if failed/status timeout
1147 @deprecated: It is recommended to use L{WaitForJobChange} wherever
1148 possible; L{WaitForJobChange} returns immediately after a job changed and
1149 does not use polling
1153 job_result = self.GetJobStatus(job_id)
1155 if job_result and job_result["status"] == JOB_STATUS_SUCCESS:
1157 elif not job_result or job_result["status"] in JOB_STATUS_FINALIZED:
1168 def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial):
1169 """Waits for job changes.
1171 @type job_id: string
1172 @param job_id: Job ID for which to wait
1173 @return: C{None} if no changes have been detected and a dict with two keys,
1174 C{job_info} and C{log_entries} otherwise.
1180 "previous_job_info": prev_job_info,
1181 "previous_log_serial": prev_log_serial,
1184 return self._SendRequest(HTTP_GET,
1185 "/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
1188 def CancelJob(self, job_id, dry_run=False):
1191 @type job_id: string
1192 @param job_id: id of the job to delete
1194 @param dry_run: whether to perform a dry run
1196 @return: tuple containing the result, and a message (bool, string)
1201 query.append(("dry-run", 1))
1203 return self._SendRequest(HTTP_DELETE,
1204 "/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
1207 def GetNodes(self, bulk=False):
1208 """Gets all nodes in the cluster.
1211 @param bulk: whether to return all information about all instances
1213 @rtype: list of dict or str
1214 @return: if bulk is true, info about nodes in the cluster,
1215 else list of nodes in the cluster
1220 query.append(("bulk", 1))
1222 nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION,
1227 return [n["id"] for n in nodes]
1229 def GetNode(self, node):
1230 """Gets information about a node.
1233 @param node: node whose info to return
1236 @return: info about the node
1239 return self._SendRequest(HTTP_GET,
1240 "/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
1243 def EvacuateNode(self, node, iallocator=None, remote_node=None,
1244 dry_run=False, early_release=False):
1245 """Evacuates instances from a Ganeti node.
1248 @param node: node to evacuate
1249 @type iallocator: str or None
1250 @param iallocator: instance allocator to use
1251 @type remote_node: str
1252 @param remote_node: node to evaucate to
1254 @param dry_run: whether to perform a dry run
1255 @type early_release: bool
1256 @param early_release: whether to enable parallelization
1259 @return: list of (job ID, instance name, new secondary node); if
1260 dry_run was specified, then the actual move jobs were not
1261 submitted and the job IDs will be C{None}
1263 @raises GanetiApiError: if an iallocator and remote_node are both
1267 if iallocator and remote_node:
1268 raise GanetiApiError("Only one of iallocator or remote_node can be used")
1272 query.append(("iallocator", iallocator))
1274 query.append(("remote_node", remote_node))
1276 query.append(("dry-run", 1))
1278 query.append(("early_release", 1))
1280 return self._SendRequest(HTTP_POST,
1281 ("/%s/nodes/%s/evacuate" %
1282 (GANETI_RAPI_VERSION, node)), query, None)
1284 def MigrateNode(self, node, mode=None, dry_run=False):
1285 """Migrates all primary instances from a node.
1288 @param node: node to migrate
1290 @param mode: if passed, it will overwrite the live migration type,
1291 otherwise the hypervisor default will be used
1293 @param dry_run: whether to perform a dry run
1300 if mode is not None:
1301 query.append(("mode", mode))
1303 query.append(("dry-run", 1))
1305 return self._SendRequest(HTTP_POST,
1306 ("/%s/nodes/%s/migrate" %
1307 (GANETI_RAPI_VERSION, node)), query, None)
1309 def GetNodeRole(self, node):
1310 """Gets the current role for a node.
1313 @param node: node whose role to return
1316 @return: the current role for a node
1319 return self._SendRequest(HTTP_GET,
1320 ("/%s/nodes/%s/role" %
1321 (GANETI_RAPI_VERSION, node)), None, None)
1323 def SetNodeRole(self, node, role, force=False):
1324 """Sets the role for a node.
1327 @param node: the node whose role to set
1329 @param role: the role to set for the node
1331 @param force: whether to force the role change
1341 return self._SendRequest(HTTP_PUT,
1342 ("/%s/nodes/%s/role" %
1343 (GANETI_RAPI_VERSION, node)), query, role)
1345 def GetNodeStorageUnits(self, node, storage_type, output_fields):
1346 """Gets the storage units for a node.
1349 @param node: the node whose storage units to return
1350 @type storage_type: str
1351 @param storage_type: storage type whose units to return
1352 @type output_fields: str
1353 @param output_fields: storage type fields to return
1356 @return: job id where results can be retrieved
1360 ("storage_type", storage_type),
1361 ("output_fields", output_fields),
1364 return self._SendRequest(HTTP_GET,
1365 ("/%s/nodes/%s/storage" %
1366 (GANETI_RAPI_VERSION, node)), query, None)
1368 def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None):
1369 """Modifies parameters of storage units on the node.
1372 @param node: node whose storage units to modify
1373 @type storage_type: str
1374 @param storage_type: storage type whose units to modify
1376 @param name: name of the storage unit
1377 @type allocatable: bool or None
1378 @param allocatable: Whether to set the "allocatable" flag on the storage
1379 unit (None=no modification, True=set, False=unset)
1386 ("storage_type", storage_type),
1390 if allocatable is not None:
1391 query.append(("allocatable", allocatable))
1393 return self._SendRequest(HTTP_PUT,
1394 ("/%s/nodes/%s/storage/modify" %
1395 (GANETI_RAPI_VERSION, node)), query, None)
1397 def RepairNodeStorageUnits(self, node, storage_type, name):
1398 """Repairs a storage unit on the node.
1401 @param node: node whose storage units to repair
1402 @type storage_type: str
1403 @param storage_type: storage type to repair
1405 @param name: name of the storage unit to repair
1412 ("storage_type", storage_type),
1416 return self._SendRequest(HTTP_PUT,
1417 ("/%s/nodes/%s/storage/repair" %
1418 (GANETI_RAPI_VERSION, node)), query, None)
1420 def GetNodeTags(self, node):
1421 """Gets the tags for a node.
1424 @param node: node whose tags to return
1427 @return: tags for the node
1430 return self._SendRequest(HTTP_GET,
1431 ("/%s/nodes/%s/tags" %
1432 (GANETI_RAPI_VERSION, node)), None, None)
1434 def AddNodeTags(self, node, tags, dry_run=False):
1435 """Adds tags to a node.
1438 @param node: node to add tags to
1439 @type tags: list of str
1440 @param tags: tags to add to the node
1442 @param dry_run: whether to perform a dry run
1448 query = [("tag", t) for t in tags]
1450 query.append(("dry-run", 1))
1452 return self._SendRequest(HTTP_PUT,
1453 ("/%s/nodes/%s/tags" %
1454 (GANETI_RAPI_VERSION, node)), query, tags)
1456 def DeleteNodeTags(self, node, tags, dry_run=False):
1457 """Delete tags from a node.
1460 @param node: node to remove tags from
1461 @type tags: list of str
1462 @param tags: tags to remove from the node
1464 @param dry_run: whether to perform a dry run
1470 query = [("tag", t) for t in tags]
1472 query.append(("dry-run", 1))
1474 return self._SendRequest(HTTP_DELETE,
1475 ("/%s/nodes/%s/tags" %
1476 (GANETI_RAPI_VERSION, node)), query, None)
1478 def GetGroups(self, bulk=False):
1479 """Gets all node groups in the cluster.
1482 @param bulk: whether to return all information about the groups
1484 @rtype: list of dict or str
1485 @return: if bulk is true, a list of dictionaries with info about all node
1486 groups in the cluster, else a list of names of those node groups
1491 query.append(("bulk", 1))
1493 groups = self._SendRequest(HTTP_GET, "/%s/groups" % GANETI_RAPI_VERSION,
1498 return [g["name"] for g in groups]
1500 def GetGroup(self, group):
1501 """Gets information about a node group.
1504 @param group: name of the node group whose info to return
1507 @return: info about the node group
1510 return self._SendRequest(HTTP_GET,
1511 "/%s/groups/%s" % (GANETI_RAPI_VERSION, group),
1514 def CreateGroup(self, name, alloc_policy=None, dry_run=False):
1515 """Creates a new node group.
1518 @param name: the name of node group to create
1519 @type alloc_policy: str
1520 @param alloc_policy: the desired allocation policy for the group, if any
1522 @param dry_run: whether to peform a dry run
1530 query.append(("dry-run", 1))
1534 "alloc_policy": alloc_policy
1537 return self._SendRequest(HTTP_POST, "/%s/groups" % GANETI_RAPI_VERSION,
1540 def ModifyGroup(self, group, **kwargs):
1541 """Modifies a node group.
1543 More details for parameters can be found in the RAPI documentation.
1546 @param group: Node group name
1551 return self._SendRequest(HTTP_PUT,
1552 ("/%s/groups/%s/modify" %
1553 (GANETI_RAPI_VERSION, group)), None, kwargs)
1555 def DeleteGroup(self, group, dry_run=False):
1556 """Deletes a node group.
1559 @param group: the node group to delete
1561 @param dry_run: whether to peform a dry run
1569 query.append(("dry-run", 1))
1571 return self._SendRequest(HTTP_DELETE,
1573 (GANETI_RAPI_VERSION, group)), query, None)
1575 def RenameGroup(self, group, new_name):
1576 """Changes the name of a node group.
1579 @param group: Node group name
1580 @type new_name: string
1581 @param new_name: New node group name
1588 "new_name": new_name,
1591 return self._SendRequest(HTTP_PUT,
1592 ("/%s/groups/%s/rename" %
1593 (GANETI_RAPI_VERSION, group)), None, body)
1595 def AssignGroupNodes(self, group, nodes, force=False, dry_run=False):
1596 """Assigns nodes to a group.
1599 @param group: Node gropu name
1600 @type nodes: list of strings
1601 @param nodes: List of nodes to assign to the group
1610 query.append(("force", 1))
1613 query.append(("dry-run", 1))
1619 return self._SendRequest(HTTP_PUT,
1620 ("/%s/groups/%s/assign-nodes" %
1621 (GANETI_RAPI_VERSION, group)), query, body)
1623 def Query(self, what, fields, filter_=None):
1624 """Retrieves information about resources.
1627 @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1628 @type fields: list of string
1629 @param fields: Requested fields
1630 @type filter_: None or list
1631 @param filter_: Query filter
1641 if filter_ is not None:
1642 body["filter"] = filter_
1644 return self._SendRequest(HTTP_PUT,
1646 (GANETI_RAPI_VERSION, what)), None, body)
1648 def QueryFields(self, what, fields=None):
1649 """Retrieves available fields for a resource.
1652 @param what: Resource name, one of L{constants.QR_VIA_RAPI}
1653 @type fields: list of string
1654 @param fields: Requested fields
1662 if fields is not None:
1663 query.append(("fields", ",".join(fields)))
1665 return self._SendRequest(HTTP_GET,
1666 ("/%s/query/%s/fields" %
1667 (GANETI_RAPI_VERSION, what)), query, None)