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