root / lib / rapi / client.py @ ebeb600f
History | View | Annotate | Download (33.9 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 |
except urllib2.HTTPError, err:
|
423 |
raise GanetiApiError(str(err), code=err.code) |
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 GetFeatures(self): |
454 |
"""Gets the list of optional features supported by RAPI server.
|
455 |
|
456 |
@rtype: list
|
457 |
@return: List of optional features
|
458 |
|
459 |
"""
|
460 |
try:
|
461 |
return self._SendRequest(HTTP_GET, "/%s/features" % GANETI_RAPI_VERSION, |
462 |
None, None) |
463 |
except GanetiApiError, err:
|
464 |
# Older RAPI servers don't support this resource
|
465 |
if err.code == HTTP_NOT_FOUND:
|
466 |
return []
|
467 |
|
468 |
raise
|
469 |
|
470 |
def GetOperatingSystems(self): |
471 |
"""Gets the Operating Systems running in the Ganeti cluster.
|
472 |
|
473 |
@rtype: list of str
|
474 |
@return: operating systems
|
475 |
|
476 |
"""
|
477 |
return self._SendRequest(HTTP_GET, "/%s/os" % GANETI_RAPI_VERSION, |
478 |
None, None) |
479 |
|
480 |
def GetInfo(self): |
481 |
"""Gets info about the cluster.
|
482 |
|
483 |
@rtype: dict
|
484 |
@return: information about the cluster
|
485 |
|
486 |
"""
|
487 |
return self._SendRequest(HTTP_GET, "/%s/info" % GANETI_RAPI_VERSION, |
488 |
None, None) |
489 |
|
490 |
def GetClusterTags(self): |
491 |
"""Gets the cluster tags.
|
492 |
|
493 |
@rtype: list of str
|
494 |
@return: cluster tags
|
495 |
|
496 |
"""
|
497 |
return self._SendRequest(HTTP_GET, "/%s/tags" % GANETI_RAPI_VERSION, |
498 |
None, None) |
499 |
|
500 |
def AddClusterTags(self, tags, dry_run=False): |
501 |
"""Adds tags to the cluster.
|
502 |
|
503 |
@type tags: list of str
|
504 |
@param tags: tags to add to the cluster
|
505 |
@type dry_run: bool
|
506 |
@param dry_run: whether to perform a dry run
|
507 |
|
508 |
@rtype: int
|
509 |
@return: job id
|
510 |
|
511 |
"""
|
512 |
query = [("tag", t) for t in tags] |
513 |
if dry_run:
|
514 |
query.append(("dry-run", 1)) |
515 |
|
516 |
return self._SendRequest(HTTP_PUT, "/%s/tags" % GANETI_RAPI_VERSION, |
517 |
query, None)
|
518 |
|
519 |
def DeleteClusterTags(self, tags, dry_run=False): |
520 |
"""Deletes tags from the cluster.
|
521 |
|
522 |
@type tags: list of str
|
523 |
@param tags: tags to delete
|
524 |
@type dry_run: bool
|
525 |
@param dry_run: whether to perform a dry run
|
526 |
|
527 |
"""
|
528 |
query = [("tag", t) for t in tags] |
529 |
if dry_run:
|
530 |
query.append(("dry-run", 1)) |
531 |
|
532 |
return self._SendRequest(HTTP_DELETE, "/%s/tags" % GANETI_RAPI_VERSION, |
533 |
query, None)
|
534 |
|
535 |
def GetInstances(self, bulk=False): |
536 |
"""Gets information about instances on the cluster.
|
537 |
|
538 |
@type bulk: bool
|
539 |
@param bulk: whether to return all information about all instances
|
540 |
|
541 |
@rtype: list of dict or list of str
|
542 |
@return: if bulk is True, info about the instances, else a list of instances
|
543 |
|
544 |
"""
|
545 |
query = [] |
546 |
if bulk:
|
547 |
query.append(("bulk", 1)) |
548 |
|
549 |
instances = self._SendRequest(HTTP_GET,
|
550 |
"/%s/instances" % GANETI_RAPI_VERSION,
|
551 |
query, None)
|
552 |
if bulk:
|
553 |
return instances
|
554 |
else:
|
555 |
return [i["id"] for i in instances] |
556 |
|
557 |
def GetInstance(self, instance): |
558 |
"""Gets information about an instance.
|
559 |
|
560 |
@type instance: str
|
561 |
@param instance: instance whose info to return
|
562 |
|
563 |
@rtype: dict
|
564 |
@return: info about the instance
|
565 |
|
566 |
"""
|
567 |
return self._SendRequest(HTTP_GET, |
568 |
("/%s/instances/%s" %
|
569 |
(GANETI_RAPI_VERSION, instance)), None, None) |
570 |
|
571 |
def GetInstanceInfo(self, instance, static=None): |
572 |
"""Gets information about an instance.
|
573 |
|
574 |
@type instance: string
|
575 |
@param instance: Instance name
|
576 |
@rtype: string
|
577 |
@return: Job ID
|
578 |
|
579 |
"""
|
580 |
if static is not None: |
581 |
query = [("static", static)]
|
582 |
else:
|
583 |
query = None
|
584 |
|
585 |
return self._SendRequest(HTTP_GET, |
586 |
("/%s/instances/%s/info" %
|
587 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
588 |
|
589 |
def CreateInstance(self, mode, name, disk_template, disks, nics, |
590 |
**kwargs): |
591 |
"""Creates a new instance.
|
592 |
|
593 |
More details for parameters can be found in the RAPI documentation.
|
594 |
|
595 |
@type mode: string
|
596 |
@param mode: Instance creation mode
|
597 |
@type name: string
|
598 |
@param name: Hostname of the instance to create
|
599 |
@type disk_template: string
|
600 |
@param disk_template: Disk template for instance (e.g. plain, diskless,
|
601 |
file, or drbd)
|
602 |
@type disks: list of dicts
|
603 |
@param disks: List of disk definitions
|
604 |
@type nics: list of dicts
|
605 |
@param nics: List of NIC definitions
|
606 |
@type dry_run: bool
|
607 |
@keyword dry_run: whether to perform a dry run
|
608 |
|
609 |
@rtype: int
|
610 |
@return: job id
|
611 |
|
612 |
"""
|
613 |
query = [] |
614 |
|
615 |
if kwargs.get("dry_run"): |
616 |
query.append(("dry-run", 1)) |
617 |
|
618 |
if _INST_CREATE_REQV1 in self.GetFeatures(): |
619 |
# All required fields for request data version 1
|
620 |
body = { |
621 |
_REQ_DATA_VERSION_FIELD: 1,
|
622 |
"mode": mode,
|
623 |
"name": name,
|
624 |
"disk_template": disk_template,
|
625 |
"disks": disks,
|
626 |
"nics": nics,
|
627 |
} |
628 |
|
629 |
conflicts = set(kwargs.iterkeys()) & set(body.iterkeys()) |
630 |
if conflicts:
|
631 |
raise GanetiApiError("Required fields can not be specified as" |
632 |
" keywords: %s" % ", ".join(conflicts)) |
633 |
|
634 |
body.update((key, value) for key, value in kwargs.iteritems() |
635 |
if key != "dry_run") |
636 |
else:
|
637 |
# TODO: Implement instance creation request data version 0
|
638 |
# When implementing version 0, care should be taken to refuse unknown
|
639 |
# parameters and invalid values. The interface of this function must stay
|
640 |
# exactly the same for version 0 and 1 (e.g. they aren't allowed to
|
641 |
# require different data types).
|
642 |
raise NotImplementedError("Support for instance creation request data" |
643 |
" version 0 is not yet implemented")
|
644 |
|
645 |
return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION, |
646 |
query, body) |
647 |
|
648 |
def DeleteInstance(self, instance, dry_run=False): |
649 |
"""Deletes an instance.
|
650 |
|
651 |
@type instance: str
|
652 |
@param instance: the instance to delete
|
653 |
|
654 |
@rtype: int
|
655 |
@return: job id
|
656 |
|
657 |
"""
|
658 |
query = [] |
659 |
if dry_run:
|
660 |
query.append(("dry-run", 1)) |
661 |
|
662 |
return self._SendRequest(HTTP_DELETE, |
663 |
("/%s/instances/%s" %
|
664 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
665 |
|
666 |
def GetInstanceTags(self, instance): |
667 |
"""Gets tags for an instance.
|
668 |
|
669 |
@type instance: str
|
670 |
@param instance: instance whose tags to return
|
671 |
|
672 |
@rtype: list of str
|
673 |
@return: tags for the instance
|
674 |
|
675 |
"""
|
676 |
return self._SendRequest(HTTP_GET, |
677 |
("/%s/instances/%s/tags" %
|
678 |
(GANETI_RAPI_VERSION, instance)), None, None) |
679 |
|
680 |
def AddInstanceTags(self, instance, tags, dry_run=False): |
681 |
"""Adds tags to an instance.
|
682 |
|
683 |
@type instance: str
|
684 |
@param instance: instance to add tags to
|
685 |
@type tags: list of str
|
686 |
@param tags: tags to add to the instance
|
687 |
@type dry_run: bool
|
688 |
@param dry_run: whether to perform a dry run
|
689 |
|
690 |
@rtype: int
|
691 |
@return: job id
|
692 |
|
693 |
"""
|
694 |
query = [("tag", t) for t in tags] |
695 |
if dry_run:
|
696 |
query.append(("dry-run", 1)) |
697 |
|
698 |
return self._SendRequest(HTTP_PUT, |
699 |
("/%s/instances/%s/tags" %
|
700 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
701 |
|
702 |
def DeleteInstanceTags(self, instance, tags, dry_run=False): |
703 |
"""Deletes tags from an instance.
|
704 |
|
705 |
@type instance: str
|
706 |
@param instance: instance to delete tags from
|
707 |
@type tags: list of str
|
708 |
@param tags: tags to delete
|
709 |
@type dry_run: bool
|
710 |
@param dry_run: whether to perform a dry run
|
711 |
|
712 |
"""
|
713 |
query = [("tag", t) for t in tags] |
714 |
if dry_run:
|
715 |
query.append(("dry-run", 1)) |
716 |
|
717 |
return self._SendRequest(HTTP_DELETE, |
718 |
("/%s/instances/%s/tags" %
|
719 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
720 |
|
721 |
def RebootInstance(self, instance, reboot_type=None, ignore_secondaries=None, |
722 |
dry_run=False):
|
723 |
"""Reboots an instance.
|
724 |
|
725 |
@type instance: str
|
726 |
@param instance: instance to rebot
|
727 |
@type reboot_type: str
|
728 |
@param reboot_type: one of: hard, soft, full
|
729 |
@type ignore_secondaries: bool
|
730 |
@param ignore_secondaries: if True, ignores errors for the secondary node
|
731 |
while re-assembling disks (in hard-reboot mode only)
|
732 |
@type dry_run: bool
|
733 |
@param dry_run: whether to perform a dry run
|
734 |
|
735 |
"""
|
736 |
query = [] |
737 |
if reboot_type:
|
738 |
query.append(("type", reboot_type))
|
739 |
if ignore_secondaries is not None: |
740 |
query.append(("ignore_secondaries", ignore_secondaries))
|
741 |
if dry_run:
|
742 |
query.append(("dry-run", 1)) |
743 |
|
744 |
return self._SendRequest(HTTP_POST, |
745 |
("/%s/instances/%s/reboot" %
|
746 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
747 |
|
748 |
def ShutdownInstance(self, instance, dry_run=False): |
749 |
"""Shuts down an instance.
|
750 |
|
751 |
@type instance: str
|
752 |
@param instance: the instance to shut down
|
753 |
@type dry_run: bool
|
754 |
@param dry_run: whether to perform a dry run
|
755 |
|
756 |
"""
|
757 |
query = [] |
758 |
if dry_run:
|
759 |
query.append(("dry-run", 1)) |
760 |
|
761 |
return self._SendRequest(HTTP_PUT, |
762 |
("/%s/instances/%s/shutdown" %
|
763 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
764 |
|
765 |
def StartupInstance(self, instance, dry_run=False): |
766 |
"""Starts up an instance.
|
767 |
|
768 |
@type instance: str
|
769 |
@param instance: the instance to start up
|
770 |
@type dry_run: bool
|
771 |
@param dry_run: whether to perform a dry run
|
772 |
|
773 |
"""
|
774 |
query = [] |
775 |
if dry_run:
|
776 |
query.append(("dry-run", 1)) |
777 |
|
778 |
return self._SendRequest(HTTP_PUT, |
779 |
("/%s/instances/%s/startup" %
|
780 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
781 |
|
782 |
def ReinstallInstance(self, instance, os, no_startup=False): |
783 |
"""Reinstalls an instance.
|
784 |
|
785 |
@type instance: str
|
786 |
@param instance: the instance to reinstall
|
787 |
@type os: str
|
788 |
@param os: the os to reinstall
|
789 |
@type no_startup: bool
|
790 |
@param no_startup: whether to start the instance automatically
|
791 |
|
792 |
"""
|
793 |
query = [("os", os)]
|
794 |
if no_startup:
|
795 |
query.append(("nostartup", 1)) |
796 |
return self._SendRequest(HTTP_POST, |
797 |
("/%s/instances/%s/reinstall" %
|
798 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
799 |
|
800 |
def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO, |
801 |
remote_node=None, iallocator=None, dry_run=False): |
802 |
"""Replaces disks on an instance.
|
803 |
|
804 |
@type instance: str
|
805 |
@param instance: instance whose disks to replace
|
806 |
@type disks: list of ints
|
807 |
@param disks: Indexes of disks to replace
|
808 |
@type mode: str
|
809 |
@param mode: replacement mode to use (defaults to replace_auto)
|
810 |
@type remote_node: str or None
|
811 |
@param remote_node: new secondary node to use (for use with
|
812 |
replace_new_secondary mode)
|
813 |
@type iallocator: str or None
|
814 |
@param iallocator: instance allocator plugin to use (for use with
|
815 |
replace_auto mode)
|
816 |
@type dry_run: bool
|
817 |
@param dry_run: whether to perform a dry run
|
818 |
|
819 |
@rtype: int
|
820 |
@return: job id
|
821 |
|
822 |
"""
|
823 |
query = [ |
824 |
("mode", mode),
|
825 |
] |
826 |
|
827 |
if disks:
|
828 |
query.append(("disks", ",".join(str(idx) for idx in disks))) |
829 |
|
830 |
if remote_node:
|
831 |
query.append(("remote_node", remote_node))
|
832 |
|
833 |
if iallocator:
|
834 |
query.append(("iallocator", iallocator))
|
835 |
|
836 |
if dry_run:
|
837 |
query.append(("dry-run", 1)) |
838 |
|
839 |
return self._SendRequest(HTTP_POST, |
840 |
("/%s/instances/%s/replace-disks" %
|
841 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
842 |
|
843 |
def PrepareExport(self, instance, mode): |
844 |
"""Prepares an instance for an export.
|
845 |
|
846 |
@type instance: string
|
847 |
@param instance: Instance name
|
848 |
@type mode: string
|
849 |
@param mode: Export mode
|
850 |
@rtype: string
|
851 |
@return: Job ID
|
852 |
|
853 |
"""
|
854 |
query = [("mode", mode)]
|
855 |
return self._SendRequest(HTTP_PUT, |
856 |
("/%s/instances/%s/prepare-export" %
|
857 |
(GANETI_RAPI_VERSION, instance)), query, None)
|
858 |
|
859 |
def ExportInstance(self, instance, mode, destination, shutdown=None, |
860 |
remove_instance=None,
|
861 |
x509_key_name=None, destination_x509_ca=None): |
862 |
"""Exports an instance.
|
863 |
|
864 |
@type instance: string
|
865 |
@param instance: Instance name
|
866 |
@type mode: string
|
867 |
@param mode: Export mode
|
868 |
@rtype: string
|
869 |
@return: Job ID
|
870 |
|
871 |
"""
|
872 |
body = { |
873 |
"destination": destination,
|
874 |
"mode": mode,
|
875 |
} |
876 |
|
877 |
if shutdown is not None: |
878 |
body["shutdown"] = shutdown
|
879 |
|
880 |
if remove_instance is not None: |
881 |
body["remove_instance"] = remove_instance
|
882 |
|
883 |
if x509_key_name is not None: |
884 |
body["x509_key_name"] = x509_key_name
|
885 |
|
886 |
if destination_x509_ca is not None: |
887 |
body["destination_x509_ca"] = destination_x509_ca
|
888 |
|
889 |
return self._SendRequest(HTTP_PUT, |
890 |
("/%s/instances/%s/export" %
|
891 |
(GANETI_RAPI_VERSION, instance)), None, body)
|
892 |
|
893 |
def GetJobs(self): |
894 |
"""Gets all jobs for the cluster.
|
895 |
|
896 |
@rtype: list of int
|
897 |
@return: job ids for the cluster
|
898 |
|
899 |
"""
|
900 |
return [int(j["id"]) |
901 |
for j in self._SendRequest(HTTP_GET, |
902 |
"/%s/jobs" % GANETI_RAPI_VERSION,
|
903 |
None, None)] |
904 |
|
905 |
def GetJobStatus(self, job_id): |
906 |
"""Gets the status of a job.
|
907 |
|
908 |
@type job_id: int
|
909 |
@param job_id: job id whose status to query
|
910 |
|
911 |
@rtype: dict
|
912 |
@return: job status
|
913 |
|
914 |
"""
|
915 |
return self._SendRequest(HTTP_GET, |
916 |
"/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
|
917 |
None, None) |
918 |
|
919 |
def WaitForJobChange(self, job_id, fields, prev_job_info, prev_log_serial): |
920 |
"""Waits for job changes.
|
921 |
|
922 |
@type job_id: int
|
923 |
@param job_id: Job ID for which to wait
|
924 |
|
925 |
"""
|
926 |
body = { |
927 |
"fields": fields,
|
928 |
"previous_job_info": prev_job_info,
|
929 |
"previous_log_serial": prev_log_serial,
|
930 |
} |
931 |
|
932 |
return self._SendRequest(HTTP_GET, |
933 |
"/%s/jobs/%s/wait" % (GANETI_RAPI_VERSION, job_id),
|
934 |
None, body)
|
935 |
|
936 |
def CancelJob(self, job_id, dry_run=False): |
937 |
"""Cancels a job.
|
938 |
|
939 |
@type job_id: int
|
940 |
@param job_id: id of the job to delete
|
941 |
@type dry_run: bool
|
942 |
@param dry_run: whether to perform a dry run
|
943 |
|
944 |
"""
|
945 |
query = [] |
946 |
if dry_run:
|
947 |
query.append(("dry-run", 1)) |
948 |
|
949 |
return self._SendRequest(HTTP_DELETE, |
950 |
"/%s/jobs/%s" % (GANETI_RAPI_VERSION, job_id),
|
951 |
query, None)
|
952 |
|
953 |
def GetNodes(self, bulk=False): |
954 |
"""Gets all nodes in the cluster.
|
955 |
|
956 |
@type bulk: bool
|
957 |
@param bulk: whether to return all information about all instances
|
958 |
|
959 |
@rtype: list of dict or str
|
960 |
@return: if bulk is true, info about nodes in the cluster,
|
961 |
else list of nodes in the cluster
|
962 |
|
963 |
"""
|
964 |
query = [] |
965 |
if bulk:
|
966 |
query.append(("bulk", 1)) |
967 |
|
968 |
nodes = self._SendRequest(HTTP_GET, "/%s/nodes" % GANETI_RAPI_VERSION, |
969 |
query, None)
|
970 |
if bulk:
|
971 |
return nodes
|
972 |
else:
|
973 |
return [n["id"] for n in nodes] |
974 |
|
975 |
def GetNode(self, node): |
976 |
"""Gets information about a node.
|
977 |
|
978 |
@type node: str
|
979 |
@param node: node whose info to return
|
980 |
|
981 |
@rtype: dict
|
982 |
@return: info about the node
|
983 |
|
984 |
"""
|
985 |
return self._SendRequest(HTTP_GET, |
986 |
"/%s/nodes/%s" % (GANETI_RAPI_VERSION, node),
|
987 |
None, None) |
988 |
|
989 |
def EvacuateNode(self, node, iallocator=None, remote_node=None, |
990 |
dry_run=False):
|
991 |
"""Evacuates instances from a Ganeti node.
|
992 |
|
993 |
@type node: str
|
994 |
@param node: node to evacuate
|
995 |
@type iallocator: str or None
|
996 |
@param iallocator: instance allocator to use
|
997 |
@type remote_node: str
|
998 |
@param remote_node: node to evaucate to
|
999 |
@type dry_run: bool
|
1000 |
@param dry_run: whether to perform a dry run
|
1001 |
|
1002 |
@rtype: int
|
1003 |
@return: job id
|
1004 |
|
1005 |
@raises GanetiApiError: if an iallocator and remote_node are both specified
|
1006 |
|
1007 |
"""
|
1008 |
if iallocator and remote_node: |
1009 |
raise GanetiApiError("Only one of iallocator or remote_node can be used") |
1010 |
|
1011 |
query = [] |
1012 |
if iallocator:
|
1013 |
query.append(("iallocator", iallocator))
|
1014 |
if remote_node:
|
1015 |
query.append(("remote_node", remote_node))
|
1016 |
if dry_run:
|
1017 |
query.append(("dry-run", 1)) |
1018 |
|
1019 |
return self._SendRequest(HTTP_POST, |
1020 |
("/%s/nodes/%s/evacuate" %
|
1021 |
(GANETI_RAPI_VERSION, node)), query, None)
|
1022 |
|
1023 |
def MigrateNode(self, node, live=True, dry_run=False): |
1024 |
"""Migrates all primary instances from a node.
|
1025 |
|
1026 |
@type node: str
|
1027 |
@param node: node to migrate
|
1028 |
@type live: bool
|
1029 |
@param live: whether to use live migration
|
1030 |
@type dry_run: bool
|
1031 |
@param dry_run: whether to perform a dry run
|
1032 |
|
1033 |
@rtype: int
|
1034 |
@return: job id
|
1035 |
|
1036 |
"""
|
1037 |
query = [] |
1038 |
if live:
|
1039 |
query.append(("live", 1)) |
1040 |
if dry_run:
|
1041 |
query.append(("dry-run", 1)) |
1042 |
|
1043 |
return self._SendRequest(HTTP_POST, |
1044 |
("/%s/nodes/%s/migrate" %
|
1045 |
(GANETI_RAPI_VERSION, node)), query, None)
|
1046 |
|
1047 |
def GetNodeRole(self, node): |
1048 |
"""Gets the current role for a node.
|
1049 |
|
1050 |
@type node: str
|
1051 |
@param node: node whose role to return
|
1052 |
|
1053 |
@rtype: str
|
1054 |
@return: the current role for a node
|
1055 |
|
1056 |
"""
|
1057 |
return self._SendRequest(HTTP_GET, |
1058 |
("/%s/nodes/%s/role" %
|
1059 |
(GANETI_RAPI_VERSION, node)), None, None) |
1060 |
|
1061 |
def SetNodeRole(self, node, role, force=False): |
1062 |
"""Sets the role for a node.
|
1063 |
|
1064 |
@type node: str
|
1065 |
@param node: the node whose role to set
|
1066 |
@type role: str
|
1067 |
@param role: the role to set for the node
|
1068 |
@type force: bool
|
1069 |
@param force: whether to force the role change
|
1070 |
|
1071 |
@rtype: int
|
1072 |
@return: job id
|
1073 |
|
1074 |
"""
|
1075 |
query = [ |
1076 |
("force", force),
|
1077 |
] |
1078 |
|
1079 |
return self._SendRequest(HTTP_PUT, |
1080 |
("/%s/nodes/%s/role" %
|
1081 |
(GANETI_RAPI_VERSION, node)), query, role) |
1082 |
|
1083 |
def GetNodeStorageUnits(self, node, storage_type, output_fields): |
1084 |
"""Gets the storage units for a node.
|
1085 |
|
1086 |
@type node: str
|
1087 |
@param node: the node whose storage units to return
|
1088 |
@type storage_type: str
|
1089 |
@param storage_type: storage type whose units to return
|
1090 |
@type output_fields: str
|
1091 |
@param output_fields: storage type fields to return
|
1092 |
|
1093 |
@rtype: int
|
1094 |
@return: job id where results can be retrieved
|
1095 |
|
1096 |
"""
|
1097 |
query = [ |
1098 |
("storage_type", storage_type),
|
1099 |
("output_fields", output_fields),
|
1100 |
] |
1101 |
|
1102 |
return self._SendRequest(HTTP_GET, |
1103 |
("/%s/nodes/%s/storage" %
|
1104 |
(GANETI_RAPI_VERSION, node)), query, None)
|
1105 |
|
1106 |
def ModifyNodeStorageUnits(self, node, storage_type, name, allocatable=None): |
1107 |
"""Modifies parameters of storage units on the node.
|
1108 |
|
1109 |
@type node: str
|
1110 |
@param node: node whose storage units to modify
|
1111 |
@type storage_type: str
|
1112 |
@param storage_type: storage type whose units to modify
|
1113 |
@type name: str
|
1114 |
@param name: name of the storage unit
|
1115 |
@type allocatable: bool or None
|
1116 |
@param allocatable: Whether to set the "allocatable" flag on the storage
|
1117 |
unit (None=no modification, True=set, False=unset)
|
1118 |
|
1119 |
@rtype: int
|
1120 |
@return: job id
|
1121 |
|
1122 |
"""
|
1123 |
query = [ |
1124 |
("storage_type", storage_type),
|
1125 |
("name", name),
|
1126 |
] |
1127 |
|
1128 |
if allocatable is not None: |
1129 |
query.append(("allocatable", allocatable))
|
1130 |
|
1131 |
return self._SendRequest(HTTP_PUT, |
1132 |
("/%s/nodes/%s/storage/modify" %
|
1133 |
(GANETI_RAPI_VERSION, node)), query, None)
|
1134 |
|
1135 |
def RepairNodeStorageUnits(self, node, storage_type, name): |
1136 |
"""Repairs a storage unit on the node.
|
1137 |
|
1138 |
@type node: str
|
1139 |
@param node: node whose storage units to repair
|
1140 |
@type storage_type: str
|
1141 |
@param storage_type: storage type to repair
|
1142 |
@type name: str
|
1143 |
@param name: name of the storage unit to repair
|
1144 |
|
1145 |
@rtype: int
|
1146 |
@return: job id
|
1147 |
|
1148 |
"""
|
1149 |
query = [ |
1150 |
("storage_type", storage_type),
|
1151 |
("name", name),
|
1152 |
] |
1153 |
|
1154 |
return self._SendRequest(HTTP_PUT, |
1155 |
("/%s/nodes/%s/storage/repair" %
|
1156 |
(GANETI_RAPI_VERSION, node)), query, None)
|
1157 |
|
1158 |
def GetNodeTags(self, node): |
1159 |
"""Gets the tags for a node.
|
1160 |
|
1161 |
@type node: str
|
1162 |
@param node: node whose tags to return
|
1163 |
|
1164 |
@rtype: list of str
|
1165 |
@return: tags for the node
|
1166 |
|
1167 |
"""
|
1168 |
return self._SendRequest(HTTP_GET, |
1169 |
("/%s/nodes/%s/tags" %
|
1170 |
(GANETI_RAPI_VERSION, node)), None, None) |
1171 |
|
1172 |
def AddNodeTags(self, node, tags, dry_run=False): |
1173 |
"""Adds tags to a node.
|
1174 |
|
1175 |
@type node: str
|
1176 |
@param node: node to add tags to
|
1177 |
@type tags: list of str
|
1178 |
@param tags: tags to add to the node
|
1179 |
@type dry_run: bool
|
1180 |
@param dry_run: whether to perform a dry run
|
1181 |
|
1182 |
@rtype: int
|
1183 |
@return: job id
|
1184 |
|
1185 |
"""
|
1186 |
query = [("tag", t) for t in tags] |
1187 |
if dry_run:
|
1188 |
query.append(("dry-run", 1)) |
1189 |
|
1190 |
return self._SendRequest(HTTP_PUT, |
1191 |
("/%s/nodes/%s/tags" %
|
1192 |
(GANETI_RAPI_VERSION, node)), query, tags) |
1193 |
|
1194 |
def DeleteNodeTags(self, node, tags, dry_run=False): |
1195 |
"""Delete tags from a node.
|
1196 |
|
1197 |
@type node: str
|
1198 |
@param node: node to remove tags from
|
1199 |
@type tags: list of str
|
1200 |
@param tags: tags to remove from the node
|
1201 |
@type dry_run: bool
|
1202 |
@param dry_run: whether to perform a dry run
|
1203 |
|
1204 |
@rtype: int
|
1205 |
@return: job id
|
1206 |
|
1207 |
"""
|
1208 |
query = [("tag", t) for t in tags] |
1209 |
if dry_run:
|
1210 |
query.append(("dry-run", 1)) |
1211 |
|
1212 |
return self._SendRequest(HTTP_DELETE, |
1213 |
("/%s/nodes/%s/tags" %
|
1214 |
(GANETI_RAPI_VERSION, node)), query, None)
|