X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=tools.py;h=199d799def48edac009eae07c93f02133f922676;hb=3f14798d46e163a1955cedc7a833619cf717d4fb;hp=bc4b49e84fd21896b1659e9a76041510e0fa16ca;hpb=b4a5dd8ec367eca5f04b7cf4b8daa31458e6da6c;p=nodemanager.git diff --git a/tools.py b/tools.py index bc4b49e..199d799 100644 --- a/tools.py +++ b/tools.py @@ -8,12 +8,32 @@ import tempfile import threading import fcntl import commands - import logger - PID_FILE = '/var/run/nm.pid' +def get_default_if(): + interface = get_if_from_hwaddr(get_hwaddr_from_plnode()) + if not interface: interface = "eth0" + return interface + +def get_hwaddr_from_plnode(): + 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 + def as_daemon_thread(run): """Call function with no arguments in its own thread.""" thr = threading.Thread(target=run) @@ -34,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 @@ -92,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