root / lib / rapi / client.py @ f961e2ba
History | View | Annotate | Download (32 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2010 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
|
22 |
"""Ganeti RAPI client."""
|
23 |
|
24 |
# No Ganeti-specific modules should be imported. The RAPI client is supposed to
|
25 |
# be standalone.
|
26 |
|
27 |
import httplib |
28 |
import urllib2 |
29 |
import logging |
30 |
import simplejson |
31 |
import socket |
32 |
import urllib |
33 |
import OpenSSL |
34 |
import distutils.version |
35 |
|
36 |
|
37 |
GANETI_RAPI_PORT = 5080
|
38 |
GANETI_RAPI_VERSION = 2
|
39 |
|
40 |
HTTP_DELETE = "DELETE"
|
41 |
HTTP_GET = "GET"
|
42 |
HTTP_PUT = "PUT"
|
43 |
HTTP_POST = "POST"
|
44 |
HTTP_OK = 200
|
45 |
HTTP_NOT_FOUND = 404
|
46 |
HTTP_APP_JSON = "application/json"
|
47 |
|
48 |
REPLACE_DISK_PRI = "replace_on_primary"
|
49 |
REPLACE_DISK_SECONDARY = "replace_on_secondary"
|
50 |
REPLACE_DISK_CHG = "replace_new_secondary"
|
51 |
REPLACE_DISK_AUTO = "replace_auto"
|
52 |
|
53 |
NODE_ROLE_DRAINED = "drained"
|
54 |
NODE_ROLE_MASTER_CANDIATE = "master-candidate"
|
55 |
NODE_ROLE_MASTER = "master"
|
56 |
NODE_ROLE_OFFLINE = "offline"
|
57 |
NODE_ROLE_REGULAR = "regular"
|
58 |
|
59 |
# Internal constants
|
60 |
_REQ_DATA_VERSION_FIELD = "__version__"
|
61 |
_INST_CREATE_REQV1 = "instance-create-reqv1"
|
62 |
|
63 |
|
64 |
class Error(Exception): |
65 |
"""Base error class for this module.
|
66 |
|
67 |
"""
|
68 |
pass
|
69 |
|
70 |
|
71 |
class CertificateError(Error): |
72 |
"""Raised when a problem is found with the SSL certificate.
|
73 |
|
74 |
"""
|
75 |
pass
|
76 |
|
77 |
|
78 |
class GanetiApiError(Error): |
79 |
"""Generic error raised from Ganeti API.
|
80 |
|
81 |
"""
|
82 |
def __init__(self, msg, code=None): |
83 |
Error.__init__(self, msg)
|
84 |
self.code = code
|
85 |
|
86 |
|
87 |
def FormatX509Name(x509_name): |
88 |
"""Formats an X509 name.
|
89 |
|
90 |
@type x509_name: OpenSSL.crypto.X509Name
|
91 |
|
92 |
"""
|
93 |
try:
|
94 |
# Only supported in pyOpenSSL 0.7 and above
|
95 |
get_components_fn = x509_name.get_components |
96 |
except AttributeError: |
97 |
return repr(x509_name) |
98 |
else:
|
99 |
return "".join("/%s=%s" % (name, value) |
100 |
for name, value in get_components_fn()) |
101 |
|
102 |
|
103 |
class CertAuthorityVerify: |
104 |
"""Certificate verificator for SSL context.
|
105 |
|
106 |
Configures SSL context to verify server's certificate.
|
107 |
|
108 |
"""
|
109 |
_CAPATH_MINVERSION = "0.9"
|
110 |
_DEFVFYPATHS_MINVERSION = "0.9"
|
111 |
|
112 |
_PYOPENSSL_VERSION = OpenSSL.__version__ |
113 |
_PARSED_PYOPENSSL_VERSION = distutils.version.LooseVersion(_PYOPENSSL_VERSION) |
114 |
|
115 |
_SUPPORT_CAPATH = (_PARSED_PYOPENSSL_VERSION >= _CAPATH_MINVERSION) |
116 |
_SUPPORT_DEFVFYPATHS = (_PARSED_PYOPENSSL_VERSION >= _DEFVFYPATHS_MINVERSION) |
117 |
|
118 |
def __init__(self, cafile=None, capath=None, use_default_verify_paths=False): |
119 |
"""Initializes this class.
|
120 |
|
121 |
@type cafile: string
|
122 |
@param cafile: In which file we can find the certificates
|
123 |
@type capath: string
|
124 |
@param capath: In which directory we can find the certificates
|
125 |
@type use_default_verify_paths: bool
|
126 |
@param use_default_verify_paths: Whether the platform provided CA
|
127 |
certificates are to be used for
|
128 |
verification purposes
|
129 |
|
130 |
"""
|
131 |
self._cafile = cafile
|
132 |
self._capath = capath
|
133 |
self._use_default_verify_paths = use_default_verify_paths
|
134 |
|
135 |
if self._capath is not None and not self._SUPPORT_CAPATH: |
136 |
raise Error(("PyOpenSSL %s has no support for a CA directory," |
137 |
" version %s or above is required") %
|
138 |
(self._PYOPENSSL_VERSION, self._CAPATH_MINVERSION)) |
139 |
|
140 |
if self._use_default_verify_paths and not self._SUPPORT_DEFVFYPATHS: |
141 |
raise Error(("PyOpenSSL %s has no support for using default verification" |
142 |
" paths, version %s or above is required") %
|
143 |
(self._PYOPENSSL_VERSION, self._DEFVFYPATHS_MINVERSION)) |
144 |
|
145 |
@staticmethod
|
146 |
def _VerifySslCertCb(logger, _, cert, errnum, errdepth, ok): |
147 |
"""Callback for SSL certificate verification.
|
148 |
|
149 |
@param logger: Logging object
|
150 |
|
151 |
"""
|
152 |
if ok:
|
153 |
log_fn = logger.debug |
154 |
else:
|
155 |
log_fn = logger.error |
156 |
|
157 |
log_fn("Verifying SSL certificate at depth %s, subject '%s', issuer '%s'",
|
158 |
errdepth, FormatX509Name(cert.get_subject()), |
159 |
FormatX509Name(cert.get_issuer())) |
160 |
|
161 |
if not ok: |
162 |
try:
|
163 |
# Only supported in pyOpenSSL 0.7 and above
|
164 |
# pylint: disable-msg=E1101
|
165 |
fn = OpenSSL.crypto.X509_verify_cert_error_string |
166 |
except AttributeError: |
167 |
errmsg = ""
|
168 |
else:
|
169 |
errmsg = ":%s" % fn(errnum)
|
170 |
|
171 |
logger.error("verify error:num=%s%s", errnum, errmsg)
|
172 |
|
173 |
return ok
|
174 |
|
175 |
def __call__(self, ctx, logger): |
176 |
"""Configures an SSL context to verify certificates.
|
177 |
|
178 |
@type ctx: OpenSSL.SSL.Context
|
179 |
@param ctx: SSL context
|
180 |
|
181 |
"""
|
182 |
if self._use_default_verify_paths: |
183 |
ctx.set_default_verify_paths() |
184 |
|
185 |
if self._cafile or self._capath: |
186 |
if self._SUPPORT_CAPATH: |
187 |
ctx.load_verify_locations(self._cafile, self._capath) |
188 |
else:
|
189 |
ctx.load_verify_locations(self._cafile)
|
190 |
|
191 |
ctx.set_verify(OpenSSL.SSL.VERIFY_PEER, |
192 |
lambda conn, cert, errnum, errdepth, ok: \
|
193 |
self._VerifySslCertCb(logger, conn, cert,
|
194 |
errnum, errdepth, ok)) |
195 |
|
196 |
|
197 |
class _HTTPSConnectionOpenSSL(httplib.HTTPSConnection): |
198 |
"""HTTPS Connection handler that verifies the SSL certificate.
|
199 |
|
200 |
"""
|
201 |
def __init__(self, *args, **kwargs): |
202 |
"""Initializes this class.
|
203 |
|
204 |
"""
|
205 |
httplib.HTTPSConnection.__init__(self, *args, **kwargs)
|
206 |
self._logger = None |
207 |
self._config_ssl_verification = None |
208 |
|
209 |
def Setup(self, logger, config_ssl_verification): |
210 |
"""Sets the SSL verification config function.
|
211 |
|
212 |
@param logger: Logging object
|
213 |
@type config_ssl_verification: callable
|
214 |
|
215 |
"""
|
216 |
assert self._logger is None |
217 |
assert self._config_ssl_verification is None |
218 |
|
219 |
self._logger = logger
|
220 |
self._config_ssl_verification = config_ssl_verification
|
221 |
|
222 |
def connect(self): |
223 |
"""Connect to the server specified when the object was created.
|
224 |
|
225 |
This ensures that SSL certificates are verified.
|
226 |
|
227 |
"""
|
228 |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
229 |
|
230 |
ctx = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD) |
231 |
ctx.set_options(OpenSSL.SSL.OP_NO_SSLv2) |
232 |
|
233 |
if self._config_ssl_verification: |
234 |
self._config_ssl_verification(ctx, self._logger) |
235 |
|
236 |
ssl = OpenSSL.SSL.Connection(ctx, sock) |
237 |
ssl.connect((self.host, self.port)) |
238 |
|
239 |
self.sock = httplib.FakeSocket(sock, ssl)
|
240 |
|
241 |
|
242 |
class _HTTPSHandler(urllib2.HTTPSHandler): |
243 |
def __init__(self, logger, config_ssl_verification): |
244 |
"""Initializes this class.
|
245 |
|
246 |
@param logger: Logging object
|
247 |
@type config_ssl_verification: callable
|
248 |
@param config_ssl_verification: Function to configure SSL context for
|
249 |
certificate verification
|
250 |
|
251 |
"""
|
252 |
urllib2.HTTPSHandler.__init__(self)
|
253 |
self._logger = logger
|
254 |
self._config_ssl_verification = config_ssl_verification
|
255 |
|
256 |
def _CreateHttpsConnection(self, *args, **kwargs): |
257 |
"""Wrapper around L{_HTTPSConnectionOpenSSL} to add SSL verification.
|
258 |
|
259 |
This wrapper is necessary provide a compatible API to urllib2.
|
260 |
|
261 |
"""
|
262 |
conn = _HTTPSConnectionOpenSSL(*args, **kwargs) |
263 |
conn.Setup(self._logger, self._config_ssl_verification) |
264 |
return conn
|
265 |
|
266 |
def https_open(self, req): |
267 |
"""Creates HTTPS connection.
|
268 |
|
269 |
Called by urllib2.
|
270 |
|
271 |
"""
|
272 |
return self.do_open(self._CreateHttpsConnection, req) |
273 |
|
274 |
|
275 |
class _RapiRequest(urllib2.Request): |
276 |
def __init__(self, method, url, headers, data): |
277 |
"""Initializes this class.
|
278 |
|
279 |
"""
|
280 |
urllib2.Request.__init__(self, url, data=data, headers=headers)
|
281 |
self._method = method
|
282 |
|
283 |
def get_method(self): |
284 |
"""Returns the HTTP request method.
|
285 |
|
286 |
"""
|
287 |
return self._method |
288 |
|
289 |
|
290 |
class GanetiRapiClient(object): |
291 |
"""Ganeti RAPI client.
|
292 |
|
293 |
"""
|
294 |
USER_AGENT = "Ganeti RAPI Client"
|
295 |
_json_encoder = simplejson.JSONEncoder(sort_keys=True)
|
296 |
|
297 |
def __init__(self, host, port=GANETI_RAPI_PORT, |
298 |
username=None, password=None, |
299 |
config_ssl_verification=None, ignore_proxy=False, |
300 |
logger=logging): |
301 |
"""Constructor.
|
302 |
|
303 |
@type host: string
|
304 |
@param host: the ganeti cluster master to interact with
|
305 |
@type port: int
|
306 |
@param port: the port on which the RAPI is running (default is 5080)
|
307 |
@type username: string
|
308 |
@param username: the username to connect with
|
309 |
@type password: string
|
310 |
@param password: the password to connect with
|
311 |
@type config_ssl_verification: callable
|
312 |
@param config_ssl_verification: Function to configure SSL context for
|
313 |
certificate verification
|
314 |
@type ignore_proxy: bool
|
315 |
@param ignore_proxy: Whether to ignore proxy settings
|
316 |
@param logger: Logging object
|
317 |
|
318 |
"""
|
319 |
self._host = host
|
320 |
self._port = port
|
321 |
self._logger = logger
|
322 |
|
323 |
self._base_url = "https://%s:%s" % (host, port) |
324 |
|
325 |
handlers = [_HTTPSHandler(self._logger, config_ssl_verification)]
|
326 |
|
327 |
if username is not None: |
328 |
pwmgr = urllib2.HTTPPasswordMgrWithDefaultRealm() |
329 |
pwmgr.add_password(None, self._base_url, username, password) |
330 |
handlers.append(urllib2.HTTPBasicAuthHandler(pwmgr)) |
331 |
elif password:
|
332 |
raise Error("Specified password without username") |
333 |
|
334 |
if ignore_proxy:
|
335 |
handlers.append(urllib2.ProxyHandler({})) |
336 |
|
337 |
self._http = urllib2.build_opener(*handlers) # pylint: disable-msg=W0142 |
338 |
|
339 |
self._headers = {
|
340 |
"Accept": HTTP_APP_JSON,
|
341 |
"Content-type": HTTP_APP_JSON,
|
342 |
"User-Agent": self.USER_AGENT, |
343 |
} |
344 |
|
345 |
@staticmethod
|
346 |
def _EncodeQuery(query): |
347 |
"""Encode query values for RAPI URL.
|
348 |
|
349 |
@type query: list of two-tuples
|
350 |
@param query: Query arguments
|
351 |
@rtype: list
|
352 |
@return: Query list with encoded values
|
353 |
|
354 |
"""
|
355 |
result = [] |
356 |
|
357 |
for name, value in query: |
358 |
if value is None: |
359 |
result.append((name, ""))
|
360 |
|
361 |
elif isinstance(value, bool): |
362 |
# Boolean values must be encoded as 0 or 1
|
363 |
result.append((name, int(value)))
|
364 |
|
365 |
elif isinstance(value, (list, tuple, dict)): |
366 |
raise ValueError("Invalid query data type %r" % type(value).__name__) |
367 |
|
368 |
else:
|
369 |
result.append((name, value)) |
370 |
|
371 |
return result
|
372 |
|
373 |
def _SendRequest(self, method, path, query, content): |
374 |
"""Sends an HTTP request.
|
375 |
|
376 |
This constructs a full URL, encodes and decodes HTTP bodies, and
|
377 |
handles invalid responses in a pythonic way.
|
378 |
|
379 |
@type method: string
|
380 |
@param method: HTTP method to use
|
381 |
@type path: string
|
382 |
@param path: HTTP URL path
|
383 |
@type query: list of two-tuples
|
384 |
@param query: query arguments to pass to urllib.urlencode
|
385 |
@type content: str or None
|
386 |
@param content: HTTP body content
|
387 |
|
388 |
@rtype: str
|
389 |
@return: JSON-Decoded response
|
390 |
|
391 |
@raises CertificateError: If an invalid SSL certificate is found
|
392 |
@raises GanetiApiError: If an invalid response is returned
|
393 |
|
394 |
"""
|
395 |
assert path.startswith("/") |
396 |
|
397 |
if content:
|
398 |
encoded_content = self._json_encoder.encode(content)
|
399 |
else:
|
400 |
encoded_content = None
|
401 |
|
402 |
# Build URL
|
403 |
urlparts = [self._base_url, path]
|
404 |
if query:
|
405 |
urlparts.append("?")
|
406 |
urlparts.append(urllib.urlencode(self._EncodeQuery(query)))
|
407 |
|
408 |
url = "".join(urlparts)
|
409 |
|
410 |
self._logger.debug("Sending request %s %s to %s:%s" |
411 |
" (headers=%r, content=%r)",
|
412 |
method, url, self._host, self._port, self._headers, |
413 |
encoded_content) |
414 |
|
415 |
req = _RapiRequest(method, url, self._headers, encoded_content)
|
416 |
|
417 |
try:
|
418 |
resp = self._http.open(req)
|
419 |
encoded_response_content = resp.read() |
420 |
except (OpenSSL.SSL.Error, OpenSSL.crypto.Error), err:
|
421 |
raise CertificateError("SSL issue: %s (%r)" % (err, err)) |
422 |
|
423 |
if encoded_response_content:
|
424 |
response_content = simplejson.loads(encoded_response_content) |
425 |
else:
|
426 |
response_content = None
|
427 |
|
428 |
# TODO: Are there other status codes that are valid? (redirect?)
|
429 |
if resp.code != HTTP_OK:
|
430 |
if isinstance(response_content, dict): |
431 |
msg = ("%s %s: %s" %
|
432 |
(response_content["code"],
|
433 |
response_content["message"],
|
434 |
response_content["explain"]))
|
435 |
else:
|
436 |
msg = str(response_content)
|
437 |
|
438 |
raise GanetiApiError(msg, code=resp.code)
|
439 |
|
440 |
return response_content
|
441 |
|
442 |
def GetVersion(self): |
443 |
"""Gets the Remote API version running on the cluster.
|
444 |
|
445 |
@rtype: int
|
446 |
@return: Ganeti Remote API version
|
447 |
|
448 |
"""
|
449 |
return self._SendRequest(HTTP_GET, "/version", None, None) |
450 |
|
451 |
def GetFeatures(self): |
452 |
"""Gets the list of optional features supported by RAPI server.
|
453 |
|
454 |
@rtype: list
|
455 |
@return: List of optional features
|
456 |
|
457 |
"""
|
458 |
try:
|
459 |
return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION, |
460 |
None, None) |
461 |
except GanetiApiError, err:
|
462 |
# Older RAPI servers don't support this resource
|
463 |
if err.code == HTTP_NOT_FOUND:
|
464 |
return []
|
465 |
|
466 |
raise
|
467 |
|
468 |
def GetOperatingSystems(self): |
469 |
"""Gets the Operating Systems running in the Ganeti cluster.
|
470 |
|
471 |
@rtype: list of str
|
472 |
@return: operating systems
|
473 |
|
474 |
"""
|
475 |
return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION, |
476 |
None, None) |
477 |
|
478 |
def GetInfo(self): |
479 |
"""Gets info about the cluster.
|
480 |
|
481 |
@rtype: dict
|
482 |
@return: information about the cluster
|
483 |
|
484 |
"""
|
485 |
return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION, |
486 |
None, None) |
487 |
|
488 |
def GetClusterTags(self): |
489 |
"""Gets the cluster tags.
|
490 |
|
491 |
@rtype: list of str
|
492 |
@return: cluster tags
|
493 |
|
494 |
"""
|
495 |
return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION, |
496 |
None, None) |
497 |
|
498 |
def AddClusterTags(self, tags, dry_run=False): |
499 |
"""Adds tags to the cluster.
|
500 |
|
501 |
@type tags: list of str
|
502 |
@param tags: tags to add to the cluster
|
503 |
@type dry_run: bool
|
504 |
@param dry_run: whether to perform a dry run
|
505 |
|
506 |
@rtype: int
|
507 |
@return: job id
|
508 |
|
509 |
"""
|
510 |
query = [("tag", t) for t in tags] |
511 |
if dry_run:
|
512 |
query.append(("dry-run", 1)) |
513 |
|
514 |
return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION, |
515 |
query, None)
|
516 |
|
517 |
def DeleteClusterTags(self, tags, dry_run=False): |
518 |
"""Deletes tags from the cluster.
|
519 |
|
520 |
@type tags: list of str
|
521 |
@param tags: tags to delete
|
522 |
@type dry_run: bool
|
523 |
@param dry_run: whether to perform a dry run
|
524 |
|
525 |
"""
|
526 |
query = [("tag", t) for t in tags] |
527 |
if dry_run:
|
528 |
query.append(("dry-run", 1)) |
529 |
|
530 |
return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION, |
531 |
query, None)
|
532 |
|
533 |
def GetInstances(self, bulk=False): |
534 |
"""Gets information about instances on the cluster.
|
535 |
|
536 |
@type bulk: bool
|
537 |
@param bulk: whether to return all information about all instances
|
538 |
|
539 |
@rtype: list of dict or list of str
|
540 |
@return: if bulk is True, info about the instances, else a list of instances
|
541 |
|
542 |
"""
|
543 |
query = [] |
544 |
if bulk:
|
545 |
query.append(("bulk", 1)) |
546 |
|
547 |
instances = self._SendRequest(HTTP_GET,
|
548 |
"/%s/instances" % GANETI_RAPI_VERSION,
|
549 |
query, None)
|
550 |
if bulk:
|
551 |
return instances
|
552 |
else:
|
553 |
return [i["id"] for i in instances] |
554 |
|
555 |
def GetInstanceInfo(self, instance): |
556 |
"""Gets information about an instance.
|
557 |
|
558 |
@type instance: str
|
559 |
@param instance: instance whose info to return
|
560 |
|
561 |
@rtype: dict
|
562 |
@return: info about the instance
|
563 |
|
564 |
"""
|
565 |
return self._SendRequest(HTTP_GET, |
566 |
("/%s/instances/%s" %
|
567 |
(GANETI_RAPI_VERSION, instance)), None, None) |
568 |
|
569 |
def CreateInstance(self, mode, name, disk_template, disks, nics, |
570 |
**kwargs): |
571 |
"""Creates a new instance.
|
572 |
|
573 |
More details for parameters can be found in the RAPI documentation.
|
574 |
|
575 |
@type mode: string
|
576 |
@param mode: Instance creation mode
|
577 |
@type name: string
|
578 |
@param name: Hostname of the instance to create
|
579 |
@type disk_template: string
|
580 |
@param disk_template: Disk template for instance (e.g. plain, diskless,
|
581 |
file, or drbd)
|
582 |
@type disks: list of dicts
|
583 |
@param disks: List of disk definitions
|
584 |
@type nics: list of dicts
|
585 |
@param nics: List of NIC definitions
|
586 |
@type dry_run: bool
|
587 |
@keyword dry_run: whether to perform a dry run
|
588 |
|
589 |
@rtype: int
|
590 |
@return: job id
|
591 |
|
592 |
"""
|
593 |
query = [] |
594 |
|
595 |
if kwargs.get("dry_run"): |
596 |
query.append(("dry-run", 1)) |
597 |
|
598 |
if _INST_CREATE_REQV1 in self.GetFeatures(): |
599 |
# All required fields for request data version 1
|
600 |
body = { |
601 |
_REQ_DATA_VERSION_FIELD: 1,
|
602 |
"mode": mode,
|
603 |
"name": name,
|
604 |
"disk_template": disk_template,
|
605 |
"disks": disks,
|
606 |
"nics": nics,
|
607 |
} |
608 |
|
609 |
conflicts = set(kwargs.iterkeys()) & set(body.iterkeys()) |
610 |
if conflicts:
|
611 |
raise GanetiApiError("Required fields can not be specified as" |
612 |
" keywords: %s" % ", ".join(conflicts)) |
613 |
|
614 |
body.update((key, value) for key, value in kwargs.iteritems() |
615 |
if key != "dry_run") |
616 |
else:
|
617 |
# TODO: Implement instance creation request data version 0
|
618 |
# When implementing version 0, care should be taken to refuse unknown
|
619 |
# parameters and invalid values. The interface of this function must stay
|
620 |
# exactly the same for version 0 and 1 (e.g. they aren't allowed to
|
621 |
# require different data types).
|
622 |
raise NotImplementedError("Support for instance creation request data" |
623 |
" version 0 is not yet implemented")
|
624 |
|
625 |
return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION, |
626 |
query, body) |
627 |
|
628 |
def DeleteInstance(self, instance, dry_run=False): |
629 |
"""Deletes an instance.
|
630 |
|
631 |
@type instance: str
|
632 |
@param instance: the instance to delete
|
633 |
|
634 |
@rtype: int
|
635 |
@return: job id
|
636 |
|
637 |
"""
|
638 |
query = [] |
639 |
if dry_run:
|
640 |
query.append(("dry-run", 1)) |
641 |
|
642 |
return self._SendRequest(HTTP_DELETE, |
643 |
("/%s/instances/%s" %
|
644 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
645 |
|
646 |
def GetInstanceTags(self, instance): |
647 |
"""Gets tags for an instance.
|
648 |
|
649 |
@type instance: str
|
650 |
@param instance: instance whose tags to return
|
651 |
|
652 |
@rtype: list of str
|
653 |
@return: tags for the instance
|
654 |
|
655 |
"""
|
656 |
return self._SendRequest(HTTP_GET, |
657 |
("/%s/instances/%s/tags" %
|
658 |
(GANETI_RAPI_VERSION, instance)), None, None) |
659 |
|
660 |
def AddInstanceTags(self, instance, tags, dry_run=False): |
661 |
"""Adds tags to an instance.
|
662 |
|
663 |
@type instance: str
|
664 |
@param instance: instance to add tags to
|
665 |
@type tags: list of str
|
666 |
@param tags: tags to add to the instance
|
667 |
@type dry_run: bool
|
668 |
@param dry_run: whether to perform a dry run
|
669 |
|
670 |
@rtype: int
|
671 |
@return: job id
|
672 |
|
673 |
"""
|
674 |
query = [("tag", t) for t in tags] |
675 |
if dry_run:
|
676 |
query.append(("dry-run", 1)) |
677 |
|
678 |
return self._SendRequest(HTTP_PUT, |
679 |
("/%s/instances/%s/tags" %
|
680 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
681 |
|
682 |
def DeleteInstanceTags(self, instance, tags, dry_run=False): |
683 |
"""Deletes tags from an instance.
|
684 |
|
685 |
@type instance: str
|
686 |
@param instance: instance to delete tags from
|
687 |
@type tags: list of str
|
688 |
@param tags: tags to delete
|
689 |
@type dry_run: bool
|
690 |
@param dry_run: whether to perform a dry run
|
691 |
|
692 |
"""
|
693 |
query = [("tag", t) for t in tags] |
694 |
if dry_run:
|
695 |
query.append(("dry-run", 1)) |
696 |
|
697 |
return self._SendRequest(HTTP_DELETE, |
698 |
("/%s/instances/%s/tags" %
|
699 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
700 |
|
701 |
def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None, |
702 |
dry_run=False):
|
703 |
"""Reboots an instance.
|
704 |
|
705 |
@type instance: str
|
706 |
@param instance: instance to rebot
|
707 |
@type reboot_type: str
|
708 |
@param reboot_type: one of: hard, soft, full
|
709 |
@type ignore_secondaries: bool
|
710 |
@param ignore_secondaries: if True, ignores errors for the secondary node
|
711 |
while re-assembling disks (in hard-reboot mode only)
|
712 |
@type dry_run: bool
|
713 |
@param dry_run: whether to perform a dry run
|
714 |
|
715 |
"""
|
716 |
query = [] |
717 |
if reboot_type:
|
718 |
query.append(("type", reboot_type))
|
719 |
if ignore_secondaries is not None: |
720 |
query.append(("ignore_secondaries", ignore_secondaries))
|
721 |
if dry_run:
|
722 |
query.append(("dry-run", 1)) |
723 |
|
724 |
return self._SendRequest(HTTP_POST, |
725 |
("/%s/instances/%s/reboot" %
|
726 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
727 |
|
728 |
def ShutdownInstance(self, instance, dry_run=False): |
729 |
"""Shuts down an instance.
|
730 |
|
731 |
@type instance: str
|
732 |
@param instance: the instance to shut down
|
733 |
@type dry_run: bool
|
734 |
@param dry_run: whether to perform a dry run
|
735 |
|
736 |
"""
|
737 |
query = [] |
738 |
if dry_run:
|
739 |
query.append(("dry-run", 1)) |
740 |
|
741 |
return self._SendRequest(HTTP_PUT, |
742 |
("/%s/instances/%s/shutdown" %
|
743 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
744 |
|
745 |
def StartupInstance(self, instance, dry_run=False): |
746 |
"""Starts up an instance.
|
747 |
|
748 |
@type instance: str
|
749 |
@param instance: the instance to start up
|
750 |
@type dry_run: bool
|
751 |
@param dry_run: whether to perform a dry run
|
752 |
|
753 |
"""
|
754 |
query = [] |
755 |
if dry_run:
|
756 |
query.append(("dry-run", 1)) |
757 |
|
758 |
return self._SendRequest(HTTP_PUT, |
759 |
("/%s/instances/%s/startup" %
|
760 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
761 |
|
762 |
def ReinstallInstance(self, instance, os, no_startup=False): |
763 |
"""Reinstalls an instance.
|
764 |
|
765 |
@type instance: str
|
766 |
@param instance: the instance to reinstall
|
767 |
@type os: str
|
768 |
@param os: the os to reinstall
|
769 |
@type no_startup: bool
|
770 |
@param no_startup: whether to start the instance automatically
|
771 |
|
772 |
"""
|
773 |
query = [("os", os)]
|
774 |
if no_startup:
|
775 |
query.append(("nostartup", 1)) |
776 |
return self._SendRequest(HTTP_POST, |
777 |
("/%s/instances/%s/reinstall" %
|
778 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
779 |
|
780 |
def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO, |
781 |
remote_node=None, iallocator=None, dry_run=False): |
782 |
"""Replaces disks on an instance.
|
783 |
|
784 |
@type instance: str
|
785 |
@param instance: instance whose disks to replace
|
786 |
@type disks: list of ints
|
787 |
@param disks: Indexes of disks to replace
|
788 |
@type mode: str
|
789 |
@param mode: replacement mode to use (defaults to replace_auto)
|
790 |
@type remote_node: str or None
|
791 |
@param remote_node: new secondary node to use (for use with
|
792 |
replace_new_secondary mode)
|
793 |
@type iallocator: str or None
|
794 |
@param iallocator: instance allocator plugin to use (for use with
|
795 |
replace_auto mode)
|
796 |
@type dry_run: bool
|
797 |
@param dry_run: whether to perform a dry run
|
798 |
|
799 |
@rtype: int
|
800 |
@return: job id
|
801 |
|
802 |
"""
|
803 |
query = [ |
804 |
("mode", mode),
|
805 |
] |
806 |
|
807 |
if disks:
|
808 |
query.append(("disks", ",".join(str(idx) for idx in disks))) |
809 |
|
810 |
if remote_node:
|
811 |
query.append(("remote_node", remote_node))
|
812 |
|
813 |
if iallocator:
|
814 |
query.append(("iallocator", iallocator))
|
815 |
|
816 |
if dry_run:
|
817 |
query.append(("dry-run", 1)) |
818 |
|
819 |
return self._SendRequest(HTTP_POST, |
820 |
("/%s/instances/%s/replace-disks" %
|
821 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
822 |
|
823 |
def GetJobs(self): |
824 |
"""Gets all jobs for the cluster.
|
825 |
|
826 |
@rtype: list of int
|
827 |
@return: job ids for the cluster
|
828 |
|
829 |
"""
|
830 |
return [int(j["id"]) |
831 |
for j in self._SendRequest(HTTP_GET, |
832 |
"/%s/jobs" % GANETI_RAPI_VERSION,
|
833 |
None, None)] |
834 |
|
835 |
def GetJobStatus(self, job_id): |
836 |
"""Gets the status of a job.
|
837 |
|
838 |
@type job_id: int
|
839 |
@param job_id: job id whose status to query
|
840 |
|
841 |
@rtype: dict
|
842 |
@return: job status
|
843 |
|
844 |
"""
|
845 |
return self._SendRequest(HTTP_GET, |
846 |
"/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
|
847 |
None, None) |
848 |
|
849 |
def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial): |
850 |
"""Waits for job changes.
|
851 |
|
852 |
@type job_id: int
|
853 |
@param job_id: Job ID for which to wait
|
854 |
|
855 |
"""
|
856 |
body = { |
857 |
"fields": fields,
|
858 |
"previous_job_info": prev_job_info,
|
859 |
"previous_log_serial": prev_log_serial,
|
860 |
} |
861 |
|
862 |
return self._SendRequest(HTTP_GET, |
863 |
"/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
|
864 |
None, body)
|
865 |
|
866 |
def CancelJob(self, job_id, dry_run=False): |
867 |
"""Cancels a job.
|
868 |
|
869 |
@type job_id: int
|
870 |
@param job_id: id of the job to delete
|
871 |
@type dry_run: bool
|
872 |
@param dry_run: whether to perform a dry run
|
873 |
|
874 |
"""
|
875 |
query = [] |
876 |
if dry_run:
|
877 |
query.append(("dry-run", 1)) |
878 |
|
879 |
return self._SendRequest(HTTP_DELETE, |
880 |
"/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
|
881 |
query, None)
|
882 |
|
883 |
def GetNodes(self, bulk=False): |
884 |
"""Gets all nodes in the cluster.
|
885 |
|
886 |
@type bulk: bool
|
887 |
@param bulk: whether to return all information about all instances
|
888 |
|
889 |
@rtype: list of dict or str
|
890 |
@return: if bulk is true, info about nodes in the cluster,
|
891 |
else list of nodes in the cluster
|
892 |
|
893 |
"""
|
894 |
query = [] |
895 |
if bulk:
|
896 |
query.append(("bulk", 1)) |
897 |
|
898 |
nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION, |
899 |
query, None)
|
900 |
if bulk:
|
901 |
return nodes
|
902 |
else:
|
903 |
return [n["id"] for n in nodes] |
904 |
|
905 |
def GetNodeInfo(self, node): |
906 |
"""Gets information about a node.
|
907 |
|
908 |
@type node: str
|
909 |
@param node: node whose info to return
|
910 |
|
911 |
@rtype: dict
|
912 |
@return: info about the node
|
913 |
|
914 |
"""
|
915 |
return self._SendRequest(HTTP_GET, |
916 |
"/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
|
917 |
None, None) |
918 |
|
919 |
def EvacuateNode(self, node, iallocator=None, remote_node=None, |
920 |
dry_run=False):
|
921 |
"""Evacuates instances from a Ganeti node.
|
922 |
|
923 |
@type node: str
|
924 |
@param node: node to evacuate
|
925 |
@type iallocator: str or None
|
926 |
@param iallocator: instance allocator to use
|
927 |
@type remote_node: str
|
928 |
@param remote_node: node to evaucate to
|
929 |
@type dry_run: bool
|
930 |
@param dry_run: whether to perform a dry run
|
931 |
|
932 |
@rtype: int
|
933 |
@return: job id
|
934 |
|
935 |
@raises GanetiApiError: if an iallocator and remote_node are both specified
|
936 |
|
937 |
"""
|
938 |
if iallocator and remote_node: |
939 |
raise GanetiApiError("Only one of iallocator or remote_node can be used") |
940 |
|
941 |
query = [] |
942 |
if iallocator:
|
943 |
query.append(("iallocator", iallocator))
|
944 |
if remote_node:
|
945 |
query.append(("remote_node", remote_node))
|
946 |
if dry_run:
|
947 |
query.append(("dry-run", 1)) |
948 |
|
949 |
return self._SendRequest(HTTP_POST, |
950 |
("/%s/nodes/%s/evacuate" %
|
951 |
(GANETI_RAPI_VERSION, node)), query, None)
|
952 |
|
953 |
def MigrateNode(self, node, live=True, dry_run=False): |
954 |
"""Migrates all primary instances from a node.
|
955 |
|
956 |
@type node: str
|
957 |
@param node: node to migrate
|
958 |
@type live: bool
|
959 |
@param live: whether to use live migration
|
960 |
@type dry_run: bool
|
961 |
@param dry_run: whether to perform a dry run
|
962 |
|
963 |
@rtype: int
|
964 |
@return: job id
|
965 |
|
966 |
"""
|
967 |
query = [] |
968 |
if live:
|
969 |
query.append(("live", 1)) |
970 |
if dry_run:
|
971 |
query.append(("dry-run", 1)) |
972 |
|
973 |
return self._SendRequest(HTTP_POST, |
974 |
("/%s/nodes/%s/migrate" %
|
975 |
(GANETI_RAPI_VERSION, node)), query, None)
|
976 |
|
977 |
def GetNodeRole(self, node): |
978 |
"""Gets the current role for a node.
|
979 |
|
980 |
@type node: str
|
981 |
@param node: node whose role to return
|
982 |
|
983 |
@rtype: str
|
984 |
@return: the current role for a node
|
985 |
|
986 |
"""
|
987 |
return self._SendRequest(HTTP_GET, |
988 |
("/%s/nodes/%s/role" %
|
989 |
(GANETI_RAPI_VERSION, node)), None, None) |
990 |
|
991 |
def SetNodeRole(self, node, role, force=False): |
992 |
"""Sets the role for a node.
|
993 |
|
994 |
@type node: str
|
995 |
@param node: the node whose role to set
|
996 |
@type role: str
|
997 |
@param role: the role to set for the node
|
998 |
@type force: bool
|
999 |
@param force: whether to force the role change
|
1000 |
|
1001 |
@rtype: int
|
1002 |
@return: job id
|
1003 |
|
1004 |
"""
|
1005 |
query = [ |
1006 |
("force", force),
|
1007 |
] |
1008 |
|
1009 |
return self._SendRequest(HTTP_PUT, |
1010 |
("/%s/nodes/%s/role" %
|
1011 |
(GANETI_RAPI_VERSION, node)), query, role) |
1012 |
|
1013 |
def GetNodeStorageUnits(self, node, storage_type, output_fields): |
1014 |
"""Gets the storage units for a node.
|
1015 |
|
1016 |
@type node: str
|
1017 |
@param node: the node whose storage units to return
|
1018 |
@type storage_type: str
|
1019 |
@param storage_type: storage type whose units to return
|
1020 |
@type output_fields: str
|
1021 |
@param output_fields: storage type fields to return
|
1022 |
|
1023 |
@rtype: int
|
1024 |
@return: job id where results can be retrieved
|
1025 |
|
1026 |
"""
|
1027 |
query = [ |
1028 |
("storage_type", storage_type),
|
1029 |
("output_fields", output_fields),
|
1030 |
] |
1031 |
|
1032 |
return self._SendRequest(HTTP_GET, |
1033 |
("/%s/nodes/%s/storage" %
|
1034 |
(GANETI_RAPI_VERSION, node)), query, None)
|
1035 |
|
1036 |
def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None): |
1037 |
"""Modifies parameters of storage units on the node.
|
1038 |
|
1039 |
@type node: str
|
1040 |
@param node: node whose storage units to modify
|
1041 |
@type storage_type: str
|
1042 |
@param storage_type: storage type whose units to modify
|
1043 |
@type name: str
|
1044 |
@param name: name of the storage unit
|
1045 |
@type allocatable: bool or None
|
1046 |
@param allocatable: Whether to set the "allocatable" flag on the storage
|
1047 |
unit (None=no modification, True=set, False=unset)
|
1048 |
|
1049 |
@rtype: int
|
1050 |
@return: job id
|
1051 |
|
1052 |
"""
|
1053 |
query = [ |
1054 |
("storage_type", storage_type),
|
1055 |
("name", name),
|
1056 |
] |
1057 |
|
1058 |
if allocatable is not None: |
1059 |
query.append(("allocatable", allocatable))
|
1060 |
|
1061 |
return self._SendRequest(HTTP_PUT, |
1062 |
("/%s/nodes/%s/storage/modify" %
|
1063 |
(GANETI_RAPI_VERSION, node)), query, None)
|
1064 |
|
1065 |
def RepairNodeStorageUnits(self, node, storage_type, name): |
1066 |
"""Repairs a storage unit on the node.
|
1067 |
|
1068 |
@type node: str
|
1069 |
@param node: node whose storage units to repair
|
1070 |
@type storage_type: str
|
1071 |
@param storage_type: storage type to repair
|
1072 |
@type name: str
|
1073 |
@param name: name of the storage unit to repair
|
1074 |
|
1075 |
@rtype: int
|
1076 |
@return: job id
|
1077 |
|
1078 |
"""
|
1079 |
query = [ |
1080 |
("storage_type", storage_type),
|
1081 |
("name", name),
|
1082 |
] |
1083 |
|
1084 |
return self._SendRequest(HTTP_PUT, |
1085 |
("/%s/nodes/%s/storage/repair" %
|
1086 |
(GANETI_RAPI_VERSION, node)), query, None)
|
1087 |
|
1088 |
def GetNodeTags(self, node): |
1089 |
"""Gets the tags for a node.
|
1090 |
|
1091 |
@type node: str
|
1092 |
@param node: node whose tags to return
|
1093 |
|
1094 |
@rtype: list of str
|
1095 |
@return: tags for the node
|
1096 |
|
1097 |
"""
|
1098 |
return self._SendRequest(HTTP_GET, |
1099 |
("/%s/nodes/%s/tags" %
|
1100 |
(GANETI_RAPI_VERSION, node)), None, None) |
1101 |
|
1102 |
def AddNodeTags(self, node, tags, dry_run=False): |
1103 |
"""Adds tags to a node.
|
1104 |
|
1105 |
@type node: str
|
1106 |
@param node: node to add tags to
|
1107 |
@type tags: list of str
|
1108 |
@param tags: tags to add to the node
|
1109 |
@type dry_run: bool
|
1110 |
@param dry_run: whether to perform a dry run
|
1111 |
|
1112 |
@rtype: int
|
1113 |
@return: job id
|
1114 |
|
1115 |
"""
|
1116 |
query = [("tag", t) for t in tags] |
1117 |
if dry_run:
|
1118 |
query.append(("dry-run", 1)) |
1119 |
|
1120 |
return self._SendRequest(HTTP_PUT, |
1121 |
("/%s/nodes/%s/tags" %
|
1122 |
(GANETI_RAPI_VERSION, node)), query, tags) |
1123 |
|
1124 |
def DeleteNodeTags(self, node, tags, dry_run=False): |
1125 |
"""Delete tags from a node.
|
1126 |
|
1127 |
@type node: str
|
1128 |
@param node: node to remove tags from
|
1129 |
@type tags: list of str
|
1130 |
@param tags: tags to remove from the node
|
1131 |
@type dry_run: bool
|
1132 |
@param dry_run: whether to perform a dry run
|
1133 |
|
1134 |
@rtype: int
|
1135 |
@return: job id
|
1136 |
|
1137 |
"""
|
1138 |
query = [("tag", t) for t in tags] |
1139 |
if dry_run:
|
1140 |
query.append(("dry-run", 1)) |
1141 |
|
1142 |
return self._SendRequest(HTTP_DELETE, |
1143 |
("/%s/nodes/%s/tags" %
|
1144 |
(GANETI_RAPI_VERSION, node)), query, None)
|