X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=tools.py;h=199d799def48edac009eae07c93f02133f922676;hb=755be0fb0adb034ea9879167ed30256d3d19eca6;hp=f3e67e1595a185c907799d93f1f851526b084282;hpb=4293a16c3c0badbc130c3af6b62c3681a5eeb9d6;p=nodemanager.git diff --git a/tools.py b/tools.py index f3e67e1..199d799 100644 --- a/tools.py +++ b/tools.py @@ -9,10 +9,6 @@ import threading import fcntl import commands import logger -try: - import sioc -except: - pass PID_FILE = '/var/run/nm.pid' @@ -22,12 +18,16 @@ def get_default_if(): return interface def get_hwaddr_from_plnode(): - for line in open("/usr/boot/plnode.txt", 'r').readlines(): - if line.startswith("NET_DEVICE"): - return line.split("=")[1].strip().strip('"') + try: + for line in open("/usr/boot/plnode.txt", 'r').readlines(): + if line.startswith("NET_DEVICE"): + return line.split("=")[1].strip().strip('"') + except: + pass return None def get_if_from_hwaddr(hwaddr): + import sioc devs = sioc.gifconf() for dev in devs: dev_hwaddr = sioc.gifhwaddr(dev) @@ -54,7 +54,7 @@ def daemon(): os.setsid() if os.fork() != 0: os._exit(0) os.chdir('/') - os.umask(0) + os.umask(0022) devnull = os.open(os.devnull, os.O_RDWR) os.dup2(devnull, 0) # xxx fixme - this is just to make sure that nothing gets stupidly lost - should use devnull @@ -112,6 +112,36 @@ def write_temp_file(do_write, mode=None, uidgid=None): finally: f.close() return temporary_filename +# replace a target file with a new contents - checks for changes +# can handle chmod if requested +# can also remove resulting file if contents are void, if requested +# performs atomically: +# writes in a tmp file, which is then renamed (from sliverauth originally) +# returns True if a change occurred, or the file is deleted +def replace_file_with_string (target, new_contents, chmod=None, remove_if_empty=False): + try: + current=file(target).read() + except: + current="" + if current==new_contents: + # if turns out to be an empty string, and remove_if_empty is set, + # then make sure to trash the file if it exists + if remove_if_empty and not new_contents and os.path.isfile(target): + logger.verbose("tools.replace_file_with_string: removing file %s"%target) + try: os.unlink(target) + finally: return True + return False + # overwrite target file: create a temp in the same directory + path=os.path.dirname(target) or '.' + fd, name = tempfile.mkstemp('','repl',path) + os.write(fd,new_contents) + os.close(fd) + if os.path.exists(target): + os.unlink(target) + os.rename(name,target) + if chmod: os.chmod(target,chmod) + return True + # utilities functions to get (cached) information from the node # get node_id from /etc/planetlab/node_id and cache it