root / lib / backend.py @ 880478f8
History | View | Annotate | Download (36.2 kB)
1 |
#!/usr/bin/python
|
---|---|
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 tempfile |
30 |
import stat |
31 |
import errno |
32 |
import re |
33 |
import subprocess |
34 |
|
35 |
from ganeti import logger |
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 ListConfigFiles(): |
47 |
"""Return a list of the config files present on the local node.
|
48 |
"""
|
49 |
|
50 |
configfiles = [] |
51 |
|
52 |
for testfile in constants.MASTER_CONFIGFILES: |
53 |
if os.path.exists(testfile):
|
54 |
configfiles.append(testfile) |
55 |
|
56 |
for testfile in constants.NODE_CONFIGFILES: |
57 |
if os.path.exists(testfile):
|
58 |
configfiles.append(testfile) |
59 |
|
60 |
return configfiles
|
61 |
|
62 |
|
63 |
def StartMaster(): |
64 |
"""Activate local node as master node.
|
65 |
|
66 |
There are two needed steps for this:
|
67 |
- run the master script
|
68 |
- register the cron script
|
69 |
|
70 |
"""
|
71 |
result = utils.RunCmd([constants.MASTER_SCRIPT, "-d", "start"]) |
72 |
|
73 |
if result.failed:
|
74 |
logger.Error("could not activate cluster interface with command %s,"
|
75 |
" error: '%s'" % (result.cmd, result.output))
|
76 |
return False |
77 |
|
78 |
utils.RemoveFile(constants.MASTER_CRON_LINK) |
79 |
os.symlink(constants.MASTER_CRON_FILE, constants.MASTER_CRON_LINK) |
80 |
return True |
81 |
|
82 |
|
83 |
def StopMaster(): |
84 |
"""Deactivate this node as master.
|
85 |
|
86 |
This does two things:
|
87 |
- run the master stop script
|
88 |
- remove link to master cron script.
|
89 |
|
90 |
"""
|
91 |
result = utils.RunCmd([constants.MASTER_SCRIPT, "-d", "stop"]) |
92 |
|
93 |
if result.failed:
|
94 |
logger.Error("could not deactivate cluster interface with command %s,"
|
95 |
" error: '%s'" % (result.cmd, result.output))
|
96 |
return False |
97 |
|
98 |
utils.RemoveFile(constants.MASTER_CRON_LINK) |
99 |
|
100 |
return True |
101 |
|
102 |
|
103 |
def AddNode(dsa, dsapub, rsa, rsapub, ssh, sshpub): |
104 |
""" adds the node to the cluster
|
105 |
- updates the hostkey
|
106 |
- adds the ssh-key
|
107 |
- sets the node id
|
108 |
- sets the node status to installed
|
109 |
"""
|
110 |
|
111 |
f = open("/etc/ssh/ssh_host_rsa_key", 'w') |
112 |
f.write(rsa) |
113 |
f.close() |
114 |
|
115 |
f = open("/etc/ssh/ssh_host_rsa_key.pub", 'w') |
116 |
f.write(rsapub) |
117 |
f.close() |
118 |
|
119 |
f = open("/etc/ssh/ssh_host_dsa_key", 'w') |
120 |
f.write(dsa) |
121 |
f.close() |
122 |
|
123 |
f = open("/etc/ssh/ssh_host_dsa_key.pub", 'w') |
124 |
f.write(dsapub) |
125 |
f.close() |
126 |
|
127 |
if not os.path.isdir("/root/.ssh"): |
128 |
os.mkdir("/root/.ssh")
|
129 |
|
130 |
f = open("/root/.ssh/id_dsa", 'w') |
131 |
f.write(ssh) |
132 |
f.close() |
133 |
|
134 |
f = open("/root/.ssh/id_dsa.pub", 'w') |
135 |
f.write(sshpub) |
136 |
f.close() |
137 |
|
138 |
f = open('/root/.ssh/id_dsa.pub', 'r') |
139 |
try:
|
140 |
utils.AddAuthorizedKey('/root/.ssh/authorized_keys', f.read(8192)) |
141 |
finally:
|
142 |
f.close() |
143 |
|
144 |
utils.RunCmd(["/etc/init.d/ssh", "restart"]) |
145 |
|
146 |
utils.RemoveFile("/root/.ssh/known_hosts")
|
147 |
return True |
148 |
|
149 |
|
150 |
def LeaveCluster(): |
151 |
"""Cleans up the current node and prepares it to be removed from the cluster.
|
152 |
|
153 |
"""
|
154 |
if os.path.exists(constants.DATA_DIR):
|
155 |
for dirpath, dirnames, filenames in os.walk(constants.DATA_DIR): |
156 |
if dirpath == constants.DATA_DIR:
|
157 |
for i in filenames: |
158 |
os.unlink(os.path.join(dirpath, i)) |
159 |
|
160 |
f = open('/root/.ssh/id_dsa.pub', 'r') |
161 |
try:
|
162 |
utils.RemoveAuthorizedKey('/root/.ssh/authorized_keys', f.read(8192)) |
163 |
finally:
|
164 |
f.close() |
165 |
|
166 |
utils.RemoveFile('/root/.ssh/id_dsa')
|
167 |
utils.RemoveFile('/root/.ssh/id_dsa.pub')
|
168 |
|
169 |
|
170 |
def GetNodeInfo(vgname): |
171 |
""" gives back a hash with different informations
|
172 |
about the node
|
173 |
|
174 |
Returns:
|
175 |
{ 'vg_size' : xxx, 'vg_free' : xxx, 'memory_domain0': xxx,
|
176 |
'memory_free' : xxx, 'memory_total' : xxx }
|
177 |
where
|
178 |
vg_size is the size of the configured volume group in MiB
|
179 |
vg_free is the free size of the volume group in MiB
|
180 |
memory_dom0 is the memory allocated for domain0 in MiB
|
181 |
memory_free is the currently available (free) ram in MiB
|
182 |
memory_total is the total number of ram in MiB
|
183 |
"""
|
184 |
|
185 |
outputarray = {} |
186 |
vginfo = _GetVGInfo(vgname) |
187 |
outputarray['vg_size'] = vginfo['vg_size'] |
188 |
outputarray['vg_free'] = vginfo['vg_free'] |
189 |
|
190 |
hyper = hypervisor.GetHypervisor() |
191 |
hyp_info = hyper.GetNodeInfo() |
192 |
if hyp_info is not None: |
193 |
outputarray.update(hyp_info) |
194 |
|
195 |
return outputarray
|
196 |
|
197 |
|
198 |
def VerifyNode(what): |
199 |
"""Verify the status of the local node.
|
200 |
|
201 |
Args:
|
202 |
what - a dictionary of things to check:
|
203 |
'filelist' : list of files for which to compute checksums
|
204 |
'nodelist' : list of nodes we should check communication with
|
205 |
'hypervisor': run the hypervisor-specific verify
|
206 |
|
207 |
Requested files on local node are checksummed and the result returned.
|
208 |
|
209 |
The nodelist is traversed, with the following checks being made
|
210 |
for each node:
|
211 |
- known_hosts key correct
|
212 |
- correct resolving of node name (target node returns its own hostname
|
213 |
by ssh-execution of 'hostname', result compared against name in list.
|
214 |
|
215 |
"""
|
216 |
|
217 |
result = {} |
218 |
|
219 |
if 'hypervisor' in what: |
220 |
result['hypervisor'] = hypervisor.GetHypervisor().Verify()
|
221 |
|
222 |
if 'filelist' in what: |
223 |
result['filelist'] = utils.FingerprintFiles(what['filelist']) |
224 |
|
225 |
if 'nodelist' in what: |
226 |
result['nodelist'] = {}
|
227 |
for node in what['nodelist']: |
228 |
success, message = ssh.VerifyNodeHostname(node) |
229 |
if not success: |
230 |
result['nodelist'][node] = message
|
231 |
return result
|
232 |
|
233 |
|
234 |
def GetVolumeList(vg_name): |
235 |
"""Compute list of logical volumes and their size.
|
236 |
|
237 |
Returns:
|
238 |
dictionary of all partions (key) with their size:
|
239 |
test1: 20.06MiB
|
240 |
|
241 |
"""
|
242 |
result = utils.RunCmd(["lvs", "--noheadings", "--units=m", |
243 |
"-oname,size", vg_name])
|
244 |
if result.failed:
|
245 |
logger.Error("Failed to list logical volumes, lvs output: %s" %
|
246 |
result.output) |
247 |
return {}
|
248 |
|
249 |
lvlist = [line.split() for line in result.output.splitlines()] |
250 |
return dict(lvlist) |
251 |
|
252 |
|
253 |
def ListVolumeGroups(): |
254 |
"""List the volume groups and their size
|
255 |
|
256 |
Returns:
|
257 |
Dictionary with keys volume name and values the size of the volume
|
258 |
|
259 |
"""
|
260 |
return utils.ListVolumeGroups()
|
261 |
|
262 |
|
263 |
def BridgesExist(bridges_list): |
264 |
"""Check if a list of bridges exist on the current node
|
265 |
|
266 |
Returns:
|
267 |
True if all of them exist, false otherwise
|
268 |
|
269 |
"""
|
270 |
for bridge in bridges_list: |
271 |
if not utils.BridgeExists(bridge): |
272 |
return False |
273 |
|
274 |
return True |
275 |
|
276 |
|
277 |
def GetInstanceList(): |
278 |
""" provides a list of instances
|
279 |
|
280 |
Returns:
|
281 |
A list of all running instances on the current node
|
282 |
- instance1.example.com
|
283 |
- instance2.example.com
|
284 |
"""
|
285 |
|
286 |
try:
|
287 |
names = hypervisor.GetHypervisor().ListInstances() |
288 |
except errors.HypervisorError, err:
|
289 |
logger.Error("error enumerating instances: %s" % str(err)) |
290 |
raise
|
291 |
|
292 |
return names
|
293 |
|
294 |
|
295 |
def GetInstanceInfo(instance): |
296 |
""" gives back the informations about an instance
|
297 |
as a dictonary
|
298 |
|
299 |
Args:
|
300 |
instance: name of the instance (ex. instance1.example.com)
|
301 |
|
302 |
Returns:
|
303 |
{ 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
|
304 |
where
|
305 |
memory: memory size of instance (int)
|
306 |
state: xen state of instance (string)
|
307 |
time: cpu time of instance (float)
|
308 |
"""
|
309 |
|
310 |
output = {} |
311 |
|
312 |
iinfo = hypervisor.GetHypervisor().GetInstanceInfo(instance) |
313 |
if iinfo is not None: |
314 |
output['memory'] = iinfo[2] |
315 |
output['state'] = iinfo[4] |
316 |
output['time'] = iinfo[5] |
317 |
|
318 |
return output
|
319 |
|
320 |
|
321 |
def GetAllInstancesInfo(): |
322 |
"""Gather data about all instances.
|
323 |
|
324 |
This is the equivalent of `GetInstanceInfo()`, except that it
|
325 |
computes data for all instances at once, thus being faster if one
|
326 |
needs data about more than one instance.
|
327 |
|
328 |
Returns: a dictionary of dictionaries, keys being the instance name,
|
329 |
and with values:
|
330 |
{ 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
|
331 |
where
|
332 |
memory: memory size of instance (int)
|
333 |
state: xen state of instance (string)
|
334 |
time: cpu time of instance (float)
|
335 |
vcpus: the number of cpus
|
336 |
"""
|
337 |
|
338 |
output = {} |
339 |
|
340 |
iinfo = hypervisor.GetHypervisor().GetAllInstancesInfo() |
341 |
if iinfo:
|
342 |
for name, id, memory, vcpus, state, times in iinfo: |
343 |
output[name] = { |
344 |
'memory': memory,
|
345 |
'vcpus': vcpus,
|
346 |
'state': state,
|
347 |
'time': times,
|
348 |
} |
349 |
|
350 |
return output
|
351 |
|
352 |
|
353 |
def AddOSToInstance(instance, os_disk, swap_disk): |
354 |
"""Add an os to an instance.
|
355 |
|
356 |
Args:
|
357 |
instance: the instance object
|
358 |
os_disk: the instance-visible name of the os device
|
359 |
swap_disk: the instance-visible name of the swap device
|
360 |
|
361 |
"""
|
362 |
inst_os = OSFromDisk(instance.os) |
363 |
|
364 |
create_script = inst_os.create_script |
365 |
|
366 |
for os_device in instance.disks: |
367 |
if os_device.iv_name == os_disk:
|
368 |
break
|
369 |
else:
|
370 |
logger.Error("Can't find this device-visible name '%s'" % os_disk)
|
371 |
return False |
372 |
|
373 |
for swap_device in instance.disks: |
374 |
if swap_device.iv_name == swap_disk:
|
375 |
break
|
376 |
else:
|
377 |
logger.Error("Can't find this device-visible name '%s'" % swap_disk)
|
378 |
return False |
379 |
|
380 |
real_os_dev = _RecursiveFindBD(os_device) |
381 |
if real_os_dev is None: |
382 |
raise errors.BlockDeviceError("Block device '%s' is not set up" % |
383 |
str(os_device))
|
384 |
real_os_dev.Open() |
385 |
|
386 |
real_swap_dev = _RecursiveFindBD(swap_device) |
387 |
if real_swap_dev is None: |
388 |
raise errors.BlockDeviceError("Block device '%s' is not set up" % |
389 |
str(swap_device))
|
390 |
real_swap_dev.Open() |
391 |
|
392 |
logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
|
393 |
instance.name, int(time.time()))
|
394 |
if not os.path.exists(constants.LOG_OS_DIR): |
395 |
os.mkdir(constants.LOG_OS_DIR, 0750)
|
396 |
|
397 |
command = utils.BuildShellCmd("cd %s; %s -i %s -b %s -s %s &>%s",
|
398 |
inst_os.path, create_script, instance.name, |
399 |
real_os_dev.dev_path, real_swap_dev.dev_path, |
400 |
logfile) |
401 |
|
402 |
result = utils.RunCmd(command) |
403 |
|
404 |
if result.failed:
|
405 |
logger.Error("os create command '%s' returned error: %s"
|
406 |
" output: %s" %
|
407 |
(command, result.fail_reason, result.output)) |
408 |
return False |
409 |
|
410 |
return True |
411 |
|
412 |
|
413 |
def _GetVGInfo(vg_name): |
414 |
"""Get informations about the volume group.
|
415 |
|
416 |
Args:
|
417 |
vg_name: the volume group
|
418 |
|
419 |
Returns:
|
420 |
{ 'vg_size' : xxx, 'vg_free' : xxx, 'pv_count' : xxx }
|
421 |
where
|
422 |
vg_size is the total size of the volume group in MiB
|
423 |
vg_free is the free size of the volume group in MiB
|
424 |
pv_count are the number of physical disks in that vg
|
425 |
|
426 |
"""
|
427 |
retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings", |
428 |
"--nosuffix", "--units=m", "--separator=:", vg_name]) |
429 |
|
430 |
if retval.failed:
|
431 |
errmsg = "volume group %s not present" % vg_name
|
432 |
logger.Error(errmsg) |
433 |
raise errors.LVMError(errmsg)
|
434 |
valarr = retval.stdout.strip().split(':')
|
435 |
retdic = { |
436 |
"vg_size": int(round(float(valarr[0]), 0)), |
437 |
"vg_free": int(round(float(valarr[1]), 0)), |
438 |
"pv_count": int(valarr[2]), |
439 |
} |
440 |
return retdic
|
441 |
|
442 |
|
443 |
def _GatherBlockDevs(instance): |
444 |
"""Set up an instance's block device(s).
|
445 |
|
446 |
This is run on the primary node at instance startup. The block
|
447 |
devices must be already assembled.
|
448 |
|
449 |
"""
|
450 |
block_devices = [] |
451 |
for disk in instance.disks: |
452 |
device = _RecursiveFindBD(disk) |
453 |
if device is None: |
454 |
raise errors.BlockDeviceError("Block device '%s' is not set up." % |
455 |
str(disk))
|
456 |
device.Open() |
457 |
block_devices.append((disk, device)) |
458 |
return block_devices
|
459 |
|
460 |
|
461 |
def StartInstance(instance, extra_args): |
462 |
"""Start an instance.
|
463 |
|
464 |
Args:
|
465 |
instance - name of instance to start.
|
466 |
"""
|
467 |
|
468 |
running_instances = GetInstanceList() |
469 |
|
470 |
if instance.name in running_instances: |
471 |
return True |
472 |
|
473 |
block_devices = _GatherBlockDevs(instance) |
474 |
hyper = hypervisor.GetHypervisor() |
475 |
|
476 |
try:
|
477 |
hyper.StartInstance(instance, block_devices, extra_args) |
478 |
except errors.HypervisorError, err:
|
479 |
logger.Error("Failed to start instance: %s" % err)
|
480 |
return False |
481 |
|
482 |
return True |
483 |
|
484 |
|
485 |
def ShutdownInstance(instance): |
486 |
"""Shut an instance down.
|
487 |
|
488 |
Args:
|
489 |
instance - name of instance to shutdown.
|
490 |
"""
|
491 |
|
492 |
running_instances = GetInstanceList() |
493 |
|
494 |
if instance.name not in running_instances: |
495 |
return True |
496 |
|
497 |
hyper = hypervisor.GetHypervisor() |
498 |
try:
|
499 |
hyper.StopInstance(instance) |
500 |
except errors.HypervisorError, err:
|
501 |
logger.Error("Failed to stop instance: %s" % err)
|
502 |
return False |
503 |
|
504 |
# test every 10secs for 2min
|
505 |
shutdown_ok = False
|
506 |
|
507 |
time.sleep(1)
|
508 |
for dummy in range(11): |
509 |
if instance.name not in GetInstanceList(): |
510 |
break
|
511 |
time.sleep(10)
|
512 |
else:
|
513 |
# the shutdown did not succeed
|
514 |
logger.Error("shutdown of '%s' unsuccessful, using destroy" % instance)
|
515 |
|
516 |
try:
|
517 |
hyper.StopInstance(instance, force=True)
|
518 |
except errors.HypervisorError, err:
|
519 |
logger.Error("Failed to stop instance: %s" % err)
|
520 |
return False |
521 |
|
522 |
time.sleep(1)
|
523 |
if instance.name in GetInstanceList(): |
524 |
logger.Error("could not shutdown instance '%s' even by destroy")
|
525 |
return False |
526 |
|
527 |
return True |
528 |
|
529 |
|
530 |
def CreateBlockDevice(disk, size, on_primary): |
531 |
"""Creates a block device for an instance.
|
532 |
|
533 |
Args:
|
534 |
bdev: a ganeti.objects.Disk object
|
535 |
size: the size of the physical underlying devices
|
536 |
do_open: if the device should be `Assemble()`-d and
|
537 |
`Open()`-ed after creation
|
538 |
|
539 |
Returns:
|
540 |
the new unique_id of the device (this can sometime be
|
541 |
computed only after creation), or None. On secondary nodes,
|
542 |
it's not required to return anything.
|
543 |
|
544 |
"""
|
545 |
clist = [] |
546 |
if disk.children:
|
547 |
for child in disk.children: |
548 |
crdev = _RecursiveAssembleBD(child, on_primary) |
549 |
if on_primary or disk.AssembleOnSecondary(): |
550 |
# we need the children open in case the device itself has to
|
551 |
# be assembled
|
552 |
crdev.Open() |
553 |
else:
|
554 |
crdev.Close() |
555 |
clist.append(crdev) |
556 |
try:
|
557 |
device = bdev.FindDevice(disk.dev_type, disk.physical_id, clist) |
558 |
if device is not None: |
559 |
logger.Info("removing existing device %s" % disk)
|
560 |
device.Remove() |
561 |
except errors.BlockDeviceError, err:
|
562 |
pass
|
563 |
|
564 |
device = bdev.Create(disk.dev_type, disk.physical_id, |
565 |
clist, size) |
566 |
if device is None: |
567 |
raise ValueError("Can't create child device for %s, %s" % |
568 |
(disk, size)) |
569 |
if on_primary or disk.AssembleOnSecondary(): |
570 |
device.Assemble() |
571 |
device.SetSyncSpeed(30*1024) |
572 |
if on_primary or disk.OpenOnSecondary(): |
573 |
device.Open(force=True)
|
574 |
physical_id = device.unique_id |
575 |
return physical_id
|
576 |
|
577 |
|
578 |
def RemoveBlockDevice(disk): |
579 |
"""Remove a block device.
|
580 |
|
581 |
This is intended to be called recursively.
|
582 |
|
583 |
"""
|
584 |
try:
|
585 |
# since we are removing the device, allow a partial match
|
586 |
# this allows removal of broken mirrors
|
587 |
rdev = _RecursiveFindBD(disk, allow_partial=True)
|
588 |
except errors.BlockDeviceError, err:
|
589 |
# probably can't attach
|
590 |
logger.Info("Can't attach to device %s in remove" % disk)
|
591 |
rdev = None
|
592 |
if rdev is not None: |
593 |
result = rdev.Remove() |
594 |
else:
|
595 |
result = True
|
596 |
if disk.children:
|
597 |
for child in disk.children: |
598 |
result = result and RemoveBlockDevice(child)
|
599 |
return result
|
600 |
|
601 |
|
602 |
def _RecursiveAssembleBD(disk, as_primary): |
603 |
"""Activate a block device for an instance.
|
604 |
|
605 |
This is run on the primary and secondary nodes for an instance.
|
606 |
|
607 |
This function is called recursively.
|
608 |
|
609 |
Args:
|
610 |
disk: a objects.Disk object
|
611 |
as_primary: if we should make the block device read/write
|
612 |
|
613 |
Returns:
|
614 |
the assembled device or None (in case no device was assembled)
|
615 |
|
616 |
If the assembly is not successful, an exception is raised.
|
617 |
|
618 |
"""
|
619 |
children = [] |
620 |
if disk.children:
|
621 |
for chld_disk in disk.children: |
622 |
children.append(_RecursiveAssembleBD(chld_disk, as_primary)) |
623 |
|
624 |
if as_primary or disk.AssembleOnSecondary(): |
625 |
r_dev = bdev.AttachOrAssemble(disk.dev_type, disk.physical_id, children) |
626 |
r_dev.SetSyncSpeed(30*1024) |
627 |
result = r_dev |
628 |
if as_primary or disk.OpenOnSecondary(): |
629 |
r_dev.Open() |
630 |
else:
|
631 |
r_dev.Close() |
632 |
else:
|
633 |
result = True
|
634 |
return result
|
635 |
|
636 |
|
637 |
def AssembleBlockDevice(disk, as_primary): |
638 |
"""Activate a block device for an instance.
|
639 |
|
640 |
This is a wrapper over _RecursiveAssembleBD.
|
641 |
|
642 |
Returns:
|
643 |
a /dev path for primary nodes
|
644 |
True for secondary nodes
|
645 |
|
646 |
"""
|
647 |
result = _RecursiveAssembleBD(disk, as_primary) |
648 |
if isinstance(result, bdev.BlockDev): |
649 |
result = result.dev_path |
650 |
return result
|
651 |
|
652 |
|
653 |
def ShutdownBlockDevice(disk): |
654 |
"""Shut down a block device.
|
655 |
|
656 |
First, if the device is assembled (can `Attach()`), then the device
|
657 |
is shutdown. Then the children of the device are shutdown.
|
658 |
|
659 |
This function is called recursively. Note that we don't cache the
|
660 |
children or such, as oppossed to assemble, shutdown of different
|
661 |
devices doesn't require that the upper device was active.
|
662 |
|
663 |
"""
|
664 |
r_dev = _RecursiveFindBD(disk) |
665 |
if r_dev is not None: |
666 |
result = r_dev.Shutdown() |
667 |
else:
|
668 |
result = True
|
669 |
if disk.children:
|
670 |
for child in disk.children: |
671 |
result = result and ShutdownBlockDevice(child)
|
672 |
return result
|
673 |
|
674 |
|
675 |
def MirrorAddChild(md_cdev, new_cdev): |
676 |
"""Extend an MD raid1 array.
|
677 |
|
678 |
"""
|
679 |
md_bdev = _RecursiveFindBD(md_cdev, allow_partial=True)
|
680 |
if md_bdev is None: |
681 |
logger.Error("Can't find md device")
|
682 |
return False |
683 |
new_bdev = _RecursiveFindBD(new_cdev) |
684 |
if new_bdev is None: |
685 |
logger.Error("Can't find new device to add")
|
686 |
return False |
687 |
new_bdev.Open() |
688 |
md_bdev.AddChild(new_bdev) |
689 |
return True |
690 |
|
691 |
|
692 |
def MirrorRemoveChild(md_cdev, new_cdev): |
693 |
"""Reduce an MD raid1 array.
|
694 |
|
695 |
"""
|
696 |
md_bdev = _RecursiveFindBD(md_cdev) |
697 |
if md_bdev is None: |
698 |
return False |
699 |
new_bdev = _RecursiveFindBD(new_cdev) |
700 |
if new_bdev is None: |
701 |
return False |
702 |
new_bdev.Open() |
703 |
md_bdev.RemoveChild(new_bdev.dev_path) |
704 |
return True |
705 |
|
706 |
|
707 |
def GetMirrorStatus(disks): |
708 |
"""Get the mirroring status of a list of devices.
|
709 |
|
710 |
Args:
|
711 |
disks: list of `objects.Disk`
|
712 |
|
713 |
Returns:
|
714 |
list of (mirror_done, estimated_time) tuples, which
|
715 |
are the result of bdev.BlockDevice.CombinedSyncStatus()
|
716 |
|
717 |
"""
|
718 |
stats = [] |
719 |
for dsk in disks: |
720 |
rbd = _RecursiveFindBD(dsk) |
721 |
if rbd is None: |
722 |
raise errors.BlockDeviceError, "Can't find device %s" % str(dsk) |
723 |
stats.append(rbd.CombinedSyncStatus()) |
724 |
return stats
|
725 |
|
726 |
|
727 |
def _RecursiveFindBD(disk, allow_partial=False): |
728 |
"""Check if a device is activated.
|
729 |
|
730 |
If so, return informations about the real device.
|
731 |
|
732 |
Args:
|
733 |
disk: the objects.Disk instance
|
734 |
allow_partial: don't abort the find if a child of the
|
735 |
device can't be found; this is intended to be
|
736 |
used when repairing mirrors
|
737 |
|
738 |
Returns:
|
739 |
None if the device can't be found
|
740 |
otherwise the device instance
|
741 |
|
742 |
"""
|
743 |
children = [] |
744 |
if disk.children:
|
745 |
for chdisk in disk.children: |
746 |
children.append(_RecursiveFindBD(chdisk)) |
747 |
|
748 |
return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
|
749 |
|
750 |
|
751 |
def FindBlockDevice(disk): |
752 |
"""Check if a device is activated.
|
753 |
|
754 |
If so, return informations about the real device.
|
755 |
|
756 |
Args:
|
757 |
disk: the objects.Disk instance
|
758 |
Returns:
|
759 |
None if the device can't be found
|
760 |
(device_path, major, minor, sync_percent, estimated_time, is_degraded)
|
761 |
|
762 |
"""
|
763 |
rbd = _RecursiveFindBD(disk) |
764 |
if rbd is None: |
765 |
return rbd
|
766 |
sync_p, est_t, is_degr = rbd.GetSyncStatus() |
767 |
return rbd.dev_path, rbd.major, rbd.minor, sync_p, est_t, is_degr
|
768 |
|
769 |
|
770 |
def UploadFile(file_name, data, mode, uid, gid, atime, mtime): |
771 |
"""Write a file to the filesystem.
|
772 |
|
773 |
This allows the master to overwrite(!) a file. It will only perform
|
774 |
the operation if the file belongs to a list of configuration files.
|
775 |
|
776 |
"""
|
777 |
if not os.path.isabs(file_name): |
778 |
logger.Error("Filename passed to UploadFile is not absolute: '%s'" %
|
779 |
file_name) |
780 |
return False |
781 |
|
782 |
allowed_files = [constants.CLUSTER_CONF_FILE, "/etc/hosts",
|
783 |
"/etc/ssh/ssh_known_hosts"]
|
784 |
allowed_files.extend(ssconf.SimpleStore().GetFileList()) |
785 |
if file_name not in allowed_files: |
786 |
logger.Error("Filename passed to UploadFile not in allowed"
|
787 |
" upload targets: '%s'" % file_name)
|
788 |
return False |
789 |
|
790 |
dir_name, small_name = os.path.split(file_name) |
791 |
fd, new_name = tempfile.mkstemp('.new', small_name, dir_name)
|
792 |
# here we need to make sure we remove the temp file, if any error
|
793 |
# leaves it in place
|
794 |
try:
|
795 |
os.chown(new_name, uid, gid) |
796 |
os.chmod(new_name, mode) |
797 |
os.write(fd, data) |
798 |
os.fsync(fd) |
799 |
os.utime(new_name, (atime, mtime)) |
800 |
os.rename(new_name, file_name) |
801 |
finally:
|
802 |
os.close(fd) |
803 |
utils.RemoveFile(new_name) |
804 |
return True |
805 |
|
806 |
def _ErrnoOrStr(err): |
807 |
"""Format an EnvironmentError exception.
|
808 |
|
809 |
If the `err` argument has an errno attribute, it will be looked up
|
810 |
and converted into a textual EXXXX description. Otherwise the string
|
811 |
representation of the error will be returned.
|
812 |
|
813 |
"""
|
814 |
if hasattr(err, 'errno'): |
815 |
detail = errno.errorcode[err.errno] |
816 |
else:
|
817 |
detail = str(err)
|
818 |
return detail
|
819 |
|
820 |
|
821 |
def _OSOndiskVersion(name, os_dir=None): |
822 |
"""Compute and return the api version of a given OS.
|
823 |
|
824 |
This function will try to read the api version of the os given by
|
825 |
the 'name' parameter. By default, it wil use the constants.OS_DIR
|
826 |
as top-level directory for OSes, but this can be overriden by the
|
827 |
use of the os_dir parameter. Return value will be either an
|
828 |
integer denoting the version or None in the case when this is not
|
829 |
a valid OS name.
|
830 |
|
831 |
"""
|
832 |
if os_dir is None: |
833 |
os_dir = os.path.sep.join([constants.OS_DIR, name]) |
834 |
|
835 |
api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
|
836 |
|
837 |
try:
|
838 |
st = os.stat(api_file) |
839 |
except EnvironmentError, err: |
840 |
raise errors.InvalidOS, (name, "'ganeti_api_version' file not" |
841 |
" found (%s)" % _ErrnoOrStr(err))
|
842 |
|
843 |
if not stat.S_ISREG(stat.S_IFMT(st.st_mode)): |
844 |
raise errors.InvalidOS, (name, "'ganeti_api_version' file is not" |
845 |
" a regular file")
|
846 |
|
847 |
try:
|
848 |
f = open(api_file)
|
849 |
try:
|
850 |
api_version = f.read(256)
|
851 |
finally:
|
852 |
f.close() |
853 |
except EnvironmentError, err: |
854 |
raise errors.InvalidOS, (name, "error while reading the" |
855 |
" API version (%s)" % _ErrnoOrStr(err))
|
856 |
|
857 |
api_version = api_version.strip() |
858 |
try:
|
859 |
api_version = int(api_version)
|
860 |
except (TypeError, ValueError), err: |
861 |
raise errors.InvalidOS, (name, "API version is not integer (%s)" % |
862 |
str(err))
|
863 |
|
864 |
return api_version
|
865 |
|
866 |
def DiagnoseOS(top_dir=None): |
867 |
"""Compute the validity for all OSes.
|
868 |
|
869 |
For each name in the give top_dir parameter (if not given, defaults
|
870 |
to constants.OS_DIR), it will return an object. If this is a valid
|
871 |
os, the object will be an instance of the object.OS class. If not,
|
872 |
it will be an instance of errors.InvalidOS and this signifies that
|
873 |
this name does not correspond to a valid OS.
|
874 |
|
875 |
Returns:
|
876 |
list of objects
|
877 |
|
878 |
"""
|
879 |
if top_dir is None: |
880 |
top_dir = constants.OS_DIR |
881 |
|
882 |
try:
|
883 |
f_names = os.listdir(top_dir) |
884 |
except EnvironmentError, err: |
885 |
logger.Error("Can't list the OS directory: %s" % str(err)) |
886 |
return False |
887 |
result = [] |
888 |
for name in f_names: |
889 |
try:
|
890 |
os_inst = OSFromDisk(name, os.path.sep.join([top_dir, name])) |
891 |
result.append(os_inst) |
892 |
except errors.InvalidOS, err:
|
893 |
result.append(err) |
894 |
|
895 |
return result
|
896 |
|
897 |
|
898 |
def OSFromDisk(name, os_dir=None): |
899 |
"""Create an OS instance from disk.
|
900 |
|
901 |
This function will return an OS instance if the given name is a
|
902 |
valid OS name. Otherwise, it will raise an appropriate
|
903 |
`errors.InvalidOS` exception, detailing why this is not a valid
|
904 |
OS.
|
905 |
|
906 |
"""
|
907 |
if os_dir is None: |
908 |
os_dir = os.path.sep.join([constants.OS_DIR, name]) |
909 |
|
910 |
api_version = _OSOndiskVersion(name, os_dir) |
911 |
|
912 |
if api_version != constants.OS_API_VERSION:
|
913 |
raise errors.InvalidOS, (name, "API version mismatch (found %s want %s)" |
914 |
% (api_version, constants.OS_API_VERSION)) |
915 |
|
916 |
# OS Scripts dictionary, we will populate it with the actual script names
|
917 |
os_scripts = {'create': '', 'export': '', 'import': ''} |
918 |
|
919 |
for script in os_scripts: |
920 |
os_scripts[script] = os.path.sep.join([os_dir, script]) |
921 |
|
922 |
try:
|
923 |
st = os.stat(os_scripts[script]) |
924 |
except EnvironmentError, err: |
925 |
raise errors.InvalidOS, (name, "'%s' script missing (%s)" % |
926 |
(script, _ErrnoOrStr(err))) |
927 |
|
928 |
if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
|
929 |
raise errors.InvalidOS, (name, "'%s' script not executable" % script) |
930 |
|
931 |
if not stat.S_ISREG(stat.S_IFMT(st.st_mode)): |
932 |
raise errors.InvalidOS, (name, "'%s' is not a regular file" % script) |
933 |
|
934 |
|
935 |
return objects.OS(name=name, path=os_dir,
|
936 |
create_script=os_scripts['create'],
|
937 |
export_script=os_scripts['export'],
|
938 |
import_script=os_scripts['import'],
|
939 |
api_version=api_version) |
940 |
|
941 |
|
942 |
def SnapshotBlockDevice(disk): |
943 |
"""Create a snapshot copy of a block device.
|
944 |
|
945 |
This function is called recursively, and the snapshot is actually created
|
946 |
just for the leaf lvm backend device.
|
947 |
|
948 |
Args:
|
949 |
disk: the disk to be snapshotted
|
950 |
|
951 |
Returns:
|
952 |
a config entry for the actual lvm device snapshotted.
|
953 |
"""
|
954 |
|
955 |
if disk.children:
|
956 |
if len(disk.children) == 1: |
957 |
# only one child, let's recurse on it
|
958 |
return SnapshotBlockDevice(disk.children[0]) |
959 |
else:
|
960 |
# more than one child, choose one that matches
|
961 |
for child in disk.children: |
962 |
if child.size == disk.size:
|
963 |
# return implies breaking the loop
|
964 |
return SnapshotBlockDevice(child)
|
965 |
elif disk.dev_type == "lvm": |
966 |
r_dev = _RecursiveFindBD(disk) |
967 |
if r_dev is not None: |
968 |
# let's stay on the safe side and ask for the full size, for now
|
969 |
return r_dev.Snapshot(disk.size)
|
970 |
else:
|
971 |
return None |
972 |
else:
|
973 |
raise errors.ProgrammerError, ("Cannot snapshot non-lvm block device" |
974 |
"'%s' of type '%s'" %
|
975 |
(disk.unique_id, disk.dev_type)) |
976 |
|
977 |
|
978 |
def ExportSnapshot(disk, dest_node, instance): |
979 |
"""Export a block device snapshot to a remote node.
|
980 |
|
981 |
Args:
|
982 |
disk: the snapshot block device
|
983 |
dest_node: the node to send the image to
|
984 |
instance: instance being exported
|
985 |
|
986 |
Returns:
|
987 |
True if successful, False otherwise.
|
988 |
"""
|
989 |
|
990 |
inst_os = OSFromDisk(instance.os) |
991 |
export_script = inst_os.export_script |
992 |
|
993 |
logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
|
994 |
instance.name, int(time.time()))
|
995 |
if not os.path.exists(constants.LOG_OS_DIR): |
996 |
os.mkdir(constants.LOG_OS_DIR, 0750)
|
997 |
|
998 |
real_os_dev = _RecursiveFindBD(disk) |
999 |
if real_os_dev is None: |
1000 |
raise errors.BlockDeviceError("Block device '%s' is not set up" % |
1001 |
str(disk))
|
1002 |
real_os_dev.Open() |
1003 |
|
1004 |
destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
|
1005 |
destfile = disk.physical_id[1]
|
1006 |
|
1007 |
# the target command is built out of three individual commands,
|
1008 |
# which are joined by pipes; we check each individual command for
|
1009 |
# valid parameters
|
1010 |
|
1011 |
expcmd = utils.BuildShellCmd("cd %s; %s -i %s -b %s 2>%s", inst_os.path,
|
1012 |
export_script, instance.name, |
1013 |
real_os_dev.dev_path, logfile) |
1014 |
|
1015 |
comprcmd = "gzip"
|
1016 |
|
1017 |
remotecmd = utils.BuildShellCmd("ssh -q -oStrictHostKeyChecking=yes"
|
1018 |
" -oBatchMode=yes -oEscapeChar=none"
|
1019 |
" %s 'mkdir -p %s; cat > %s/%s'",
|
1020 |
dest_node, destdir, destdir, destfile) |
1021 |
|
1022 |
# all commands have been checked, so we're safe to combine them
|
1023 |
command = '|'.join([expcmd, comprcmd, remotecmd])
|
1024 |
|
1025 |
result = utils.RunCmd(command) |
1026 |
|
1027 |
if result.failed:
|
1028 |
logger.Error("os snapshot export command '%s' returned error: %s"
|
1029 |
" output: %s" %
|
1030 |
(command, result.fail_reason, result.output)) |
1031 |
return False |
1032 |
|
1033 |
return True |
1034 |
|
1035 |
|
1036 |
def FinalizeExport(instance, snap_disks): |
1037 |
"""Write out the export configuration information.
|
1038 |
|
1039 |
Args:
|
1040 |
instance: instance configuration
|
1041 |
snap_disks: snapshot block devices
|
1042 |
|
1043 |
Returns:
|
1044 |
False in case of error, True otherwise.
|
1045 |
"""
|
1046 |
|
1047 |
destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
|
1048 |
finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name) |
1049 |
|
1050 |
config = objects.SerializableConfigParser() |
1051 |
|
1052 |
config.add_section(constants.INISECT_EXP) |
1053 |
config.set(constants.INISECT_EXP, 'version', '0') |
1054 |
config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time())) |
1055 |
config.set(constants.INISECT_EXP, 'source', instance.primary_node)
|
1056 |
config.set(constants.INISECT_EXP, 'os', instance.os)
|
1057 |
config.set(constants.INISECT_EXP, 'compression', 'gzip') |
1058 |
|
1059 |
config.add_section(constants.INISECT_INS) |
1060 |
config.set(constants.INISECT_INS, 'name', instance.name)
|
1061 |
config.set(constants.INISECT_INS, 'memory', '%d' % instance.memory) |
1062 |
config.set(constants.INISECT_INS, 'vcpus', '%d' % instance.vcpus) |
1063 |
config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
|
1064 |
for nic_count, nic in enumerate(instance.nics): |
1065 |
config.set(constants.INISECT_INS, 'nic%d_mac' %
|
1066 |
nic_count, '%s' % nic.mac)
|
1067 |
config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip) |
1068 |
# TODO: redundant: on load can read nics until it doesn't exist
|
1069 |
config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_count) |
1070 |
|
1071 |
for disk_count, disk in enumerate(snap_disks): |
1072 |
config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
|
1073 |
('%s' % disk.iv_name))
|
1074 |
config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
|
1075 |
('%s' % disk.physical_id[1])) |
1076 |
config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
|
1077 |
('%d' % disk.size))
|
1078 |
config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_count) |
1079 |
|
1080 |
cff = os.path.join(destdir, constants.EXPORT_CONF_FILE) |
1081 |
cfo = open(cff, 'w') |
1082 |
try:
|
1083 |
config.write(cfo) |
1084 |
finally:
|
1085 |
cfo.close() |
1086 |
|
1087 |
shutil.rmtree(finaldestdir, True)
|
1088 |
shutil.move(destdir, finaldestdir) |
1089 |
|
1090 |
return True |
1091 |
|
1092 |
|
1093 |
def ExportInfo(dest): |
1094 |
"""Get export configuration information.
|
1095 |
|
1096 |
Args:
|
1097 |
dest: directory containing the export
|
1098 |
|
1099 |
Returns:
|
1100 |
A serializable config file containing the export info.
|
1101 |
|
1102 |
"""
|
1103 |
|
1104 |
cff = os.path.join(dest, constants.EXPORT_CONF_FILE) |
1105 |
|
1106 |
config = objects.SerializableConfigParser() |
1107 |
config.read(cff) |
1108 |
|
1109 |
if (not config.has_section(constants.INISECT_EXP) or |
1110 |
not config.has_section(constants.INISECT_INS)):
|
1111 |
return None |
1112 |
|
1113 |
return config
|
1114 |
|
1115 |
|
1116 |
def ImportOSIntoInstance(instance, os_disk, swap_disk, src_node, src_image): |
1117 |
"""Import an os image into an instance.
|
1118 |
|
1119 |
Args:
|
1120 |
instance: the instance object
|
1121 |
os_disk: the instance-visible name of the os device
|
1122 |
swap_disk: the instance-visible name of the swap device
|
1123 |
src_node: node holding the source image
|
1124 |
src_image: path to the source image on src_node
|
1125 |
|
1126 |
Returns:
|
1127 |
False in case of error, True otherwise.
|
1128 |
|
1129 |
"""
|
1130 |
|
1131 |
inst_os = OSFromDisk(instance.os) |
1132 |
import_script = inst_os.import_script |
1133 |
|
1134 |
for os_device in instance.disks: |
1135 |
if os_device.iv_name == os_disk:
|
1136 |
break
|
1137 |
else:
|
1138 |
logger.Error("Can't find this device-visible name '%s'" % os_disk)
|
1139 |
return False |
1140 |
|
1141 |
for swap_device in instance.disks: |
1142 |
if swap_device.iv_name == swap_disk:
|
1143 |
break
|
1144 |
else:
|
1145 |
logger.Error("Can't find this device-visible name '%s'" % swap_disk)
|
1146 |
return False |
1147 |
|
1148 |
real_os_dev = _RecursiveFindBD(os_device) |
1149 |
if real_os_dev is None: |
1150 |
raise errors.BlockDeviceError, ("Block device '%s' is not set up" % |
1151 |
str(os_device))
|
1152 |
real_os_dev.Open() |
1153 |
|
1154 |
real_swap_dev = _RecursiveFindBD(swap_device) |
1155 |
if real_swap_dev is None: |
1156 |
raise errors.BlockDeviceError, ("Block device '%s' is not set up" % |
1157 |
str(swap_device))
|
1158 |
real_swap_dev.Open() |
1159 |
|
1160 |
logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
|
1161 |
instance.name, int(time.time()))
|
1162 |
if not os.path.exists(constants.LOG_OS_DIR): |
1163 |
os.mkdir(constants.LOG_OS_DIR, 0750)
|
1164 |
|
1165 |
remotecmd = utils.BuildShellCmd("ssh -q -oStrictHostKeyChecking=yes"
|
1166 |
" -oBatchMode=yes -oEscapeChar=none"
|
1167 |
" %s 'cat %s'", src_node, src_image)
|
1168 |
|
1169 |
comprcmd = "gunzip"
|
1170 |
impcmd = utils.BuildShellCmd("(cd %s; %s -i %s -b %s -s %s &>%s)",
|
1171 |
inst_os.path, import_script, instance.name, |
1172 |
real_os_dev.dev_path, real_swap_dev.dev_path, |
1173 |
logfile) |
1174 |
|
1175 |
command = '|'.join([remotecmd, comprcmd, impcmd])
|
1176 |
|
1177 |
result = utils.RunCmd(command) |
1178 |
|
1179 |
if result.failed:
|
1180 |
logger.Error("os import command '%s' returned error: %s"
|
1181 |
" output: %s" %
|
1182 |
(command, result.fail_reason, result.output)) |
1183 |
return False |
1184 |
|
1185 |
return True |
1186 |
|
1187 |
|
1188 |
def ListExports(): |
1189 |
"""Return a list of exports currently available on this machine.
|
1190 |
"""
|
1191 |
if os.path.isdir(constants.EXPORT_DIR):
|
1192 |
return os.listdir(constants.EXPORT_DIR)
|
1193 |
else:
|
1194 |
return []
|
1195 |
|
1196 |
|
1197 |
def RemoveExport(export): |
1198 |
"""Remove an existing export from the node.
|
1199 |
|
1200 |
Args:
|
1201 |
export: the name of the export to remove
|
1202 |
|
1203 |
Returns:
|
1204 |
False in case of error, True otherwise.
|
1205 |
"""
|
1206 |
|
1207 |
target = os.path.join(constants.EXPORT_DIR, export) |
1208 |
|
1209 |
shutil.rmtree(target) |
1210 |
# TODO: catch some of the relevant exceptions and provide a pretty
|
1211 |
# error message if rmtree fails.
|
1212 |
|
1213 |
return True |
1214 |
|
1215 |
|
1216 |
class HooksRunner(object): |
1217 |
"""Hook runner.
|
1218 |
|
1219 |
This class is instantiated on the node side (ganeti-noded) and not on
|
1220 |
the master side.
|
1221 |
|
1222 |
"""
|
1223 |
RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
|
1224 |
|
1225 |
def __init__(self, hooks_base_dir=None): |
1226 |
"""Constructor for hooks runner.
|
1227 |
|
1228 |
Args:
|
1229 |
- hooks_base_dir: if not None, this overrides the
|
1230 |
constants.HOOKS_BASE_DIR (useful for unittests)
|
1231 |
- logs_base_dir: if not None, this overrides the
|
1232 |
constants.LOG_HOOKS_DIR (useful for unittests)
|
1233 |
- logging: enable or disable logging of script output
|
1234 |
|
1235 |
"""
|
1236 |
if hooks_base_dir is None: |
1237 |
hooks_base_dir = constants.HOOKS_BASE_DIR |
1238 |
self._BASE_DIR = hooks_base_dir
|
1239 |
|
1240 |
@staticmethod
|
1241 |
def ExecHook(script, env): |
1242 |
"""Exec one hook script.
|
1243 |
|
1244 |
Args:
|
1245 |
- phase: the phase
|
1246 |
- script: the full path to the script
|
1247 |
- env: the environment with which to exec the script
|
1248 |
|
1249 |
"""
|
1250 |
# exec the process using subprocess and log the output
|
1251 |
fdstdin = None
|
1252 |
try:
|
1253 |
fdstdin = open("/dev/null", "r") |
1254 |
child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE, |
1255 |
stderr=subprocess.STDOUT, close_fds=True,
|
1256 |
shell=False, cwd="/",env=env) |
1257 |
output = ""
|
1258 |
try:
|
1259 |
output = child.stdout.read(4096)
|
1260 |
child.stdout.close() |
1261 |
except EnvironmentError, err: |
1262 |
output += "Hook script error: %s" % str(err) |
1263 |
|
1264 |
while True: |
1265 |
try:
|
1266 |
result = child.wait() |
1267 |
break
|
1268 |
except EnvironmentError, err: |
1269 |
if err.errno == errno.EINTR:
|
1270 |
continue
|
1271 |
raise
|
1272 |
finally:
|
1273 |
# try not to leak fds
|
1274 |
for fd in (fdstdin, ): |
1275 |
if fd is not None: |
1276 |
try:
|
1277 |
fd.close() |
1278 |
except EnvironmentError, err: |
1279 |
# just log the error
|
1280 |
#logger.Error("While closing fd %s: %s" % (fd, err))
|
1281 |
pass
|
1282 |
|
1283 |
return result == 0, output |
1284 |
|
1285 |
def RunHooks(self, hpath, phase, env): |
1286 |
"""Run the scripts in the hooks directory.
|
1287 |
|
1288 |
This method will not be usually overriden by child opcodes.
|
1289 |
|
1290 |
"""
|
1291 |
if phase == constants.HOOKS_PHASE_PRE:
|
1292 |
suffix = "pre"
|
1293 |
elif phase == constants.HOOKS_PHASE_POST:
|
1294 |
suffix = "post"
|
1295 |
else:
|
1296 |
raise errors.ProgrammerError, ("Unknown hooks phase: '%s'" % phase) |
1297 |
rr = [] |
1298 |
|
1299 |
subdir = "%s-%s.d" % (hpath, suffix)
|
1300 |
dir_name = "%s/%s" % (self._BASE_DIR, subdir) |
1301 |
try:
|
1302 |
dir_contents = os.listdir(dir_name) |
1303 |
except OSError, err: |
1304 |
# must log
|
1305 |
return rr
|
1306 |
|
1307 |
# we use the standard python sort order,
|
1308 |
# so 00name is the recommended naming scheme
|
1309 |
dir_contents.sort() |
1310 |
for relname in dir_contents: |
1311 |
fname = os.path.join(dir_name, relname) |
1312 |
if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and |
1313 |
self.RE_MASK.match(relname) is not None): |
1314 |
rrval = constants.HKR_SKIP |
1315 |
output = ""
|
1316 |
else:
|
1317 |
result, output = self.ExecHook(fname, env)
|
1318 |
if not result: |
1319 |
rrval = constants.HKR_FAIL |
1320 |
else:
|
1321 |
rrval = constants.HKR_SUCCESS |
1322 |
rr.append(("%s/%s" % (subdir, relname), rrval, output))
|
1323 |
|
1324 |
return rr
|