root / lib / backend.py @ 1c65840b
History | View | Annotate | Download (52.3 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007 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 |
"""Functions used by the node daemon"""
|
23 |
|
24 |
|
25 |
import os |
26 |
import os.path |
27 |
import shutil |
28 |
import time |
29 |
import stat |
30 |
import errno |
31 |
import re |
32 |
import subprocess |
33 |
import random |
34 |
import logging |
35 |
|
36 |
from ganeti import errors |
37 |
from ganeti import utils |
38 |
from ganeti import ssh |
39 |
from ganeti import hypervisor |
40 |
from ganeti import constants |
41 |
from ganeti import bdev |
42 |
from ganeti import objects |
43 |
from ganeti import ssconf |
44 |
|
45 |
|
46 |
def _GetSshRunner(): |
47 |
return ssh.SshRunner()
|
48 |
|
49 |
|
50 |
def StartMaster(start_daemons): |
51 |
"""Activate local node as master node.
|
52 |
|
53 |
The function will always try activate the IP address of the master
|
54 |
(if someone else has it, then it won't). Then, if the start_daemons
|
55 |
parameter is True, it will also start the master daemons
|
56 |
(ganet-masterd and ganeti-rapi).
|
57 |
|
58 |
"""
|
59 |
result = utils.RunCmd([constants.MASTER_SCRIPT, "-d", "start"]) |
60 |
|
61 |
if result.failed:
|
62 |
logging.error("could not activate cluster interface with command %s,"
|
63 |
" error: '%s'", result.cmd, result.output)
|
64 |
return False |
65 |
|
66 |
return True |
67 |
|
68 |
|
69 |
def StopMaster(stop_daemons): |
70 |
"""Deactivate this node as master.
|
71 |
|
72 |
The function will always try to deactivate the IP address of the
|
73 |
master. Then, if the stop_daemons parameter is True, it will also
|
74 |
stop the master daemons (ganet-masterd and ganeti-rapi).
|
75 |
|
76 |
"""
|
77 |
result = utils.RunCmd([constants.MASTER_SCRIPT, "-d", "stop"]) |
78 |
|
79 |
if result.failed:
|
80 |
logging.error("could not deactivate cluster interface with command %s,"
|
81 |
" error: '%s'", result.cmd, result.output)
|
82 |
return False |
83 |
|
84 |
return True |
85 |
|
86 |
|
87 |
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub): |
88 |
"""Joins this node to the cluster.
|
89 |
|
90 |
This does the following:
|
91 |
- updates the hostkeys of the machine (rsa and dsa)
|
92 |
- adds the ssh private key to the user
|
93 |
- adds the ssh public key to the users' authorized_keys file
|
94 |
|
95 |
"""
|
96 |
sshd_keys = [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
|
97 |
(constants.SSH_HOST_RSA_PUB, rsapub, 0644),
|
98 |
(constants.SSH_HOST_DSA_PRIV, dsa, 0600),
|
99 |
(constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
|
100 |
for name, content, mode in sshd_keys: |
101 |
utils.WriteFile(name, data=content, mode=mode) |
102 |
|
103 |
try:
|
104 |
priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS, |
105 |
mkdir=True)
|
106 |
except errors.OpExecError, err:
|
107 |
logging.exception("Error while processing user ssh files")
|
108 |
return False |
109 |
|
110 |
for name, content in [(priv_key, sshkey), (pub_key, sshpub)]: |
111 |
utils.WriteFile(name, data=content, mode=0600)
|
112 |
|
113 |
utils.AddAuthorizedKey(auth_keys, sshpub) |
114 |
|
115 |
utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
|
116 |
|
117 |
return True |
118 |
|
119 |
|
120 |
def LeaveCluster(): |
121 |
"""Cleans up the current node and prepares it to be removed from the cluster.
|
122 |
|
123 |
"""
|
124 |
if os.path.isdir(constants.DATA_DIR):
|
125 |
for rel_name in utils.ListVisibleFiles(constants.DATA_DIR): |
126 |
full_name = os.path.join(constants.DATA_DIR, rel_name) |
127 |
if os.path.isfile(full_name) and not os.path.islink(full_name): |
128 |
utils.RemoveFile(full_name) |
129 |
|
130 |
try:
|
131 |
priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS) |
132 |
except errors.OpExecError:
|
133 |
logging.exception("Error while processing ssh files")
|
134 |
return
|
135 |
|
136 |
f = open(pub_key, 'r') |
137 |
try:
|
138 |
utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
|
139 |
finally:
|
140 |
f.close() |
141 |
|
142 |
utils.RemoveFile(priv_key) |
143 |
utils.RemoveFile(pub_key) |
144 |
|
145 |
# Return a reassuring string to the caller, and quit
|
146 |
raise errors.QuitGanetiException(False, 'Shutdown scheduled') |
147 |
|
148 |
|
149 |
def GetNodeInfo(vgname): |
150 |
"""Gives back a hash with different informations about the node.
|
151 |
|
152 |
Returns:
|
153 |
{ 'vg_size' : xxx, 'vg_free' : xxx, 'memory_domain0': xxx,
|
154 |
'memory_free' : xxx, 'memory_total' : xxx }
|
155 |
where
|
156 |
vg_size is the size of the configured volume group in MiB
|
157 |
vg_free is the free size of the volume group in MiB
|
158 |
memory_dom0 is the memory allocated for domain0 in MiB
|
159 |
memory_free is the currently available (free) ram in MiB
|
160 |
memory_total is the total number of ram in MiB
|
161 |
|
162 |
"""
|
163 |
outputarray = {} |
164 |
vginfo = _GetVGInfo(vgname) |
165 |
outputarray['vg_size'] = vginfo['vg_size'] |
166 |
outputarray['vg_free'] = vginfo['vg_free'] |
167 |
|
168 |
hyper = hypervisor.GetHypervisor() |
169 |
hyp_info = hyper.GetNodeInfo() |
170 |
if hyp_info is not None: |
171 |
outputarray.update(hyp_info) |
172 |
|
173 |
f = open("/proc/sys/kernel/random/boot_id", 'r') |
174 |
try:
|
175 |
outputarray["bootid"] = f.read(128).rstrip("\n") |
176 |
finally:
|
177 |
f.close() |
178 |
|
179 |
return outputarray
|
180 |
|
181 |
|
182 |
def VerifyNode(what): |
183 |
"""Verify the status of the local node.
|
184 |
|
185 |
Args:
|
186 |
what - a dictionary of things to check:
|
187 |
'filelist' : list of files for which to compute checksums
|
188 |
'nodelist' : list of nodes we should check communication with
|
189 |
'hypervisor': run the hypervisor-specific verify
|
190 |
|
191 |
Requested files on local node are checksummed and the result returned.
|
192 |
|
193 |
The nodelist is traversed, with the following checks being made
|
194 |
for each node:
|
195 |
- known_hosts key correct
|
196 |
- correct resolving of node name (target node returns its own hostname
|
197 |
by ssh-execution of 'hostname', result compared against name in list.
|
198 |
|
199 |
"""
|
200 |
result = {} |
201 |
|
202 |
if 'hypervisor' in what: |
203 |
result['hypervisor'] = hypervisor.GetHypervisor().Verify()
|
204 |
|
205 |
if 'filelist' in what: |
206 |
result['filelist'] = utils.FingerprintFiles(what['filelist']) |
207 |
|
208 |
if 'nodelist' in what: |
209 |
result['nodelist'] = {}
|
210 |
random.shuffle(what['nodelist'])
|
211 |
for node in what['nodelist']: |
212 |
success, message = _GetSshRunner().VerifyNodeHostname(node) |
213 |
if not success: |
214 |
result['nodelist'][node] = message
|
215 |
if 'node-net-test' in what: |
216 |
result['node-net-test'] = {}
|
217 |
my_name = utils.HostInfo().name |
218 |
my_pip = my_sip = None
|
219 |
for name, pip, sip in what['node-net-test']: |
220 |
if name == my_name:
|
221 |
my_pip = pip |
222 |
my_sip = sip |
223 |
break
|
224 |
if not my_pip: |
225 |
result['node-net-test'][my_name] = ("Can't find my own" |
226 |
" primary/secondary IP"
|
227 |
" in the node list")
|
228 |
else:
|
229 |
port = ssconf.SimpleStore().GetNodeDaemonPort() |
230 |
for name, pip, sip in what['node-net-test']: |
231 |
fail = [] |
232 |
if not utils.TcpPing(pip, port, source=my_pip): |
233 |
fail.append("primary")
|
234 |
if sip != pip:
|
235 |
if not utils.TcpPing(sip, port, source=my_sip): |
236 |
fail.append("secondary")
|
237 |
if fail:
|
238 |
result['node-net-test'][name] = ("failure using the %s" |
239 |
" interface(s)" %
|
240 |
" and ".join(fail))
|
241 |
|
242 |
return result
|
243 |
|
244 |
|
245 |
def GetVolumeList(vg_name): |
246 |
"""Compute list of logical volumes and their size.
|
247 |
|
248 |
Returns:
|
249 |
dictionary of all partions (key) with their size (in MiB), inactive
|
250 |
and online status:
|
251 |
{'test1': ('20.06', True, True)}
|
252 |
|
253 |
"""
|
254 |
lvs = {} |
255 |
sep = '|'
|
256 |
result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix", |
257 |
"--separator=%s" % sep,
|
258 |
"-olv_name,lv_size,lv_attr", vg_name])
|
259 |
if result.failed:
|
260 |
logging.error("Failed to list logical volumes, lvs output: %s",
|
261 |
result.output) |
262 |
return result.output
|
263 |
|
264 |
valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
|
265 |
for line in result.stdout.splitlines(): |
266 |
line = line.strip() |
267 |
match = valid_line_re.match(line) |
268 |
if not match: |
269 |
logging.error("Invalid line returned from lvs output: '%s'", line)
|
270 |
continue
|
271 |
name, size, attr = match.groups() |
272 |
inactive = attr[4] == '-' |
273 |
online = attr[5] == 'o' |
274 |
lvs[name] = (size, inactive, online) |
275 |
|
276 |
return lvs
|
277 |
|
278 |
|
279 |
def ListVolumeGroups(): |
280 |
"""List the volume groups and their size.
|
281 |
|
282 |
Returns:
|
283 |
Dictionary with keys volume name and values the size of the volume
|
284 |
|
285 |
"""
|
286 |
return utils.ListVolumeGroups()
|
287 |
|
288 |
|
289 |
def NodeVolumes(): |
290 |
"""List all volumes on this node.
|
291 |
|
292 |
"""
|
293 |
result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix", |
294 |
"--separator=|",
|
295 |
"--options=lv_name,lv_size,devices,vg_name"])
|
296 |
if result.failed:
|
297 |
logging.error("Failed to list logical volumes, lvs output: %s",
|
298 |
result.output) |
299 |
return {}
|
300 |
|
301 |
def parse_dev(dev): |
302 |
if '(' in dev: |
303 |
return dev.split('(')[0] |
304 |
else:
|
305 |
return dev
|
306 |
|
307 |
def map_line(line): |
308 |
return {
|
309 |
'name': line[0].strip(), |
310 |
'size': line[1].strip(), |
311 |
'dev': parse_dev(line[2].strip()), |
312 |
'vg': line[3].strip(), |
313 |
} |
314 |
|
315 |
return [map_line(line.split('|')) for line in result.stdout.splitlines() |
316 |
if line.count('|') >= 3] |
317 |
|
318 |
|
319 |
def BridgesExist(bridges_list): |
320 |
"""Check if a list of bridges exist on the current node.
|
321 |
|
322 |
Returns:
|
323 |
True if all of them exist, false otherwise
|
324 |
|
325 |
"""
|
326 |
for bridge in bridges_list: |
327 |
if not utils.BridgeExists(bridge): |
328 |
return False |
329 |
|
330 |
return True |
331 |
|
332 |
|
333 |
def GetInstanceList(): |
334 |
"""Provides a list of instances.
|
335 |
|
336 |
Returns:
|
337 |
A list of all running instances on the current node
|
338 |
- instance1.example.com
|
339 |
- instance2.example.com
|
340 |
|
341 |
"""
|
342 |
try:
|
343 |
names = hypervisor.GetHypervisor().ListInstances() |
344 |
except errors.HypervisorError, err:
|
345 |
logging.exception("Error enumerating instances")
|
346 |
raise
|
347 |
|
348 |
return names
|
349 |
|
350 |
|
351 |
def GetInstanceInfo(instance): |
352 |
"""Gives back the informations about an instance as a dictionary.
|
353 |
|
354 |
Args:
|
355 |
instance: name of the instance (ex. instance1.example.com)
|
356 |
|
357 |
Returns:
|
358 |
{ 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
|
359 |
where
|
360 |
memory: memory size of instance (int)
|
361 |
state: xen state of instance (string)
|
362 |
time: cpu time of instance (float)
|
363 |
|
364 |
"""
|
365 |
output = {} |
366 |
|
367 |
iinfo = hypervisor.GetHypervisor().GetInstanceInfo(instance) |
368 |
if iinfo is not None: |
369 |
output['memory'] = iinfo[2] |
370 |
output['state'] = iinfo[4] |
371 |
output['time'] = iinfo[5] |
372 |
|
373 |
return output
|
374 |
|
375 |
|
376 |
def GetAllInstancesInfo(): |
377 |
"""Gather data about all instances.
|
378 |
|
379 |
This is the equivalent of `GetInstanceInfo()`, except that it
|
380 |
computes data for all instances at once, thus being faster if one
|
381 |
needs data about more than one instance.
|
382 |
|
383 |
Returns: a dictionary of dictionaries, keys being the instance name,
|
384 |
and with values:
|
385 |
{ 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
|
386 |
where
|
387 |
memory: memory size of instance (int)
|
388 |
state: xen state of instance (string)
|
389 |
time: cpu time of instance (float)
|
390 |
vcpus: the number of cpus
|
391 |
|
392 |
"""
|
393 |
output = {} |
394 |
|
395 |
iinfo = hypervisor.GetHypervisor().GetAllInstancesInfo() |
396 |
if iinfo:
|
397 |
for name, inst_id, memory, vcpus, state, times in iinfo: |
398 |
output[name] = { |
399 |
'memory': memory,
|
400 |
'vcpus': vcpus,
|
401 |
'state': state,
|
402 |
'time': times,
|
403 |
} |
404 |
|
405 |
return output
|
406 |
|
407 |
|
408 |
def AddOSToInstance(instance, os_disk, swap_disk): |
409 |
"""Add an OS to an instance.
|
410 |
|
411 |
Args:
|
412 |
instance: the instance object
|
413 |
os_disk: the instance-visible name of the os device
|
414 |
swap_disk: the instance-visible name of the swap device
|
415 |
|
416 |
"""
|
417 |
inst_os = OSFromDisk(instance.os) |
418 |
|
419 |
create_script = inst_os.create_script |
420 |
|
421 |
os_device = instance.FindDisk(os_disk) |
422 |
if os_device is None: |
423 |
logging.error("Can't find this device-visible name '%s'", os_disk)
|
424 |
return False |
425 |
|
426 |
swap_device = instance.FindDisk(swap_disk) |
427 |
if swap_device is None: |
428 |
logging.error("Can't find this device-visible name '%s'", swap_disk)
|
429 |
return False |
430 |
|
431 |
real_os_dev = _RecursiveFindBD(os_device) |
432 |
if real_os_dev is None: |
433 |
raise errors.BlockDeviceError("Block device '%s' is not set up" % |
434 |
str(os_device))
|
435 |
real_os_dev.Open() |
436 |
|
437 |
real_swap_dev = _RecursiveFindBD(swap_device) |
438 |
if real_swap_dev is None: |
439 |
raise errors.BlockDeviceError("Block device '%s' is not set up" % |
440 |
str(swap_device))
|
441 |
real_swap_dev.Open() |
442 |
|
443 |
logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
|
444 |
instance.name, int(time.time()))
|
445 |
if not os.path.exists(constants.LOG_OS_DIR): |
446 |
os.mkdir(constants.LOG_OS_DIR, 0750)
|
447 |
|
448 |
command = utils.BuildShellCmd("cd %s && %s -i %s -b %s -s %s &>%s",
|
449 |
inst_os.path, create_script, instance.name, |
450 |
real_os_dev.dev_path, real_swap_dev.dev_path, |
451 |
logfile) |
452 |
|
453 |
result = utils.RunCmd(command) |
454 |
if result.failed:
|
455 |
logging.error("os create command '%s' returned error: %s, logfile: %s,"
|
456 |
" output: %s", command, result.fail_reason, logfile,
|
457 |
result.output) |
458 |
return False |
459 |
|
460 |
return True |
461 |
|
462 |
|
463 |
def RunRenameInstance(instance, old_name, os_disk, swap_disk): |
464 |
"""Run the OS rename script for an instance.
|
465 |
|
466 |
Args:
|
467 |
instance: the instance object
|
468 |
old_name: the old name of the instance
|
469 |
os_disk: the instance-visible name of the os device
|
470 |
swap_disk: the instance-visible name of the swap device
|
471 |
|
472 |
"""
|
473 |
inst_os = OSFromDisk(instance.os) |
474 |
|
475 |
script = inst_os.rename_script |
476 |
|
477 |
os_device = instance.FindDisk(os_disk) |
478 |
if os_device is None: |
479 |
logging.error("Can't find this device-visible name '%s'", os_disk)
|
480 |
return False |
481 |
|
482 |
swap_device = instance.FindDisk(swap_disk) |
483 |
if swap_device is None: |
484 |
logging.error("Can't find this device-visible name '%s'", swap_disk)
|
485 |
return False |
486 |
|
487 |
real_os_dev = _RecursiveFindBD(os_device) |
488 |
if real_os_dev is None: |
489 |
raise errors.BlockDeviceError("Block device '%s' is not set up" % |
490 |
str(os_device))
|
491 |
real_os_dev.Open() |
492 |
|
493 |
real_swap_dev = _RecursiveFindBD(swap_device) |
494 |
if real_swap_dev is None: |
495 |
raise errors.BlockDeviceError("Block device '%s' is not set up" % |
496 |
str(swap_device))
|
497 |
real_swap_dev.Open() |
498 |
|
499 |
logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
|
500 |
old_name, |
501 |
instance.name, int(time.time()))
|
502 |
if not os.path.exists(constants.LOG_OS_DIR): |
503 |
os.mkdir(constants.LOG_OS_DIR, 0750)
|
504 |
|
505 |
command = utils.BuildShellCmd("cd %s && %s -o %s -n %s -b %s -s %s &>%s",
|
506 |
inst_os.path, script, old_name, instance.name, |
507 |
real_os_dev.dev_path, real_swap_dev.dev_path, |
508 |
logfile) |
509 |
|
510 |
result = utils.RunCmd(command) |
511 |
|
512 |
if result.failed:
|
513 |
logging.error("os create command '%s' returned error: %s output: %s",
|
514 |
command, result.fail_reason, result.output) |
515 |
return False |
516 |
|
517 |
return True |
518 |
|
519 |
|
520 |
def _GetVGInfo(vg_name): |
521 |
"""Get informations about the volume group.
|
522 |
|
523 |
Args:
|
524 |
vg_name: the volume group
|
525 |
|
526 |
Returns:
|
527 |
{ 'vg_size' : xxx, 'vg_free' : xxx, 'pv_count' : xxx }
|
528 |
where
|
529 |
vg_size is the total size of the volume group in MiB
|
530 |
vg_free is the free size of the volume group in MiB
|
531 |
pv_count are the number of physical disks in that vg
|
532 |
|
533 |
If an error occurs during gathering of data, we return the same dict
|
534 |
with keys all set to None.
|
535 |
|
536 |
"""
|
537 |
retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"]) |
538 |
|
539 |
retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings", |
540 |
"--nosuffix", "--units=m", "--separator=:", vg_name]) |
541 |
|
542 |
if retval.failed:
|
543 |
logging.error("volume group %s not present", vg_name)
|
544 |
return retdic
|
545 |
valarr = retval.stdout.strip().rstrip(':').split(':') |
546 |
if len(valarr) == 3: |
547 |
try:
|
548 |
retdic = { |
549 |
"vg_size": int(round(float(valarr[0]), 0)), |
550 |
"vg_free": int(round(float(valarr[1]), 0)), |
551 |
"pv_count": int(valarr[2]), |
552 |
} |
553 |
except ValueError, err: |
554 |
logging.exception("Fail to parse vgs output")
|
555 |
else:
|
556 |
logging.error("vgs output has the wrong number of fields (expected"
|
557 |
" three): %s", str(valarr)) |
558 |
return retdic
|
559 |
|
560 |
|
561 |
def _GatherBlockDevs(instance): |
562 |
"""Set up an instance's block device(s).
|
563 |
|
564 |
This is run on the primary node at instance startup. The block
|
565 |
devices must be already assembled.
|
566 |
|
567 |
"""
|
568 |
block_devices = [] |
569 |
for disk in instance.disks: |
570 |
device = _RecursiveFindBD(disk) |
571 |
if device is None: |
572 |
raise errors.BlockDeviceError("Block device '%s' is not set up." % |
573 |
str(disk))
|
574 |
device.Open() |
575 |
block_devices.append((disk, device)) |
576 |
return block_devices
|
577 |
|
578 |
|
579 |
def StartInstance(instance, extra_args): |
580 |
"""Start an instance.
|
581 |
|
582 |
Args:
|
583 |
instance - name of instance to start.
|
584 |
|
585 |
"""
|
586 |
running_instances = GetInstanceList() |
587 |
|
588 |
if instance.name in running_instances: |
589 |
return True |
590 |
|
591 |
block_devices = _GatherBlockDevs(instance) |
592 |
hyper = hypervisor.GetHypervisor() |
593 |
|
594 |
try:
|
595 |
hyper.StartInstance(instance, block_devices, extra_args) |
596 |
except errors.HypervisorError, err:
|
597 |
logging.exception("Failed to start instance")
|
598 |
return False |
599 |
|
600 |
return True |
601 |
|
602 |
|
603 |
def ShutdownInstance(instance): |
604 |
"""Shut an instance down.
|
605 |
|
606 |
Args:
|
607 |
instance - name of instance to shutdown.
|
608 |
|
609 |
"""
|
610 |
running_instances = GetInstanceList() |
611 |
|
612 |
if instance.name not in running_instances: |
613 |
return True |
614 |
|
615 |
hyper = hypervisor.GetHypervisor() |
616 |
try:
|
617 |
hyper.StopInstance(instance) |
618 |
except errors.HypervisorError, err:
|
619 |
logging.error("Failed to stop instance")
|
620 |
return False |
621 |
|
622 |
# test every 10secs for 2min
|
623 |
shutdown_ok = False
|
624 |
|
625 |
time.sleep(1)
|
626 |
for dummy in range(11): |
627 |
if instance.name not in GetInstanceList(): |
628 |
break
|
629 |
time.sleep(10)
|
630 |
else:
|
631 |
# the shutdown did not succeed
|
632 |
logging.error("shutdown of '%s' unsuccessful, using destroy", instance)
|
633 |
|
634 |
try:
|
635 |
hyper.StopInstance(instance, force=True)
|
636 |
except errors.HypervisorError, err:
|
637 |
logging.exception("Failed to stop instance")
|
638 |
return False |
639 |
|
640 |
time.sleep(1)
|
641 |
if instance.name in GetInstanceList(): |
642 |
logging.error("could not shutdown instance '%s' even by destroy",
|
643 |
instance.name) |
644 |
return False |
645 |
|
646 |
return True |
647 |
|
648 |
|
649 |
def RebootInstance(instance, reboot_type, extra_args): |
650 |
"""Reboot an instance.
|
651 |
|
652 |
Args:
|
653 |
instance - name of instance to reboot
|
654 |
reboot_type - how to reboot [soft,hard,full]
|
655 |
|
656 |
"""
|
657 |
running_instances = GetInstanceList() |
658 |
|
659 |
if instance.name not in running_instances: |
660 |
logging.error("Cannot reboot instance that is not running")
|
661 |
return False |
662 |
|
663 |
hyper = hypervisor.GetHypervisor() |
664 |
if reboot_type == constants.INSTANCE_REBOOT_SOFT:
|
665 |
try:
|
666 |
hyper.RebootInstance(instance) |
667 |
except errors.HypervisorError, err:
|
668 |
logging.exception("Failed to soft reboot instance")
|
669 |
return False |
670 |
elif reboot_type == constants.INSTANCE_REBOOT_HARD:
|
671 |
try:
|
672 |
ShutdownInstance(instance) |
673 |
StartInstance(instance, extra_args) |
674 |
except errors.HypervisorError, err:
|
675 |
logging.exception("Failed to hard reboot instance")
|
676 |
return False |
677 |
else:
|
678 |
raise errors.ParameterError("reboot_type invalid") |
679 |
|
680 |
|
681 |
return True |
682 |
|
683 |
|
684 |
def MigrateInstance(instance, target, live): |
685 |
"""Migrates an instance to another node.
|
686 |
|
687 |
"""
|
688 |
hyper = hypervisor.GetHypervisor() |
689 |
|
690 |
try:
|
691 |
hyper.MigrateInstance(instance, target, live) |
692 |
except errors.HypervisorError, err:
|
693 |
msg = "Failed to migrate instance: %s" % str(err) |
694 |
logging.error(msg) |
695 |
return (False, msg) |
696 |
return (True, "Migration successfull") |
697 |
|
698 |
|
699 |
def CreateBlockDevice(disk, size, owner, on_primary, info): |
700 |
"""Creates a block device for an instance.
|
701 |
|
702 |
Args:
|
703 |
disk: a ganeti.objects.Disk object
|
704 |
size: the size of the physical underlying device
|
705 |
owner: a string with the name of the instance
|
706 |
on_primary: a boolean indicating if it is the primary node or not
|
707 |
info: string that will be sent to the physical device creation
|
708 |
|
709 |
Returns:
|
710 |
the new unique_id of the device (this can sometime be
|
711 |
computed only after creation), or None. On secondary nodes,
|
712 |
it's not required to return anything.
|
713 |
|
714 |
"""
|
715 |
clist = [] |
716 |
if disk.children:
|
717 |
for child in disk.children: |
718 |
crdev = _RecursiveAssembleBD(child, owner, on_primary) |
719 |
if on_primary or disk.AssembleOnSecondary(): |
720 |
# we need the children open in case the device itself has to
|
721 |
# be assembled
|
722 |
crdev.Open() |
723 |
clist.append(crdev) |
724 |
try:
|
725 |
device = bdev.FindDevice(disk.dev_type, disk.physical_id, clist) |
726 |
if device is not None: |
727 |
logging.info("removing existing device %s", disk)
|
728 |
device.Remove() |
729 |
except errors.BlockDeviceError, err:
|
730 |
pass
|
731 |
|
732 |
device = bdev.Create(disk.dev_type, disk.physical_id, |
733 |
clist, size) |
734 |
if device is None: |
735 |
raise ValueError("Can't create child device for %s, %s" % |
736 |
(disk, size)) |
737 |
if on_primary or disk.AssembleOnSecondary(): |
738 |
if not device.Assemble(): |
739 |
errorstring = "Can't assemble device after creation"
|
740 |
logging.error(errorstring) |
741 |
raise errors.BlockDeviceError("%s, very unusual event - check the node" |
742 |
" daemon logs" % errorstring)
|
743 |
device.SetSyncSpeed(constants.SYNC_SPEED) |
744 |
if on_primary or disk.OpenOnSecondary(): |
745 |
device.Open(force=True)
|
746 |
DevCacheManager.UpdateCache(device.dev_path, owner, |
747 |
on_primary, disk.iv_name) |
748 |
|
749 |
device.SetInfo(info) |
750 |
|
751 |
physical_id = device.unique_id |
752 |
return physical_id
|
753 |
|
754 |
|
755 |
def RemoveBlockDevice(disk): |
756 |
"""Remove a block device.
|
757 |
|
758 |
This is intended to be called recursively.
|
759 |
|
760 |
"""
|
761 |
try:
|
762 |
# since we are removing the device, allow a partial match
|
763 |
# this allows removal of broken mirrors
|
764 |
rdev = _RecursiveFindBD(disk, allow_partial=True)
|
765 |
except errors.BlockDeviceError, err:
|
766 |
# probably can't attach
|
767 |
logging.info("Can't attach to device %s in remove", disk)
|
768 |
rdev = None
|
769 |
if rdev is not None: |
770 |
r_path = rdev.dev_path |
771 |
result = rdev.Remove() |
772 |
if result:
|
773 |
DevCacheManager.RemoveCache(r_path) |
774 |
else:
|
775 |
result = True
|
776 |
if disk.children:
|
777 |
for child in disk.children: |
778 |
result = result and RemoveBlockDevice(child)
|
779 |
return result
|
780 |
|
781 |
|
782 |
def _RecursiveAssembleBD(disk, owner, as_primary): |
783 |
"""Activate a block device for an instance.
|
784 |
|
785 |
This is run on the primary and secondary nodes for an instance.
|
786 |
|
787 |
This function is called recursively.
|
788 |
|
789 |
Args:
|
790 |
disk: a objects.Disk object
|
791 |
as_primary: if we should make the block device read/write
|
792 |
|
793 |
Returns:
|
794 |
the assembled device or None (in case no device was assembled)
|
795 |
|
796 |
If the assembly is not successful, an exception is raised.
|
797 |
|
798 |
"""
|
799 |
children = [] |
800 |
if disk.children:
|
801 |
mcn = disk.ChildrenNeeded() |
802 |
if mcn == -1: |
803 |
mcn = 0 # max number of Nones allowed |
804 |
else:
|
805 |
mcn = len(disk.children) - mcn # max number of Nones |
806 |
for chld_disk in disk.children: |
807 |
try:
|
808 |
cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary) |
809 |
except errors.BlockDeviceError, err:
|
810 |
if children.count(None) >= mcn: |
811 |
raise
|
812 |
cdev = None
|
813 |
logging.debug("Error in child activation: %s", str(err)) |
814 |
children.append(cdev) |
815 |
|
816 |
if as_primary or disk.AssembleOnSecondary(): |
817 |
r_dev = bdev.AttachOrAssemble(disk.dev_type, disk.physical_id, children) |
818 |
r_dev.SetSyncSpeed(constants.SYNC_SPEED) |
819 |
result = r_dev |
820 |
if as_primary or disk.OpenOnSecondary(): |
821 |
r_dev.Open() |
822 |
DevCacheManager.UpdateCache(r_dev.dev_path, owner, |
823 |
as_primary, disk.iv_name) |
824 |
|
825 |
else:
|
826 |
result = True
|
827 |
return result
|
828 |
|
829 |
|
830 |
def AssembleBlockDevice(disk, owner, as_primary): |
831 |
"""Activate a block device for an instance.
|
832 |
|
833 |
This is a wrapper over _RecursiveAssembleBD.
|
834 |
|
835 |
Returns:
|
836 |
a /dev path for primary nodes
|
837 |
True for secondary nodes
|
838 |
|
839 |
"""
|
840 |
result = _RecursiveAssembleBD(disk, owner, as_primary) |
841 |
if isinstance(result, bdev.BlockDev): |
842 |
result = result.dev_path |
843 |
return result
|
844 |
|
845 |
|
846 |
def ShutdownBlockDevice(disk): |
847 |
"""Shut down a block device.
|
848 |
|
849 |
First, if the device is assembled (can `Attach()`), then the device
|
850 |
is shutdown. Then the children of the device are shutdown.
|
851 |
|
852 |
This function is called recursively. Note that we don't cache the
|
853 |
children or such, as oppossed to assemble, shutdown of different
|
854 |
devices doesn't require that the upper device was active.
|
855 |
|
856 |
"""
|
857 |
r_dev = _RecursiveFindBD(disk) |
858 |
if r_dev is not None: |
859 |
r_path = r_dev.dev_path |
860 |
result = r_dev.Shutdown() |
861 |
if result:
|
862 |
DevCacheManager.RemoveCache(r_path) |
863 |
else:
|
864 |
result = True
|
865 |
if disk.children:
|
866 |
for child in disk.children: |
867 |
result = result and ShutdownBlockDevice(child)
|
868 |
return result
|
869 |
|
870 |
|
871 |
def MirrorAddChildren(parent_cdev, new_cdevs): |
872 |
"""Extend a mirrored block device.
|
873 |
|
874 |
"""
|
875 |
parent_bdev = _RecursiveFindBD(parent_cdev, allow_partial=True)
|
876 |
if parent_bdev is None: |
877 |
logging.error("Can't find parent device")
|
878 |
return False |
879 |
new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs] |
880 |
if new_bdevs.count(None) > 0: |
881 |
logging.error("Can't find new device(s) to add: %s:%s",
|
882 |
new_bdevs, new_cdevs) |
883 |
return False |
884 |
parent_bdev.AddChildren(new_bdevs) |
885 |
return True |
886 |
|
887 |
|
888 |
def MirrorRemoveChildren(parent_cdev, new_cdevs): |
889 |
"""Shrink a mirrored block device.
|
890 |
|
891 |
"""
|
892 |
parent_bdev = _RecursiveFindBD(parent_cdev) |
893 |
if parent_bdev is None: |
894 |
logging.error("Can't find parent in remove children: %s", parent_cdev)
|
895 |
return False |
896 |
devs = [] |
897 |
for disk in new_cdevs: |
898 |
rpath = disk.StaticDevPath() |
899 |
if rpath is None: |
900 |
bd = _RecursiveFindBD(disk) |
901 |
if bd is None: |
902 |
logging.error("Can't find dynamic device %s while removing children",
|
903 |
disk) |
904 |
return False |
905 |
else:
|
906 |
devs.append(bd.dev_path) |
907 |
else:
|
908 |
devs.append(rpath) |
909 |
parent_bdev.RemoveChildren(devs) |
910 |
return True |
911 |
|
912 |
|
913 |
def GetMirrorStatus(disks): |
914 |
"""Get the mirroring status of a list of devices.
|
915 |
|
916 |
Args:
|
917 |
disks: list of `objects.Disk`
|
918 |
|
919 |
Returns:
|
920 |
list of (mirror_done, estimated_time) tuples, which
|
921 |
are the result of bdev.BlockDevice.CombinedSyncStatus()
|
922 |
|
923 |
"""
|
924 |
stats = [] |
925 |
for dsk in disks: |
926 |
rbd = _RecursiveFindBD(dsk) |
927 |
if rbd is None: |
928 |
raise errors.BlockDeviceError("Can't find device %s" % str(dsk)) |
929 |
stats.append(rbd.CombinedSyncStatus()) |
930 |
return stats
|
931 |
|
932 |
|
933 |
def _RecursiveFindBD(disk, allow_partial=False): |
934 |
"""Check if a device is activated.
|
935 |
|
936 |
If so, return informations about the real device.
|
937 |
|
938 |
Args:
|
939 |
disk: the objects.Disk instance
|
940 |
allow_partial: don't abort the find if a child of the
|
941 |
device can't be found; this is intended to be
|
942 |
used when repairing mirrors
|
943 |
|
944 |
Returns:
|
945 |
None if the device can't be found
|
946 |
otherwise the device instance
|
947 |
|
948 |
"""
|
949 |
children = [] |
950 |
if disk.children:
|
951 |
for chdisk in disk.children: |
952 |
children.append(_RecursiveFindBD(chdisk)) |
953 |
|
954 |
return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
|
955 |
|
956 |
|
957 |
def FindBlockDevice(disk): |
958 |
"""Check if a device is activated.
|
959 |
|
960 |
If so, return informations about the real device.
|
961 |
|
962 |
Args:
|
963 |
disk: the objects.Disk instance
|
964 |
Returns:
|
965 |
None if the device can't be found
|
966 |
(device_path, major, minor, sync_percent, estimated_time, is_degraded)
|
967 |
|
968 |
"""
|
969 |
rbd = _RecursiveFindBD(disk) |
970 |
if rbd is None: |
971 |
return rbd
|
972 |
return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
|
973 |
|
974 |
|
975 |
def UploadFile(file_name, data, mode, uid, gid, atime, mtime): |
976 |
"""Write a file to the filesystem.
|
977 |
|
978 |
This allows the master to overwrite(!) a file. It will only perform
|
979 |
the operation if the file belongs to a list of configuration files.
|
980 |
|
981 |
"""
|
982 |
if not os.path.isabs(file_name): |
983 |
logging.error("Filename passed to UploadFile is not absolute: '%s'",
|
984 |
file_name) |
985 |
return False |
986 |
|
987 |
allowed_files = [ |
988 |
constants.CLUSTER_CONF_FILE, |
989 |
constants.ETC_HOSTS, |
990 |
constants.SSH_KNOWN_HOSTS_FILE, |
991 |
constants.VNC_PASSWORD_FILE, |
992 |
constants.JOB_QUEUE_SERIAL_FILE, |
993 |
] |
994 |
allowed_files.extend(ssconf.SimpleStore().GetFileList()) |
995 |
if file_name not in allowed_files: |
996 |
logging.error("Filename passed to UploadFile not in allowed"
|
997 |
" upload targets: '%s'", file_name)
|
998 |
return False |
999 |
|
1000 |
utils.WriteFile(file_name, data=data, mode=mode, uid=uid, gid=gid, |
1001 |
atime=atime, mtime=mtime) |
1002 |
return True |
1003 |
|
1004 |
|
1005 |
def _ErrnoOrStr(err): |
1006 |
"""Format an EnvironmentError exception.
|
1007 |
|
1008 |
If the `err` argument has an errno attribute, it will be looked up
|
1009 |
and converted into a textual EXXXX description. Otherwise the string
|
1010 |
representation of the error will be returned.
|
1011 |
|
1012 |
"""
|
1013 |
if hasattr(err, 'errno'): |
1014 |
detail = errno.errorcode[err.errno] |
1015 |
else:
|
1016 |
detail = str(err)
|
1017 |
return detail
|
1018 |
|
1019 |
|
1020 |
def _OSOndiskVersion(name, os_dir): |
1021 |
"""Compute and return the API version of a given OS.
|
1022 |
|
1023 |
This function will try to read the API version of the os given by
|
1024 |
the 'name' parameter and residing in the 'os_dir' directory.
|
1025 |
|
1026 |
Return value will be either an integer denoting the version or None in the
|
1027 |
case when this is not a valid OS name.
|
1028 |
|
1029 |
"""
|
1030 |
api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
|
1031 |
|
1032 |
try:
|
1033 |
st = os.stat(api_file) |
1034 |
except EnvironmentError, err: |
1035 |
raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not" |
1036 |
" found (%s)" % _ErrnoOrStr(err))
|
1037 |
|
1038 |
if not stat.S_ISREG(stat.S_IFMT(st.st_mode)): |
1039 |
raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not" |
1040 |
" a regular file")
|
1041 |
|
1042 |
try:
|
1043 |
f = open(api_file)
|
1044 |
try:
|
1045 |
api_version = f.read(256)
|
1046 |
finally:
|
1047 |
f.close() |
1048 |
except EnvironmentError, err: |
1049 |
raise errors.InvalidOS(name, os_dir, "error while reading the" |
1050 |
" API version (%s)" % _ErrnoOrStr(err))
|
1051 |
|
1052 |
api_version = api_version.strip() |
1053 |
try:
|
1054 |
api_version = int(api_version)
|
1055 |
except (TypeError, ValueError), err: |
1056 |
raise errors.InvalidOS(name, os_dir,
|
1057 |
"API version is not integer (%s)" % str(err)) |
1058 |
|
1059 |
return api_version
|
1060 |
|
1061 |
|
1062 |
def DiagnoseOS(top_dirs=None): |
1063 |
"""Compute the validity for all OSes.
|
1064 |
|
1065 |
Returns an OS object for each name in all the given top directories
|
1066 |
(if not given defaults to constants.OS_SEARCH_PATH)
|
1067 |
|
1068 |
Returns:
|
1069 |
list of OS objects
|
1070 |
|
1071 |
"""
|
1072 |
if top_dirs is None: |
1073 |
top_dirs = constants.OS_SEARCH_PATH |
1074 |
|
1075 |
result = [] |
1076 |
for dir_name in top_dirs: |
1077 |
if os.path.isdir(dir_name):
|
1078 |
try:
|
1079 |
f_names = utils.ListVisibleFiles(dir_name) |
1080 |
except EnvironmentError, err: |
1081 |
logging.exception("Can't list the OS directory %s", dir_name)
|
1082 |
break
|
1083 |
for name in f_names: |
1084 |
try:
|
1085 |
os_inst = OSFromDisk(name, base_dir=dir_name) |
1086 |
result.append(os_inst) |
1087 |
except errors.InvalidOS, err:
|
1088 |
result.append(objects.OS.FromInvalidOS(err)) |
1089 |
|
1090 |
return result
|
1091 |
|
1092 |
|
1093 |
def OSFromDisk(name, base_dir=None): |
1094 |
"""Create an OS instance from disk.
|
1095 |
|
1096 |
This function will return an OS instance if the given name is a
|
1097 |
valid OS name. Otherwise, it will raise an appropriate
|
1098 |
`errors.InvalidOS` exception, detailing why this is not a valid
|
1099 |
OS.
|
1100 |
|
1101 |
Args:
|
1102 |
os_dir: Directory containing the OS scripts. Defaults to a search
|
1103 |
in all the OS_SEARCH_PATH directories.
|
1104 |
|
1105 |
"""
|
1106 |
|
1107 |
if base_dir is None: |
1108 |
os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir) |
1109 |
if os_dir is None: |
1110 |
raise errors.InvalidOS(name, None, "OS dir not found in search path") |
1111 |
else:
|
1112 |
os_dir = os.path.sep.join([base_dir, name]) |
1113 |
|
1114 |
api_version = _OSOndiskVersion(name, os_dir) |
1115 |
|
1116 |
if api_version != constants.OS_API_VERSION:
|
1117 |
raise errors.InvalidOS(name, os_dir, "API version mismatch" |
1118 |
" (found %s want %s)"
|
1119 |
% (api_version, constants.OS_API_VERSION)) |
1120 |
|
1121 |
# OS Scripts dictionary, we will populate it with the actual script names
|
1122 |
os_scripts = {'create': '', 'export': '', 'import': '', 'rename': ''} |
1123 |
|
1124 |
for script in os_scripts: |
1125 |
os_scripts[script] = os.path.sep.join([os_dir, script]) |
1126 |
|
1127 |
try:
|
1128 |
st = os.stat(os_scripts[script]) |
1129 |
except EnvironmentError, err: |
1130 |
raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" % |
1131 |
(script, _ErrnoOrStr(err))) |
1132 |
|
1133 |
if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
|
1134 |
raise errors.InvalidOS(name, os_dir, "'%s' script not executable" % |
1135 |
script) |
1136 |
|
1137 |
if not stat.S_ISREG(stat.S_IFMT(st.st_mode)): |
1138 |
raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" % |
1139 |
script) |
1140 |
|
1141 |
|
1142 |
return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
|
1143 |
create_script=os_scripts['create'],
|
1144 |
export_script=os_scripts['export'],
|
1145 |
import_script=os_scripts['import'],
|
1146 |
rename_script=os_scripts['rename'],
|
1147 |
api_version=api_version) |
1148 |
|
1149 |
|
1150 |
def GrowBlockDevice(disk, amount): |
1151 |
"""Grow a stack of block devices.
|
1152 |
|
1153 |
This function is called recursively, with the childrens being the
|
1154 |
first one resize.
|
1155 |
|
1156 |
Args:
|
1157 |
disk: the disk to be grown
|
1158 |
|
1159 |
Returns: a tuple of (status, result), with:
|
1160 |
status: the result (true/false) of the operation
|
1161 |
result: the error message if the operation failed, otherwise not used
|
1162 |
|
1163 |
"""
|
1164 |
r_dev = _RecursiveFindBD(disk) |
1165 |
if r_dev is None: |
1166 |
return False, "Cannot find block device %s" % (disk,) |
1167 |
|
1168 |
try:
|
1169 |
r_dev.Grow(amount) |
1170 |
except errors.BlockDeviceError, err:
|
1171 |
return False, str(err) |
1172 |
|
1173 |
return True, None |
1174 |
|
1175 |
|
1176 |
def SnapshotBlockDevice(disk): |
1177 |
"""Create a snapshot copy of a block device.
|
1178 |
|
1179 |
This function is called recursively, and the snapshot is actually created
|
1180 |
just for the leaf lvm backend device.
|
1181 |
|
1182 |
Args:
|
1183 |
disk: the disk to be snapshotted
|
1184 |
|
1185 |
Returns:
|
1186 |
a config entry for the actual lvm device snapshotted.
|
1187 |
|
1188 |
"""
|
1189 |
if disk.children:
|
1190 |
if len(disk.children) == 1: |
1191 |
# only one child, let's recurse on it
|
1192 |
return SnapshotBlockDevice(disk.children[0]) |
1193 |
else:
|
1194 |
# more than one child, choose one that matches
|
1195 |
for child in disk.children: |
1196 |
if child.size == disk.size:
|
1197 |
# return implies breaking the loop
|
1198 |
return SnapshotBlockDevice(child)
|
1199 |
elif disk.dev_type == constants.LD_LV:
|
1200 |
r_dev = _RecursiveFindBD(disk) |
1201 |
if r_dev is not None: |
1202 |
# let's stay on the safe side and ask for the full size, for now
|
1203 |
return r_dev.Snapshot(disk.size)
|
1204 |
else:
|
1205 |
return None |
1206 |
else:
|
1207 |
raise errors.ProgrammerError("Cannot snapshot non-lvm block device" |
1208 |
" '%s' of type '%s'" %
|
1209 |
(disk.unique_id, disk.dev_type)) |
1210 |
|
1211 |
|
1212 |
def ExportSnapshot(disk, dest_node, instance): |
1213 |
"""Export a block device snapshot to a remote node.
|
1214 |
|
1215 |
Args:
|
1216 |
disk: the snapshot block device
|
1217 |
dest_node: the node to send the image to
|
1218 |
instance: instance being exported
|
1219 |
|
1220 |
Returns:
|
1221 |
True if successful, False otherwise.
|
1222 |
|
1223 |
"""
|
1224 |
inst_os = OSFromDisk(instance.os) |
1225 |
export_script = inst_os.export_script |
1226 |
|
1227 |
logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
|
1228 |
instance.name, int(time.time()))
|
1229 |
if not os.path.exists(constants.LOG_OS_DIR): |
1230 |
os.mkdir(constants.LOG_OS_DIR, 0750)
|
1231 |
|
1232 |
real_os_dev = _RecursiveFindBD(disk) |
1233 |
if real_os_dev is None: |
1234 |
raise errors.BlockDeviceError("Block device '%s' is not set up" % |
1235 |
str(disk))
|
1236 |
real_os_dev.Open() |
1237 |
|
1238 |
destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
|
1239 |
destfile = disk.physical_id[1]
|
1240 |
|
1241 |
# the target command is built out of three individual commands,
|
1242 |
# which are joined by pipes; we check each individual command for
|
1243 |
# valid parameters
|
1244 |
|
1245 |
expcmd = utils.BuildShellCmd("cd %s; %s -i %s -b %s 2>%s", inst_os.path,
|
1246 |
export_script, instance.name, |
1247 |
real_os_dev.dev_path, logfile) |
1248 |
|
1249 |
comprcmd = "gzip"
|
1250 |
|
1251 |
destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
|
1252 |
destdir, destdir, destfile) |
1253 |
remotecmd = _GetSshRunner().BuildCmd(dest_node, constants.GANETI_RUNAS, |
1254 |
destcmd) |
1255 |
|
1256 |
# all commands have been checked, so we're safe to combine them
|
1257 |
command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
|
1258 |
|
1259 |
result = utils.RunCmd(command) |
1260 |
|
1261 |
if result.failed:
|
1262 |
logging.error("os snapshot export command '%s' returned error: %s"
|
1263 |
" output: %s", command, result.fail_reason, result.output)
|
1264 |
return False |
1265 |
|
1266 |
return True |
1267 |
|
1268 |
|
1269 |
def FinalizeExport(instance, snap_disks): |
1270 |
"""Write out the export configuration information.
|
1271 |
|
1272 |
Args:
|
1273 |
instance: instance configuration
|
1274 |
snap_disks: snapshot block devices
|
1275 |
|
1276 |
Returns:
|
1277 |
False in case of error, True otherwise.
|
1278 |
|
1279 |
"""
|
1280 |
destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
|
1281 |
finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name) |
1282 |
|
1283 |
config = objects.SerializableConfigParser() |
1284 |
|
1285 |
config.add_section(constants.INISECT_EXP) |
1286 |
config.set(constants.INISECT_EXP, 'version', '0') |
1287 |
config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time())) |
1288 |
config.set(constants.INISECT_EXP, 'source', instance.primary_node)
|
1289 |
config.set(constants.INISECT_EXP, 'os', instance.os)
|
1290 |
config.set(constants.INISECT_EXP, 'compression', 'gzip') |
1291 |
|
1292 |
config.add_section(constants.INISECT_INS) |
1293 |
config.set(constants.INISECT_INS, 'name', instance.name)
|
1294 |
config.set(constants.INISECT_INS, 'memory', '%d' % instance.memory) |
1295 |
config.set(constants.INISECT_INS, 'vcpus', '%d' % instance.vcpus) |
1296 |
config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
|
1297 |
|
1298 |
nic_count = 0
|
1299 |
for nic_count, nic in enumerate(instance.nics): |
1300 |
config.set(constants.INISECT_INS, 'nic%d_mac' %
|
1301 |
nic_count, '%s' % nic.mac)
|
1302 |
config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip) |
1303 |
config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count, '%s' % nic.bridge) |
1304 |
# TODO: redundant: on load can read nics until it doesn't exist
|
1305 |
config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_count) |
1306 |
|
1307 |
disk_count = 0
|
1308 |
for disk_count, disk in enumerate(snap_disks): |
1309 |
config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
|
1310 |
('%s' % disk.iv_name))
|
1311 |
config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
|
1312 |
('%s' % disk.physical_id[1])) |
1313 |
config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
|
1314 |
('%d' % disk.size))
|
1315 |
config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_count) |
1316 |
|
1317 |
cff = os.path.join(destdir, constants.EXPORT_CONF_FILE) |
1318 |
cfo = open(cff, 'w') |
1319 |
try:
|
1320 |
config.write(cfo) |
1321 |
finally:
|
1322 |
cfo.close() |
1323 |
|
1324 |
shutil.rmtree(finaldestdir, True)
|
1325 |
shutil.move(destdir, finaldestdir) |
1326 |
|
1327 |
return True |
1328 |
|
1329 |
|
1330 |
def ExportInfo(dest): |
1331 |
"""Get export configuration information.
|
1332 |
|
1333 |
Args:
|
1334 |
dest: directory containing the export
|
1335 |
|
1336 |
Returns:
|
1337 |
A serializable config file containing the export info.
|
1338 |
|
1339 |
"""
|
1340 |
cff = os.path.join(dest, constants.EXPORT_CONF_FILE) |
1341 |
|
1342 |
config = objects.SerializableConfigParser() |
1343 |
config.read(cff) |
1344 |
|
1345 |
if (not config.has_section(constants.INISECT_EXP) or |
1346 |
not config.has_section(constants.INISECT_INS)):
|
1347 |
return None |
1348 |
|
1349 |
return config
|
1350 |
|
1351 |
|
1352 |
def ImportOSIntoInstance(instance, os_disk, swap_disk, src_node, src_image): |
1353 |
"""Import an os image into an instance.
|
1354 |
|
1355 |
Args:
|
1356 |
instance: the instance object
|
1357 |
os_disk: the instance-visible name of the os device
|
1358 |
swap_disk: the instance-visible name of the swap device
|
1359 |
src_node: node holding the source image
|
1360 |
src_image: path to the source image on src_node
|
1361 |
|
1362 |
Returns:
|
1363 |
False in case of error, True otherwise.
|
1364 |
|
1365 |
"""
|
1366 |
inst_os = OSFromDisk(instance.os) |
1367 |
import_script = inst_os.import_script |
1368 |
|
1369 |
os_device = instance.FindDisk(os_disk) |
1370 |
if os_device is None: |
1371 |
logging.error("Can't find this device-visible name '%s'", os_disk)
|
1372 |
return False |
1373 |
|
1374 |
swap_device = instance.FindDisk(swap_disk) |
1375 |
if swap_device is None: |
1376 |
logging.error("Can't find this device-visible name '%s'", swap_disk)
|
1377 |
return False |
1378 |
|
1379 |
real_os_dev = _RecursiveFindBD(os_device) |
1380 |
if real_os_dev is None: |
1381 |
raise errors.BlockDeviceError("Block device '%s' is not set up" % |
1382 |
str(os_device))
|
1383 |
real_os_dev.Open() |
1384 |
|
1385 |
real_swap_dev = _RecursiveFindBD(swap_device) |
1386 |
if real_swap_dev is None: |
1387 |
raise errors.BlockDeviceError("Block device '%s' is not set up" % |
1388 |
str(swap_device))
|
1389 |
real_swap_dev.Open() |
1390 |
|
1391 |
logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
|
1392 |
instance.name, int(time.time()))
|
1393 |
if not os.path.exists(constants.LOG_OS_DIR): |
1394 |
os.mkdir(constants.LOG_OS_DIR, 0750)
|
1395 |
|
1396 |
destcmd = utils.BuildShellCmd('cat %s', src_image)
|
1397 |
remotecmd = _GetSshRunner().BuildCmd(src_node, constants.GANETI_RUNAS, |
1398 |
destcmd) |
1399 |
|
1400 |
comprcmd = "gunzip"
|
1401 |
impcmd = utils.BuildShellCmd("(cd %s; %s -i %s -b %s -s %s &>%s)",
|
1402 |
inst_os.path, import_script, instance.name, |
1403 |
real_os_dev.dev_path, real_swap_dev.dev_path, |
1404 |
logfile) |
1405 |
|
1406 |
command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
|
1407 |
|
1408 |
result = utils.RunCmd(command) |
1409 |
|
1410 |
if result.failed:
|
1411 |
logging.error("os import command '%s' returned error: %s"
|
1412 |
" output: %s", command, result.fail_reason, result.output)
|
1413 |
return False |
1414 |
|
1415 |
return True |
1416 |
|
1417 |
|
1418 |
def ListExports(): |
1419 |
"""Return a list of exports currently available on this machine.
|
1420 |
|
1421 |
"""
|
1422 |
if os.path.isdir(constants.EXPORT_DIR):
|
1423 |
return utils.ListVisibleFiles(constants.EXPORT_DIR)
|
1424 |
else:
|
1425 |
return []
|
1426 |
|
1427 |
|
1428 |
def RemoveExport(export): |
1429 |
"""Remove an existing export from the node.
|
1430 |
|
1431 |
Args:
|
1432 |
export: the name of the export to remove
|
1433 |
|
1434 |
Returns:
|
1435 |
False in case of error, True otherwise.
|
1436 |
|
1437 |
"""
|
1438 |
target = os.path.join(constants.EXPORT_DIR, export) |
1439 |
|
1440 |
shutil.rmtree(target) |
1441 |
# TODO: catch some of the relevant exceptions and provide a pretty
|
1442 |
# error message if rmtree fails.
|
1443 |
|
1444 |
return True |
1445 |
|
1446 |
|
1447 |
def RenameBlockDevices(devlist): |
1448 |
"""Rename a list of block devices.
|
1449 |
|
1450 |
The devlist argument is a list of tuples (disk, new_logical,
|
1451 |
new_physical). The return value will be a combined boolean result
|
1452 |
(True only if all renames succeeded).
|
1453 |
|
1454 |
"""
|
1455 |
result = True
|
1456 |
for disk, unique_id in devlist: |
1457 |
dev = _RecursiveFindBD(disk) |
1458 |
if dev is None: |
1459 |
result = False
|
1460 |
continue
|
1461 |
try:
|
1462 |
old_rpath = dev.dev_path |
1463 |
dev.Rename(unique_id) |
1464 |
new_rpath = dev.dev_path |
1465 |
if old_rpath != new_rpath:
|
1466 |
DevCacheManager.RemoveCache(old_rpath) |
1467 |
# FIXME: we should add the new cache information here, like:
|
1468 |
# DevCacheManager.UpdateCache(new_rpath, owner, ...)
|
1469 |
# but we don't have the owner here - maybe parse from existing
|
1470 |
# cache? for now, we only lose lvm data when we rename, which
|
1471 |
# is less critical than DRBD or MD
|
1472 |
except errors.BlockDeviceError, err:
|
1473 |
logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
|
1474 |
result = False
|
1475 |
return result
|
1476 |
|
1477 |
|
1478 |
def _TransformFileStorageDir(file_storage_dir): |
1479 |
"""Checks whether given file_storage_dir is valid.
|
1480 |
|
1481 |
Checks wheter the given file_storage_dir is within the cluster-wide
|
1482 |
default file_storage_dir stored in SimpleStore. Only paths under that
|
1483 |
directory are allowed.
|
1484 |
|
1485 |
Args:
|
1486 |
file_storage_dir: string with path
|
1487 |
|
1488 |
Returns:
|
1489 |
normalized file_storage_dir (string) if valid, None otherwise
|
1490 |
|
1491 |
"""
|
1492 |
file_storage_dir = os.path.normpath(file_storage_dir) |
1493 |
base_file_storage_dir = ssconf.SimpleStore().GetFileStorageDir() |
1494 |
if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) == |
1495 |
base_file_storage_dir): |
1496 |
logging.error("file storage directory '%s' is not under base file"
|
1497 |
" storage directory '%s'",
|
1498 |
file_storage_dir, base_file_storage_dir) |
1499 |
return None |
1500 |
return file_storage_dir
|
1501 |
|
1502 |
|
1503 |
def CreateFileStorageDir(file_storage_dir): |
1504 |
"""Create file storage directory.
|
1505 |
|
1506 |
Args:
|
1507 |
file_storage_dir: string containing the path
|
1508 |
|
1509 |
Returns:
|
1510 |
tuple with first element a boolean indicating wheter dir
|
1511 |
creation was successful or not
|
1512 |
|
1513 |
"""
|
1514 |
file_storage_dir = _TransformFileStorageDir(file_storage_dir) |
1515 |
result = True,
|
1516 |
if not file_storage_dir: |
1517 |
result = False,
|
1518 |
else:
|
1519 |
if os.path.exists(file_storage_dir):
|
1520 |
if not os.path.isdir(file_storage_dir): |
1521 |
logging.error("'%s' is not a directory", file_storage_dir)
|
1522 |
result = False,
|
1523 |
else:
|
1524 |
try:
|
1525 |
os.makedirs(file_storage_dir, 0750)
|
1526 |
except OSError, err: |
1527 |
logging.error("Cannot create file storage directory '%s': %s",
|
1528 |
file_storage_dir, err) |
1529 |
result = False,
|
1530 |
return result
|
1531 |
|
1532 |
|
1533 |
def RemoveFileStorageDir(file_storage_dir): |
1534 |
"""Remove file storage directory.
|
1535 |
|
1536 |
Remove it only if it's empty. If not log an error and return.
|
1537 |
|
1538 |
Args:
|
1539 |
file_storage_dir: string containing the path
|
1540 |
|
1541 |
Returns:
|
1542 |
tuple with first element a boolean indicating wheter dir
|
1543 |
removal was successful or not
|
1544 |
|
1545 |
"""
|
1546 |
file_storage_dir = _TransformFileStorageDir(file_storage_dir) |
1547 |
result = True,
|
1548 |
if not file_storage_dir: |
1549 |
result = False,
|
1550 |
else:
|
1551 |
if os.path.exists(file_storage_dir):
|
1552 |
if not os.path.isdir(file_storage_dir): |
1553 |
logging.error("'%s' is not a directory", file_storage_dir)
|
1554 |
result = False,
|
1555 |
# deletes dir only if empty, otherwise we want to return False
|
1556 |
try:
|
1557 |
os.rmdir(file_storage_dir) |
1558 |
except OSError, err: |
1559 |
logging.exception("Cannot remove file storage directory '%s'",
|
1560 |
file_storage_dir) |
1561 |
result = False,
|
1562 |
return result
|
1563 |
|
1564 |
|
1565 |
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir): |
1566 |
"""Rename the file storage directory.
|
1567 |
|
1568 |
Args:
|
1569 |
old_file_storage_dir: string containing the old path
|
1570 |
new_file_storage_dir: string containing the new path
|
1571 |
|
1572 |
Returns:
|
1573 |
tuple with first element a boolean indicating wheter dir
|
1574 |
rename was successful or not
|
1575 |
|
1576 |
"""
|
1577 |
old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir) |
1578 |
new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir) |
1579 |
result = True,
|
1580 |
if not old_file_storage_dir or not new_file_storage_dir: |
1581 |
result = False,
|
1582 |
else:
|
1583 |
if not os.path.exists(new_file_storage_dir): |
1584 |
if os.path.isdir(old_file_storage_dir):
|
1585 |
try:
|
1586 |
os.rename(old_file_storage_dir, new_file_storage_dir) |
1587 |
except OSError, err: |
1588 |
logging.exception("Cannot rename '%s' to '%s'",
|
1589 |
old_file_storage_dir, new_file_storage_dir) |
1590 |
result = False,
|
1591 |
else:
|
1592 |
logging.error("'%s' is not a directory", old_file_storage_dir)
|
1593 |
result = False,
|
1594 |
else:
|
1595 |
if os.path.exists(old_file_storage_dir):
|
1596 |
logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
|
1597 |
old_file_storage_dir, new_file_storage_dir) |
1598 |
result = False,
|
1599 |
return result
|
1600 |
|
1601 |
|
1602 |
def CloseBlockDevices(disks): |
1603 |
"""Closes the given block devices.
|
1604 |
|
1605 |
This means they will be switched to secondary mode (in case of DRBD).
|
1606 |
|
1607 |
"""
|
1608 |
bdevs = [] |
1609 |
for cf in disks: |
1610 |
rd = _RecursiveFindBD(cf) |
1611 |
if rd is None: |
1612 |
return (False, "Can't find device %s" % cf) |
1613 |
bdevs.append(rd) |
1614 |
|
1615 |
msg = [] |
1616 |
for rd in bdevs: |
1617 |
try:
|
1618 |
rd.Close() |
1619 |
except errors.BlockDeviceError, err:
|
1620 |
msg.append(str(err))
|
1621 |
if msg:
|
1622 |
return (False, "Can't make devices secondary: %s" % ",".join(msg)) |
1623 |
else:
|
1624 |
return (True, "All devices secondary") |
1625 |
|
1626 |
|
1627 |
class HooksRunner(object): |
1628 |
"""Hook runner.
|
1629 |
|
1630 |
This class is instantiated on the node side (ganeti-noded) and not on
|
1631 |
the master side.
|
1632 |
|
1633 |
"""
|
1634 |
RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
|
1635 |
|
1636 |
def __init__(self, hooks_base_dir=None): |
1637 |
"""Constructor for hooks runner.
|
1638 |
|
1639 |
Args:
|
1640 |
- hooks_base_dir: if not None, this overrides the
|
1641 |
constants.HOOKS_BASE_DIR (useful for unittests)
|
1642 |
|
1643 |
"""
|
1644 |
if hooks_base_dir is None: |
1645 |
hooks_base_dir = constants.HOOKS_BASE_DIR |
1646 |
self._BASE_DIR = hooks_base_dir
|
1647 |
|
1648 |
@staticmethod
|
1649 |
def ExecHook(script, env): |
1650 |
"""Exec one hook script.
|
1651 |
|
1652 |
Args:
|
1653 |
- script: the full path to the script
|
1654 |
- env: the environment with which to exec the script
|
1655 |
|
1656 |
"""
|
1657 |
# exec the process using subprocess and log the output
|
1658 |
fdstdin = None
|
1659 |
try:
|
1660 |
fdstdin = open("/dev/null", "r") |
1661 |
child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE, |
1662 |
stderr=subprocess.STDOUT, close_fds=True,
|
1663 |
shell=False, cwd="/", env=env) |
1664 |
output = ""
|
1665 |
try:
|
1666 |
output = child.stdout.read(4096)
|
1667 |
child.stdout.close() |
1668 |
except EnvironmentError, err: |
1669 |
output += "Hook script error: %s" % str(err) |
1670 |
|
1671 |
while True: |
1672 |
try:
|
1673 |
result = child.wait() |
1674 |
break
|
1675 |
except EnvironmentError, err: |
1676 |
if err.errno == errno.EINTR:
|
1677 |
continue
|
1678 |
raise
|
1679 |
finally:
|
1680 |
# try not to leak fds
|
1681 |
for fd in (fdstdin, ): |
1682 |
if fd is not None: |
1683 |
try:
|
1684 |
fd.close() |
1685 |
except EnvironmentError, err: |
1686 |
# just log the error
|
1687 |
#logging.exception("Error while closing fd %s", fd)
|
1688 |
pass
|
1689 |
|
1690 |
return result == 0, output |
1691 |
|
1692 |
def RunHooks(self, hpath, phase, env): |
1693 |
"""Run the scripts in the hooks directory.
|
1694 |
|
1695 |
This method will not be usually overriden by child opcodes.
|
1696 |
|
1697 |
"""
|
1698 |
if phase == constants.HOOKS_PHASE_PRE:
|
1699 |
suffix = "pre"
|
1700 |
elif phase == constants.HOOKS_PHASE_POST:
|
1701 |
suffix = "post"
|
1702 |
else:
|
1703 |
raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase) |
1704 |
rr = [] |
1705 |
|
1706 |
subdir = "%s-%s.d" % (hpath, suffix)
|
1707 |
dir_name = "%s/%s" % (self._BASE_DIR, subdir) |
1708 |
try:
|
1709 |
dir_contents = utils.ListVisibleFiles(dir_name) |
1710 |
except OSError, err: |
1711 |
# must log
|
1712 |
return rr
|
1713 |
|
1714 |
# we use the standard python sort order,
|
1715 |
# so 00name is the recommended naming scheme
|
1716 |
dir_contents.sort() |
1717 |
for relname in dir_contents: |
1718 |
fname = os.path.join(dir_name, relname) |
1719 |
if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and |
1720 |
self.RE_MASK.match(relname) is not None): |
1721 |
rrval = constants.HKR_SKIP |
1722 |
output = ""
|
1723 |
else:
|
1724 |
result, output = self.ExecHook(fname, env)
|
1725 |
if not result: |
1726 |
rrval = constants.HKR_FAIL |
1727 |
else:
|
1728 |
rrval = constants.HKR_SUCCESS |
1729 |
rr.append(("%s/%s" % (subdir, relname), rrval, output))
|
1730 |
|
1731 |
return rr
|
1732 |
|
1733 |
|
1734 |
class IAllocatorRunner(object): |
1735 |
"""IAllocator runner.
|
1736 |
|
1737 |
This class is instantiated on the node side (ganeti-noded) and not on
|
1738 |
the master side.
|
1739 |
|
1740 |
"""
|
1741 |
def Run(self, name, idata): |
1742 |
"""Run an iallocator script.
|
1743 |
|
1744 |
Return value: tuple of:
|
1745 |
- run status (one of the IARUN_ constants)
|
1746 |
- stdout
|
1747 |
- stderr
|
1748 |
- fail reason (as from utils.RunResult)
|
1749 |
|
1750 |
"""
|
1751 |
alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH, |
1752 |
os.path.isfile) |
1753 |
if alloc_script is None: |
1754 |
return (constants.IARUN_NOTFOUND, None, None, None) |
1755 |
|
1756 |
fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
|
1757 |
try:
|
1758 |
os.write(fd, idata) |
1759 |
os.close(fd) |
1760 |
result = utils.RunCmd([alloc_script, fin_name]) |
1761 |
if result.failed:
|
1762 |
return (constants.IARUN_FAILURE, result.stdout, result.stderr,
|
1763 |
result.fail_reason) |
1764 |
finally:
|
1765 |
os.unlink(fin_name) |
1766 |
|
1767 |
return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None) |
1768 |
|
1769 |
|
1770 |
class DevCacheManager(object): |
1771 |
"""Simple class for managing a cache of block device information.
|
1772 |
|
1773 |
"""
|
1774 |
_DEV_PREFIX = "/dev/"
|
1775 |
_ROOT_DIR = constants.BDEV_CACHE_DIR |
1776 |
|
1777 |
@classmethod
|
1778 |
def _ConvertPath(cls, dev_path): |
1779 |
"""Converts a /dev/name path to the cache file name.
|
1780 |
|
1781 |
This replaces slashes with underscores and strips the /dev
|
1782 |
prefix. It then returns the full path to the cache file
|
1783 |
|
1784 |
"""
|
1785 |
if dev_path.startswith(cls._DEV_PREFIX):
|
1786 |
dev_path = dev_path[len(cls._DEV_PREFIX):]
|
1787 |
dev_path = dev_path.replace("/", "_") |
1788 |
fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
|
1789 |
return fpath
|
1790 |
|
1791 |
@classmethod
|
1792 |
def UpdateCache(cls, dev_path, owner, on_primary, iv_name): |
1793 |
"""Updates the cache information for a given device.
|
1794 |
|
1795 |
"""
|
1796 |
if dev_path is None: |
1797 |
logging.error("DevCacheManager.UpdateCache got a None dev_path")
|
1798 |
return
|
1799 |
fpath = cls._ConvertPath(dev_path) |
1800 |
if on_primary:
|
1801 |
state = "primary"
|
1802 |
else:
|
1803 |
state = "secondary"
|
1804 |
if iv_name is None: |
1805 |
iv_name = "not_visible"
|
1806 |
fdata = "%s %s %s\n" % (str(owner), state, iv_name) |
1807 |
try:
|
1808 |
utils.WriteFile(fpath, data=fdata) |
1809 |
except EnvironmentError, err: |
1810 |
logging.exception("Can't update bdev cache for %s", dev_path)
|
1811 |
|
1812 |
@classmethod
|
1813 |
def RemoveCache(cls, dev_path): |
1814 |
"""Remove data for a dev_path.
|
1815 |
|
1816 |
"""
|
1817 |
if dev_path is None: |
1818 |
logging.error("DevCacheManager.RemoveCache got a None dev_path")
|
1819 |
return
|
1820 |
fpath = cls._ConvertPath(dev_path) |
1821 |
try:
|
1822 |
utils.RemoveFile(fpath) |
1823 |
except EnvironmentError, err: |
1824 |
logging.exception("Can't update bdev cache for %s", dev_path)
|