root / lib / rpc.py @ c4de9b7a
History | View | Annotate | Download (22.2 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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 |
"""Inter-node RPC library.
|
23 |
|
24 |
"""
|
25 |
|
26 |
# pylint: disable=C0103,R0201,R0904
|
27 |
# C0103: Invalid name, since call_ are not valid
|
28 |
# R0201: Method could be a function, we keep all rpcs instance methods
|
29 |
# as not to change them back and forth between static/instance methods
|
30 |
# if they need to start using instance attributes
|
31 |
# R0904: Too many public methods
|
32 |
|
33 |
import os |
34 |
import logging |
35 |
import zlib |
36 |
import base64 |
37 |
import pycurl |
38 |
import threading |
39 |
|
40 |
from ganeti import utils |
41 |
from ganeti import objects |
42 |
from ganeti import http |
43 |
from ganeti import serializer |
44 |
from ganeti import constants |
45 |
from ganeti import errors |
46 |
from ganeti import netutils |
47 |
from ganeti import ssconf |
48 |
from ganeti import runtime |
49 |
from ganeti import compat |
50 |
|
51 |
# Special module generated at build time
|
52 |
from ganeti import _generated_rpc |
53 |
|
54 |
# pylint has a bug here, doesn't see this import
|
55 |
import ganeti.http.client # pylint: disable=W0611 |
56 |
|
57 |
|
58 |
# Timeout for connecting to nodes (seconds)
|
59 |
_RPC_CONNECT_TIMEOUT = 5
|
60 |
|
61 |
_RPC_CLIENT_HEADERS = [ |
62 |
"Content-type: %s" % http.HTTP_APP_JSON,
|
63 |
"Expect:",
|
64 |
] |
65 |
|
66 |
# Various time constants for the timeout table
|
67 |
_TMO_URGENT = 60 # one minute |
68 |
_TMO_FAST = 5 * 60 # five minutes |
69 |
_TMO_NORMAL = 15 * 60 # 15 minutes |
70 |
_TMO_SLOW = 3600 # one hour |
71 |
_TMO_4HRS = 4 * 3600 |
72 |
_TMO_1DAY = 86400
|
73 |
|
74 |
# Timeout table that will be built later by decorators
|
75 |
# Guidelines for choosing timeouts:
|
76 |
# - call used during watcher: timeout -> 1min, _TMO_URGENT
|
77 |
# - trivial (but be sure it is trivial) (e.g. reading a file): 5min, _TMO_FAST
|
78 |
# - other calls: 15 min, _TMO_NORMAL
|
79 |
# - special calls (instance add, etc.): either _TMO_SLOW (1h) or huge timeouts
|
80 |
|
81 |
_TIMEOUTS = { |
82 |
} |
83 |
|
84 |
#: Special value to describe an offline host
|
85 |
_OFFLINE = object()
|
86 |
|
87 |
|
88 |
def Init(): |
89 |
"""Initializes the module-global HTTP client manager.
|
90 |
|
91 |
Must be called before using any RPC function and while exactly one thread is
|
92 |
running.
|
93 |
|
94 |
"""
|
95 |
# curl_global_init(3) and curl_global_cleanup(3) must be called with only
|
96 |
# one thread running. This check is just a safety measure -- it doesn't
|
97 |
# cover all cases.
|
98 |
assert threading.activeCount() == 1, \ |
99 |
"Found more than one active thread when initializing pycURL"
|
100 |
|
101 |
logging.info("Using PycURL %s", pycurl.version)
|
102 |
|
103 |
pycurl.global_init(pycurl.GLOBAL_ALL) |
104 |
|
105 |
|
106 |
def Shutdown(): |
107 |
"""Stops the module-global HTTP client manager.
|
108 |
|
109 |
Must be called before quitting the program and while exactly one thread is
|
110 |
running.
|
111 |
|
112 |
"""
|
113 |
pycurl.global_cleanup() |
114 |
|
115 |
|
116 |
def _ConfigRpcCurl(curl): |
117 |
noded_cert = str(constants.NODED_CERT_FILE)
|
118 |
|
119 |
curl.setopt(pycurl.FOLLOWLOCATION, False)
|
120 |
curl.setopt(pycurl.CAINFO, noded_cert) |
121 |
curl.setopt(pycurl.SSL_VERIFYHOST, 0)
|
122 |
curl.setopt(pycurl.SSL_VERIFYPEER, True)
|
123 |
curl.setopt(pycurl.SSLCERTTYPE, "PEM")
|
124 |
curl.setopt(pycurl.SSLCERT, noded_cert) |
125 |
curl.setopt(pycurl.SSLKEYTYPE, "PEM")
|
126 |
curl.setopt(pycurl.SSLKEY, noded_cert) |
127 |
curl.setopt(pycurl.CONNECTTIMEOUT, _RPC_CONNECT_TIMEOUT) |
128 |
|
129 |
|
130 |
def _RpcTimeout(secs): |
131 |
"""Timeout decorator.
|
132 |
|
133 |
When applied to a rpc call_* function, it updates the global timeout
|
134 |
table with the given function/timeout.
|
135 |
|
136 |
"""
|
137 |
def decorator(f): |
138 |
name = f.__name__ |
139 |
assert name.startswith("call_") |
140 |
_TIMEOUTS[name[len("call_"):]] = secs |
141 |
return f
|
142 |
return decorator
|
143 |
|
144 |
|
145 |
def RunWithRPC(fn): |
146 |
"""RPC-wrapper decorator.
|
147 |
|
148 |
When applied to a function, it runs it with the RPC system
|
149 |
initialized, and it shutsdown the system afterwards. This means the
|
150 |
function must be called without RPC being initialized.
|
151 |
|
152 |
"""
|
153 |
def wrapper(*args, **kwargs): |
154 |
Init() |
155 |
try:
|
156 |
return fn(*args, **kwargs)
|
157 |
finally:
|
158 |
Shutdown() |
159 |
return wrapper
|
160 |
|
161 |
|
162 |
def _Compress(data): |
163 |
"""Compresses a string for transport over RPC.
|
164 |
|
165 |
Small amounts of data are not compressed.
|
166 |
|
167 |
@type data: str
|
168 |
@param data: Data
|
169 |
@rtype: tuple
|
170 |
@return: Encoded data to send
|
171 |
|
172 |
"""
|
173 |
# Small amounts of data are not compressed
|
174 |
if len(data) < 512: |
175 |
return (constants.RPC_ENCODING_NONE, data)
|
176 |
|
177 |
# Compress with zlib and encode in base64
|
178 |
return (constants.RPC_ENCODING_ZLIB_BASE64,
|
179 |
base64.b64encode(zlib.compress(data, 3)))
|
180 |
|
181 |
|
182 |
class RpcResult(object): |
183 |
"""RPC Result class.
|
184 |
|
185 |
This class holds an RPC result. It is needed since in multi-node
|
186 |
calls we can't raise an exception just because one one out of many
|
187 |
failed, and therefore we use this class to encapsulate the result.
|
188 |
|
189 |
@ivar data: the data payload, for successful results, or None
|
190 |
@ivar call: the name of the RPC call
|
191 |
@ivar node: the name of the node to which we made the call
|
192 |
@ivar offline: whether the operation failed because the node was
|
193 |
offline, as opposed to actual failure; offline=True will always
|
194 |
imply failed=True, in order to allow simpler checking if
|
195 |
the user doesn't care about the exact failure mode
|
196 |
@ivar fail_msg: the error message if the call failed
|
197 |
|
198 |
"""
|
199 |
def __init__(self, data=None, failed=False, offline=False, |
200 |
call=None, node=None): |
201 |
self.offline = offline
|
202 |
self.call = call
|
203 |
self.node = node
|
204 |
|
205 |
if offline:
|
206 |
self.fail_msg = "Node is marked offline" |
207 |
self.data = self.payload = None |
208 |
elif failed:
|
209 |
self.fail_msg = self._EnsureErr(data) |
210 |
self.data = self.payload = None |
211 |
else:
|
212 |
self.data = data
|
213 |
if not isinstance(self.data, (tuple, list)): |
214 |
self.fail_msg = ("RPC layer error: invalid result type (%s)" % |
215 |
type(self.data)) |
216 |
self.payload = None |
217 |
elif len(data) != 2: |
218 |
self.fail_msg = ("RPC layer error: invalid result length (%d), " |
219 |
"expected 2" % len(self.data)) |
220 |
self.payload = None |
221 |
elif not self.data[0]: |
222 |
self.fail_msg = self._EnsureErr(self.data[1]) |
223 |
self.payload = None |
224 |
else:
|
225 |
# finally success
|
226 |
self.fail_msg = None |
227 |
self.payload = data[1] |
228 |
|
229 |
for attr_name in ["call", "data", "fail_msg", |
230 |
"node", "offline", "payload"]: |
231 |
assert hasattr(self, attr_name), "Missing attribute %s" % attr_name |
232 |
|
233 |
@staticmethod
|
234 |
def _EnsureErr(val): |
235 |
"""Helper to ensure we return a 'True' value for error."""
|
236 |
if val:
|
237 |
return val
|
238 |
else:
|
239 |
return "No error information" |
240 |
|
241 |
def Raise(self, msg, prereq=False, ecode=None): |
242 |
"""If the result has failed, raise an OpExecError.
|
243 |
|
244 |
This is used so that LU code doesn't have to check for each
|
245 |
result, but instead can call this function.
|
246 |
|
247 |
"""
|
248 |
if not self.fail_msg: |
249 |
return
|
250 |
|
251 |
if not msg: # one could pass None for default message |
252 |
msg = ("Call '%s' to node '%s' has failed: %s" %
|
253 |
(self.call, self.node, self.fail_msg)) |
254 |
else:
|
255 |
msg = "%s: %s" % (msg, self.fail_msg) |
256 |
if prereq:
|
257 |
ec = errors.OpPrereqError |
258 |
else:
|
259 |
ec = errors.OpExecError |
260 |
if ecode is not None: |
261 |
args = (msg, ecode) |
262 |
else:
|
263 |
args = (msg, ) |
264 |
raise ec(*args) # pylint: disable=W0142 |
265 |
|
266 |
|
267 |
def _SsconfResolver(node_list, |
268 |
ssc=ssconf.SimpleStore, |
269 |
nslookup_fn=netutils.Hostname.GetIP): |
270 |
"""Return addresses for given node names.
|
271 |
|
272 |
@type node_list: list
|
273 |
@param node_list: List of node names
|
274 |
@type ssc: class
|
275 |
@param ssc: SimpleStore class that is used to obtain node->ip mappings
|
276 |
@type nslookup_fn: callable
|
277 |
@param nslookup_fn: function use to do NS lookup
|
278 |
@rtype: list of tuple; (string, string)
|
279 |
@return: List of tuples containing node name and IP address
|
280 |
|
281 |
"""
|
282 |
ss = ssc() |
283 |
iplist = ss.GetNodePrimaryIPList() |
284 |
family = ss.GetPrimaryIPFamily() |
285 |
ipmap = dict(entry.split() for entry in iplist) |
286 |
|
287 |
result = [] |
288 |
for node in node_list: |
289 |
ip = ipmap.get(node) |
290 |
if ip is None: |
291 |
ip = nslookup_fn(node, family=family) |
292 |
result.append((node, ip)) |
293 |
|
294 |
return result
|
295 |
|
296 |
|
297 |
class _StaticResolver: |
298 |
def __init__(self, addresses): |
299 |
"""Initializes this class.
|
300 |
|
301 |
"""
|
302 |
self._addresses = addresses
|
303 |
|
304 |
def __call__(self, hosts): |
305 |
"""Returns static addresses for hosts.
|
306 |
|
307 |
"""
|
308 |
assert len(hosts) == len(self._addresses) |
309 |
return zip(hosts, self._addresses) |
310 |
|
311 |
|
312 |
def _CheckConfigNode(name, node): |
313 |
"""Checks if a node is online.
|
314 |
|
315 |
@type name: string
|
316 |
@param name: Node name
|
317 |
@type node: L{objects.Node} or None
|
318 |
@param node: Node object
|
319 |
|
320 |
"""
|
321 |
if node is None: |
322 |
# Depend on DNS for name resolution
|
323 |
ip = name |
324 |
elif node.offline:
|
325 |
ip = _OFFLINE |
326 |
else:
|
327 |
ip = node.primary_ip |
328 |
return (name, ip)
|
329 |
|
330 |
|
331 |
def _NodeConfigResolver(single_node_fn, all_nodes_fn, hosts): |
332 |
"""Calculate node addresses using configuration.
|
333 |
|
334 |
"""
|
335 |
# Special case for single-host lookups
|
336 |
if len(hosts) == 1: |
337 |
(name, ) = hosts |
338 |
return [_CheckConfigNode(name, single_node_fn(name))]
|
339 |
else:
|
340 |
all_nodes = all_nodes_fn() |
341 |
return [_CheckConfigNode(name, all_nodes.get(name, None)) |
342 |
for name in hosts] |
343 |
|
344 |
|
345 |
class _RpcProcessor: |
346 |
def __init__(self, resolver, port, lock_monitor_cb=None): |
347 |
"""Initializes this class.
|
348 |
|
349 |
@param resolver: callable accepting a list of hostnames, returning a list
|
350 |
of tuples containing name and IP address (IP address can be the name or
|
351 |
the special value L{_OFFLINE} to mark offline machines)
|
352 |
@type port: int
|
353 |
@param port: TCP port
|
354 |
@param lock_monitor_cb: Callable for registering with lock monitor
|
355 |
|
356 |
"""
|
357 |
self._resolver = resolver
|
358 |
self._port = port
|
359 |
self._lock_monitor_cb = lock_monitor_cb
|
360 |
|
361 |
@staticmethod
|
362 |
def _PrepareRequests(hosts, port, procedure, body, read_timeout): |
363 |
"""Prepares requests by sorting offline hosts into separate list.
|
364 |
|
365 |
"""
|
366 |
results = {} |
367 |
requests = {} |
368 |
|
369 |
for (name, ip) in hosts: |
370 |
if ip is _OFFLINE: |
371 |
# Node is marked as offline
|
372 |
results[name] = RpcResult(node=name, offline=True, call=procedure)
|
373 |
else:
|
374 |
requests[name] = \ |
375 |
http.client.HttpClientRequest(str(ip), port,
|
376 |
http.HTTP_PUT, str("/%s" % procedure), |
377 |
headers=_RPC_CLIENT_HEADERS, |
378 |
post_data=body, |
379 |
read_timeout=read_timeout, |
380 |
nicename="%s/%s" % (name, procedure),
|
381 |
curl_config_fn=_ConfigRpcCurl) |
382 |
|
383 |
return (results, requests)
|
384 |
|
385 |
@staticmethod
|
386 |
def _CombineResults(results, requests, procedure): |
387 |
"""Combines pre-computed results for offline hosts with actual call results.
|
388 |
|
389 |
"""
|
390 |
for name, req in requests.items(): |
391 |
if req.success and req.resp_status_code == http.HTTP_OK: |
392 |
host_result = RpcResult(data=serializer.LoadJson(req.resp_body), |
393 |
node=name, call=procedure) |
394 |
else:
|
395 |
# TODO: Better error reporting
|
396 |
if req.error:
|
397 |
msg = req.error |
398 |
else:
|
399 |
msg = req.resp_body |
400 |
|
401 |
logging.error("RPC error in %s on node %s: %s", procedure, name, msg)
|
402 |
host_result = RpcResult(data=msg, failed=True, node=name,
|
403 |
call=procedure) |
404 |
|
405 |
results[name] = host_result |
406 |
|
407 |
return results
|
408 |
|
409 |
def __call__(self, hosts, procedure, body, read_timeout=None, |
410 |
_req_process_fn=http.client.ProcessRequests): |
411 |
"""Makes an RPC request to a number of nodes.
|
412 |
|
413 |
@type hosts: sequence
|
414 |
@param hosts: Hostnames
|
415 |
@type procedure: string
|
416 |
@param procedure: Request path
|
417 |
@type body: string
|
418 |
@param body: Request body
|
419 |
@type read_timeout: int or None
|
420 |
@param read_timeout: Read timeout for request
|
421 |
|
422 |
"""
|
423 |
if read_timeout is None: |
424 |
read_timeout = _TIMEOUTS.get(procedure, None)
|
425 |
|
426 |
assert read_timeout is not None, \ |
427 |
"Missing RPC read timeout for procedure '%s'" % procedure
|
428 |
|
429 |
(results, requests) = \ |
430 |
self._PrepareRequests(self._resolver(hosts), self._port, procedure, |
431 |
str(body), read_timeout)
|
432 |
|
433 |
_req_process_fn(requests.values(), lock_monitor_cb=self._lock_monitor_cb)
|
434 |
|
435 |
assert not frozenset(results).intersection(requests) |
436 |
|
437 |
return self._CombineResults(results, requests, procedure) |
438 |
|
439 |
|
440 |
class RpcRunner(_generated_rpc.RpcClientDefault, |
441 |
_generated_rpc.RpcClientBootstrap): |
442 |
"""RPC runner class.
|
443 |
|
444 |
"""
|
445 |
def __init__(self, context): |
446 |
"""Initialized the RPC runner.
|
447 |
|
448 |
@type context: C{masterd.GanetiContext}
|
449 |
@param context: Ganeti context
|
450 |
|
451 |
"""
|
452 |
# Pylint doesn't recognize multiple inheritance properly, see
|
453 |
# <http://www.logilab.org/ticket/36586> and
|
454 |
# <http://www.logilab.org/ticket/35642>
|
455 |
# pylint: disable=W0233
|
456 |
_generated_rpc.RpcClientBootstrap.__init__(self)
|
457 |
_generated_rpc.RpcClientDefault.__init__(self)
|
458 |
|
459 |
self._cfg = context.cfg
|
460 |
self._proc = _RpcProcessor(compat.partial(_NodeConfigResolver,
|
461 |
self._cfg.GetNodeInfo,
|
462 |
self._cfg.GetAllNodesInfo),
|
463 |
netutils.GetDaemonPort(constants.NODED), |
464 |
lock_monitor_cb=context.glm.AddToLockMonitor) |
465 |
|
466 |
def _InstDict(self, instance, hvp=None, bep=None, osp=None): |
467 |
"""Convert the given instance to a dict.
|
468 |
|
469 |
This is done via the instance's ToDict() method and additionally
|
470 |
we fill the hvparams with the cluster defaults.
|
471 |
|
472 |
@type instance: L{objects.Instance}
|
473 |
@param instance: an Instance object
|
474 |
@type hvp: dict or None
|
475 |
@param hvp: a dictionary with overridden hypervisor parameters
|
476 |
@type bep: dict or None
|
477 |
@param bep: a dictionary with overridden backend parameters
|
478 |
@type osp: dict or None
|
479 |
@param osp: a dictionary with overridden os parameters
|
480 |
@rtype: dict
|
481 |
@return: the instance dict, with the hvparams filled with the
|
482 |
cluster defaults
|
483 |
|
484 |
"""
|
485 |
idict = instance.ToDict() |
486 |
cluster = self._cfg.GetClusterInfo()
|
487 |
idict["hvparams"] = cluster.FillHV(instance)
|
488 |
if hvp is not None: |
489 |
idict["hvparams"].update(hvp)
|
490 |
idict["beparams"] = cluster.FillBE(instance)
|
491 |
if bep is not None: |
492 |
idict["beparams"].update(bep)
|
493 |
idict["osparams"] = cluster.SimpleFillOS(instance.os, instance.osparams)
|
494 |
if osp is not None: |
495 |
idict["osparams"].update(osp)
|
496 |
for nic in idict["nics"]: |
497 |
nic['nicparams'] = objects.FillDict(
|
498 |
cluster.nicparams[constants.PP_DEFAULT], |
499 |
nic['nicparams'])
|
500 |
return idict
|
501 |
|
502 |
def _InstDictHvpBep(self, (instance, hvp, bep)): |
503 |
"""Wrapper for L{_InstDict}.
|
504 |
|
505 |
"""
|
506 |
return self._InstDict(instance, hvp=hvp, bep=bep) |
507 |
|
508 |
def _InstDictOsp(self, (instance, osparams)): |
509 |
"""Wrapper for L{_InstDict}.
|
510 |
|
511 |
"""
|
512 |
return self._InstDict(instance, osp=osparams) |
513 |
|
514 |
def _MultiNodeCall(self, node_list, procedure, args, read_timeout=None): |
515 |
"""Helper for making a multi-node call
|
516 |
|
517 |
"""
|
518 |
body = serializer.DumpJson(args, indent=False)
|
519 |
return self._proc(node_list, procedure, body, read_timeout=read_timeout) |
520 |
|
521 |
def _Call(self, node_list, procedure, timeout, args): |
522 |
"""Entry point for automatically generated RPC wrappers.
|
523 |
|
524 |
"""
|
525 |
return self._MultiNodeCall(node_list, procedure, args, read_timeout=timeout) |
526 |
|
527 |
@staticmethod
|
528 |
def _StaticMultiNodeCall(node_list, procedure, args, |
529 |
address_list=None, read_timeout=None): |
530 |
"""Helper for making a multi-node static call
|
531 |
|
532 |
"""
|
533 |
body = serializer.DumpJson(args, indent=False)
|
534 |
|
535 |
if address_list is None: |
536 |
resolver = _SsconfResolver |
537 |
else:
|
538 |
# Caller provided an address list
|
539 |
resolver = _StaticResolver(address_list) |
540 |
|
541 |
proc = _RpcProcessor(resolver, |
542 |
netutils.GetDaemonPort(constants.NODED)) |
543 |
return proc(node_list, procedure, body, read_timeout=read_timeout)
|
544 |
|
545 |
def _SingleNodeCall(self, node, procedure, args, read_timeout=None): |
546 |
"""Helper for making a single-node call
|
547 |
|
548 |
"""
|
549 |
body = serializer.DumpJson(args, indent=False)
|
550 |
return self._proc([node], procedure, body, read_timeout=read_timeout)[node] |
551 |
|
552 |
@classmethod
|
553 |
def _StaticSingleNodeCall(cls, node, procedure, args, read_timeout=None): |
554 |
"""Helper for making a single-node static call
|
555 |
|
556 |
"""
|
557 |
body = serializer.DumpJson(args, indent=False)
|
558 |
proc = _RpcProcessor(_SsconfResolver, |
559 |
netutils.GetDaemonPort(constants.NODED)) |
560 |
return proc([node], procedure, body, read_timeout=read_timeout)[node]
|
561 |
|
562 |
@staticmethod
|
563 |
def _BlockdevFindPostProc(result): |
564 |
if not result.fail_msg and result.payload is not None: |
565 |
result.payload = objects.BlockDevStatus.FromDict(result.payload) |
566 |
return result
|
567 |
|
568 |
@staticmethod
|
569 |
def _BlockdevGetMirrorStatusPostProc(result): |
570 |
if not result.fail_msg: |
571 |
result.payload = [objects.BlockDevStatus.FromDict(i) |
572 |
for i in result.payload] |
573 |
return result
|
574 |
|
575 |
@staticmethod
|
576 |
def _BlockdevGetMirrorStatusMultiPostProc(result): |
577 |
for nres in result.values(): |
578 |
if nres.fail_msg:
|
579 |
continue
|
580 |
|
581 |
for idx, (success, status) in enumerate(nres.payload): |
582 |
if success:
|
583 |
nres.payload[idx] = (success, objects.BlockDevStatus.FromDict(status)) |
584 |
|
585 |
return result
|
586 |
|
587 |
@staticmethod
|
588 |
def _OsGetPostProc(result): |
589 |
if not result.fail_msg and isinstance(result.payload, dict): |
590 |
result.payload = objects.OS.FromDict(result.payload) |
591 |
return result
|
592 |
|
593 |
@staticmethod
|
594 |
def _PrepareFinalizeExportDisks(snap_disks): |
595 |
flat_disks = [] |
596 |
|
597 |
for disk in snap_disks: |
598 |
if isinstance(disk, bool): |
599 |
flat_disks.append(disk) |
600 |
else:
|
601 |
flat_disks.append(disk.ToDict()) |
602 |
|
603 |
return flat_disks
|
604 |
|
605 |
@staticmethod
|
606 |
def _ImpExpStatusPostProc(result): |
607 |
"""Post-processor for import/export status.
|
608 |
|
609 |
@rtype: Payload containing list of L{objects.ImportExportStatus} instances
|
610 |
@return: Returns a list of the state of each named import/export or None if
|
611 |
a status couldn't be retrieved
|
612 |
|
613 |
"""
|
614 |
if not result.fail_msg: |
615 |
decoded = [] |
616 |
|
617 |
for i in result.payload: |
618 |
if i is None: |
619 |
decoded.append(None)
|
620 |
continue
|
621 |
decoded.append(objects.ImportExportStatus.FromDict(i)) |
622 |
|
623 |
result.payload = decoded |
624 |
|
625 |
return result
|
626 |
|
627 |
@staticmethod
|
628 |
def _EncodeImportExportIO(ieio, ieioargs): |
629 |
"""Encodes import/export I/O information.
|
630 |
|
631 |
"""
|
632 |
if ieio == constants.IEIO_RAW_DISK:
|
633 |
assert len(ieioargs) == 1 |
634 |
return (ieioargs[0].ToDict(), ) |
635 |
|
636 |
if ieio == constants.IEIO_SCRIPT:
|
637 |
assert len(ieioargs) == 2 |
638 |
return (ieioargs[0].ToDict(), ieioargs[1]) |
639 |
|
640 |
return ieioargs
|
641 |
|
642 |
#
|
643 |
# Begin RPC calls
|
644 |
#
|
645 |
|
646 |
@classmethod
|
647 |
@_RpcTimeout(_TMO_NORMAL)
|
648 |
def call_upload_file(cls, node_list, file_name, address_list=None): |
649 |
"""Upload a file.
|
650 |
|
651 |
The node will refuse the operation in case the file is not on the
|
652 |
approved file list.
|
653 |
|
654 |
This is a multi-node call.
|
655 |
|
656 |
@type node_list: list
|
657 |
@param node_list: the list of node names to upload to
|
658 |
@type file_name: str
|
659 |
@param file_name: the filename to upload
|
660 |
@type address_list: list or None
|
661 |
@keyword address_list: an optional list of node addresses, in order
|
662 |
to optimize the RPC speed
|
663 |
|
664 |
"""
|
665 |
file_contents = utils.ReadFile(file_name) |
666 |
data = _Compress(file_contents) |
667 |
st = os.stat(file_name) |
668 |
getents = runtime.GetEnts() |
669 |
params = [file_name, data, st.st_mode, getents.LookupUid(st.st_uid), |
670 |
getents.LookupGid(st.st_gid), st.st_atime, st.st_mtime] |
671 |
return cls._StaticMultiNodeCall(node_list, "upload_file", params, |
672 |
address_list=address_list) |
673 |
|
674 |
@classmethod
|
675 |
@_RpcTimeout(_TMO_NORMAL)
|
676 |
def call_write_ssconf_files(cls, node_list, values): |
677 |
"""Write ssconf files.
|
678 |
|
679 |
This is a multi-node call.
|
680 |
|
681 |
"""
|
682 |
return cls._StaticMultiNodeCall(node_list, "write_ssconf_files", [values]) |
683 |
|
684 |
def call_test_delay(self, node_list, duration, read_timeout=None): |
685 |
"""Sleep for a fixed time on given node(s).
|
686 |
|
687 |
This is a multi-node call.
|
688 |
|
689 |
"""
|
690 |
assert read_timeout is None |
691 |
return self.call_test_delay(node_list, duration, |
692 |
read_timeout=int(duration + 5)) |
693 |
|
694 |
@_RpcTimeout(_TMO_NORMAL)
|
695 |
def call_hypervisor_validate_params(self, node_list, hvname, hvparams): |
696 |
"""Validate the hypervisor params.
|
697 |
|
698 |
This is a multi-node call.
|
699 |
|
700 |
@type node_list: list
|
701 |
@param node_list: the list of nodes to query
|
702 |
@type hvname: string
|
703 |
@param hvname: the hypervisor name
|
704 |
@type hvparams: dict
|
705 |
@param hvparams: the hypervisor parameters to be validated
|
706 |
|
707 |
"""
|
708 |
cluster = self._cfg.GetClusterInfo()
|
709 |
hv_full = objects.FillDict(cluster.hvparams.get(hvname, {}), hvparams) |
710 |
return self._MultiNodeCall(node_list, "hypervisor_validate_params", |
711 |
[hvname, hv_full]) |
712 |
|
713 |
|
714 |
class JobQueueRunner(_generated_rpc.RpcClientJobQueue): |
715 |
"""RPC wrappers for job queue.
|
716 |
|
717 |
"""
|
718 |
_Compress = staticmethod(_Compress)
|
719 |
|
720 |
def __init__(self, context, address_list): |
721 |
"""Initializes this class.
|
722 |
|
723 |
"""
|
724 |
_generated_rpc.RpcClientJobQueue.__init__(self)
|
725 |
|
726 |
if address_list is None: |
727 |
resolver = _SsconfResolver |
728 |
else:
|
729 |
# Caller provided an address list
|
730 |
resolver = _StaticResolver(address_list) |
731 |
|
732 |
self._proc = _RpcProcessor(resolver,
|
733 |
netutils.GetDaemonPort(constants.NODED), |
734 |
lock_monitor_cb=context.glm.AddToLockMonitor) |
735 |
|
736 |
def _Call(self, node_list, procedure, timeout, args): |
737 |
"""Entry point for automatically generated RPC wrappers.
|
738 |
|
739 |
"""
|
740 |
body = serializer.DumpJson(args, indent=False)
|
741 |
|
742 |
return self._proc(node_list, procedure, body, read_timeout=timeout) |
743 |
|
744 |
|
745 |
class BootstrapRunner(_generated_rpc.RpcClientBootstrap): |
746 |
"""RPC wrappers for bootstrapping.
|
747 |
|
748 |
"""
|
749 |
def __init__(self): |
750 |
"""Initializes this class.
|
751 |
|
752 |
"""
|
753 |
_generated_rpc.RpcClientBootstrap.__init__(self)
|
754 |
|
755 |
self._proc = _RpcProcessor(_SsconfResolver,
|
756 |
netutils.GetDaemonPort(constants.NODED)) |
757 |
|
758 |
def _Call(self, node_list, procedure, timeout, args): |
759 |
"""Entry point for automatically generated RPC wrappers.
|
760 |
|
761 |
"""
|
762 |
body = serializer.DumpJson(args, indent=False)
|
763 |
|
764 |
return self._proc(node_list, procedure, body, read_timeout=timeout) |