X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=tools.py;h=9590b57fb1ef5a0a6c1abc763ba9268952787e61;hb=ab555c3e4f9b7a3f55b5c15239467f8f4e1732ef;hp=bd911e8fa317ee8ad3a18f0e1ceca7561d6da8d4;hpb=daea12f08fc20740d05dcde1cd9512b8b308b54c;p=nodemanager.git diff --git a/tools.py b/tools.py index bd911e8..9590b57 100644 --- a/tools.py +++ b/tools.py @@ -8,11 +8,8 @@ import tempfile import threading import fcntl import commands -import sioc - import logger - PID_FILE = '/var/run/nm.pid' def get_default_if(): @@ -21,12 +18,16 @@ def get_default_if(): return interface def get_hwaddr_from_plnode(): - for line in open("/usr/share/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) @@ -111,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