X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=tools.py;h=199d799def48edac009eae07c93f02133f922676;hb=755be0fb0adb034ea9879167ed30256d3d19eca6;hp=941838bd41529c5a69cded3d3edd309beb2ab670;hpb=0ade807b91a8c84098406935d41d749f33efbe9d;p=nodemanager.git diff --git a/tools.py b/tools.py index 941838b..199d799 100644 --- a/tools.py +++ b/tools.py @@ -18,18 +18,21 @@ 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) - if dev_hwaddr == hwaddr: return dev - return None + import sioc + devs = sioc.gifconf() + for dev in devs: + dev_hwaddr = sioc.gifhwaddr(dev) + if dev_hwaddr == hwaddr: return dev + return None def as_daemon_thread(run): """Call function with no arguments in its own thread.""" @@ -51,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 @@ -109,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