def main():
  """
  <Purpose>
    Kills all the seattle programs that are running.

  <Arguments>
    None.
  
  <Exceptions>
    None.

  <Side Effects>
    Kills all the seattle programs that are running.

  <Returns>
    None.
  """
  for lockname in locklist:
    lockstate = runonce.getprocesslock(lockname)
    # If lockstate is a process pid, then we need to terminate it. Otherwise,
    # that lock is not being held by a program that needs to be terminated. 
    if not lockstate == True and not lockstate == False:
      # We got the pid, we can stop the process
      harshexit.portablekill(lockstate)

      # Now acquire the lock for ourselves, looping until we
      # actually get it.
      retrievedlock = runonce.getprocesslock(lockname)
      while retrievedlock != True:
        harshexit.portablekill(retrievedlock)
        retrievedlock = runonce.getprocesslock(lockname)
示例#2
0
def main():
    """
  <Purpose>
    Kills all the seattle programs that are running.

  <Arguments>
    None.
  
  <Exceptions>
    None.

  <Side Effects>
    Kills all the seattle programs that are running.

  <Returns>
    None.
  """
    for lockname in locklist:
        lockstate = runonce.getprocesslock(lockname)
        # If lockstate is a process pid, then we need to terminate it. Otherwise,
        # that lock is not being held by a program that needs to be terminated.
        if not lockstate == True and not lockstate == False:
            # We got the pid, we can stop the process
            harshexit.portablekill(lockstate)

            # Now acquire the lock for ourselves, looping until we
            # actually get it.
            retrievedlock = runonce.getprocesslock(lockname)
            while retrievedlock != True:
                harshexit.portablekill(retrievedlock)
                retrievedlock = runonce.getprocesslock(lockname)
示例#3
0
文件: nmmain.py 项目: Ashmita89/attic
def main():

  global configuration

  if not FOREGROUND:
    # Background ourselves.
    daemon.daemonize()

  # ensure that only one instance is running at a time...
  gotlock = runonce.getprocesslock("seattlenodemanager")
  if gotlock == True:
    # I got the lock.   All is well...
    pass
  else:
    if gotlock:
      servicelogger.log("[ERROR]:Another node manager process (pid: " + str(gotlock) + 
          ") is running")
    else:
      servicelogger.log("[ERROR]:Another node manager process is running")
    return

  
  # I'll grab the necessary information first...
  servicelogger.log("[INFO]:Loading config")
  # BUG: Do this better?   Is this the right way to engineer this?
  configuration = persist.restore_object("nodeman.cfg")
  
  # Armon: initialize the network restrictions
  initialize_ip_interface_restrictions(configuration)
  
  
  
  # ZACK BOKA: For Linux and Darwin systems, check to make sure that the new
  #            seattle crontab entry has been installed in the crontab.
  #            Do this here because the "nodeman.cfg" needs to have been read
  #            into configuration via the persist module.
  if nonportable.ostype == 'Linux' or nonportable.ostype == 'Darwin':
    if 'crontab_updated_for_2009_installer' not in configuration or \
          configuration['crontab_updated_for_2009_installer'] == False:
      try:
        import update_crontab_entry
        modified_crontab_entry = \
            update_crontab_entry.modify_seattle_crontab_entry()
        # If updating the seattle crontab entry succeeded, then update the
        # 'crontab_updated_for_2009_installer' so the nodemanager no longer
        # tries to update the crontab entry when it starts up.
        if modified_crontab_entry:
          configuration['crontab_updated_for_2009_installer'] = True
          persist.commit_object(configuration,"nodeman.cfg")

      except Exception,e:
        exception_traceback_string = traceback.format_exc()
        servicelogger.log("[ERROR]: The following error occured when " \
                            + "modifying the crontab for the new 2009 " \
                            + "seattle crontab entry: " \
                            + exception_traceback_string)
def init():
  """
  <Purpose>
    This method is here to do a runthrough of trying to update.  The idea is
    that if there is going to be a fatal error, we want to die immediately
    rather than later.  This way, when a node is updating to a flawed version,
    the old one won't die until we know the new one is working.  Also goes
    through the magic explained in the comment block above.

  <Arguments>
    None

  <Exceptions>
    See fresh_software_updater and software_updater_start.

  <Side Effects>
    If we can't get the lock, we will exit.
    We will hold the softwareupdater.new lock while trying to start, but if
    all goes well, we will release that lock and aquire the 
    softwareupdater.old lock.

  <Returns>
    None
  """
  # Note: be careful about making this init() method take too long. If it takes
  # longer to complete than the amount of time that restart_software_updater()
  # waits, then the new software updater will never be left running. Keep in
  # mind very slow systems and adjust the wait time in restart_software_updater()
  # if needed.
  
  gotlock = runonce.getprocesslock("softwareupdater.new")
  if gotlock == True:
    # I got the lock.   All is well...
    pass
  else:
    # didn't get the lock, and we like to be real quiet, so lets 
    # exit quietly
    print 'Exit Queitly, no Lock'
    sys.exit(55)

  # Close stdin because we don't read from stdin at all. We leave stdout and stderr
  # open because we haven't done anything to make sure that output to those (such as
  # uncaught python exceptions) go somewhere else useful.
  sys.stdin.close()

  # don't hang if the socket is slow (in some ways, this doesn't always work)
  # BUG: http://mail.python.org/pipermail/python-list/2008-January/471845.html
  socket.setdefaulttimeout(10)

  # time to handle startup (with respect to other copies of the updater
  if len(sys.argv) == 1:
    # I was called with no arguments, must be a fresh start...
    fresh_software_updater()
  else:
    # the first argument is our mutex number...
    software_updater_start(sys.argv[1])
示例#5
0
def init():
  """
  <Purpose>
    This method is here to do a runthrough of trying to update.  The idea is
    that if there is going to be a fatal error, we want to die immediately
    rather than later.  This way, when a node is updating to a flawed version,
    the old one won't die until we know the new one is working.  Also goes
    through the magic explained in the comment block above.

  <Arguments>
    None

  <Exceptions>
    See fresh_software_updater and software_updater_start.

  <Side Effects>
    If we can't get the lock, we will exit.
    We will hold the softwareupdater.new lock while trying to start, but if
    all goes well, we will release that lock and aquire the 
    softwareupdater.old lock.

  <Returns>
    None
  """
  # Note: be careful about making this init() method take too long. If it takes
  # longer to complete than the amount of time that restart_software_updater()
  # waits, then the new software updater will never be left running. Keep in
  # mind very slow systems and adjust the wait time in restart_software_updater()
  # if needed.
  
  gotlock = runonce.getprocesslock("softwareupdater.new")
  if gotlock == True:
    # I got the lock.   All is well...
    pass
  else:
    # didn't get the lock, and we like to be real quiet, so lets 
    # exit quietly
    print 'Exit Queitly, no Lock'
    sys.exit(55)

  # Close stdin because we don't read from stdin at all. We leave stdout and stderr
  # open because we haven't done anything to make sure that output to those (such as
  # uncaught python exceptions) go somewhere else useful.
  sys.stdin.close()

  # don't hang if the socket is slow (in some ways, this doesn't always work)
  # BUG: http://mail.python.org/pipermail/python-list/2008-January/471845.html
  socket.setdefaulttimeout(10)

  # time to handle startup (with respect to other copies of the updater
  if len(sys.argv) == 1:
    # I was called with no arguments, must be a fresh start...
    fresh_software_updater()
  else:
    # the first argument is our mutex number...
    software_updater_start(sys.argv[1])
示例#6
0
 def stop_nm():
   # Stop the NM
   gotlock = runonce.getprocesslock("seattlenodemanager")
   if gotlock == True:
     # No NM running? This is an error
     logstream.write("FAILURE: Successfully acquired the NM process lock! The NM should be running!\n")
   else:
     if gotlock:
       # Kill the NM
       harshexit.portablekill(gotlock)
       # Allow the sockets to cleanup and the locks to be cleaned
       time.sleep(3)
示例#7
0
def main():
  # Give time for any changes in acquiring/relinquishing keys to take effect
  time.sleep(2)
  for lockname in locklist:
    status = runonce.getprocesslock(lockname)
    if status == True:
      print "The lock '" + lockname + "' was not being held."
      runonce.releaseprocesslock(lockname)
    elif status == False:
      print "There was an error getting the lock '" + lockname + "'."
    else:
      print "The lock '" + lockname + "' is currently being used by process pid: " + str(status)
示例#8
0
 def stop_nm():
   # Stop the NM
   gotlock = runonce.getprocesslock("seattlenodemanager")
   if gotlock == True:
     # No NM running? This is an error
     logstream.write("FAILURE: Successfully acquired the NM process lock! The NM should be running!\n")
   else:
     if gotlock:
       # Kill the NM
       harshexit.portablekill(gotlock)
       # Allow the sockets to cleanup and the locks to be cleaned
       time.sleep(3)
示例#9
0
def main():
    # Give time for any changes in acquiring/relinquishing keys to take effect
    time.sleep(2)
    for lockname in locklist:
        status = runonce.getprocesslock(lockname)
        if status == True:
            print "The lock '" + lockname + "' was not being held."
            runonce.releaseprocesslock(lockname)
        elif status == False:
            print "There was an error getting the lock '" + lockname + "'."
        else:
            print "The lock '" + lockname + "' is currently being used by process pid: " + str(
                status)
示例#10
0
def fresh_software_updater():
    """
  <Purpose>
    This function is ment to be called when starting a softwareupdater when no
    other is currently running.  It will clear away any outdated OK or stop
    files, then release the softwareupdater.new lock and acquire the
    softwareupdater.old lock.

  <Arguments>
    None
 
  <Exceptions>
    Possible exception if there is a problem removing the OK/stop files.    

  <Side Effects>
    The softwareupdater.new lock is released.
    The softwareupdater.old lock is acquired.
    All old OK and stop files are removed.

  <Returns>
    None
  """
    # clean all mutex files
    for filename in os.listdir('.'):
        # Remove any outdated stop or OK files...
        if filename.startswith('softwareupdater.OK.') or filename.startswith(
                'softwareupdater.stop.'):
            os.remove(filename)

    # Get the process lock for the main part of the program.
    gotlock = runonce.getprocesslock("softwareupdater.old")
    # Release the lock on the initialization part of the program
    runonce.releaseprocesslock('softwareupdater.new')
    if gotlock == True:
        # I got the lock.   All is well...
        pass
    else:
        if gotlock:
            safe_log(
                "[fresh_software_updater] Another software updater old process (pid: "
                + str(gotlock) + ") is running")
            sys.exit(55)
        else:
            safe_log(
                "[fresh_software_updater] Another software updater old process is running"
            )
            sys.exit(55)
    # Should be ready to go...

    safe_log("[fresh_software_updater] Fresh software updater started.")
def fresh_software_updater():
    """
  <Purpose>
    This function is ment to be called when starting a softwareupdater when no
    other is currently running.  It will clear away any outdated OK or stop
    files, then release the softwareupdater.new lock and acquire the
    softwareupdater.old lock.

  <Arguments>
    None
 
  <Exceptions>
    Possible exception if there is a problem removing the OK/stop files.    

  <Side Effects>
    The softwareupdater.new lock is released.
    The softwareupdater.old lock is acquired.
    All old OK and stop files are removed.

  <Returns>
    None
  """
    # clean all mutex files
    for filename in os.listdir("."):
        # Remove any outdated stop or OK files...
        if filename.startswith("softwareupdater.OK.") or filename.startswith("softwareupdater.stop."):
            os.remove(filename)

    # Get the process lock for the main part of the program.
    gotlock = runonce.getprocesslock("softwareupdater.old")
    # Release the lock on the initialization part of the program
    runonce.releaseprocesslock("softwareupdater.new")
    if gotlock == True:
        # I got the lock.   All is well...
        pass
    else:
        if gotlock:
            safe_log(
                "[fresh_software_updater] Another software updater old process (pid: " + str(gotlock) + ") is running"
            )
            sys.exit(55)
        else:
            safe_log("[fresh_software_updater] Another software updater old process is running")
            sys.exit(55)
    # Should be ready to go...

    safe_log("[fresh_software_updater] Fresh software updater started.")
示例#12
0
def restart_client(filenamelist):
    """
  <Purpose>
    Restarts the node manager.

  <Arguments>
    filenamelist - Currently not used, but is included for possible future use.

  <Exceptions>
    None

  <Side Effects>
    The current node manager is killed, and a new one is started.

  <Returns>
    None.
  """
    # kill nmmain if it is currently running
    retval = runonce.getprocesslock('seattlenodemanager')
    if retval == True:
        safe_log(
            "[restart_client] Obtained the lock 'seattlenodemanager', it wasn't running."
        )
        # I got the lock, it wasn't running...
        # we want to start a new one, so lets release
        runonce.releaseprocesslock('seattlenodemanager')
    elif retval == False:
        # Someone has the lock, but I can't do anything...
        safe_log(
            "[restart_client] The lock 'seattlenodemanager' is held by an unknown process. Will try to start it anyways."
        )
    else:
        safe_log("[restart_client] Stopping the nodemanager.")
        # I know the process ID!   Let's stop the process...
        harshexit.portablekill(retval)

    safe_log("[restart_client] Starting the nodemanager.")

    # run the node manager.   I rely on it to do the smart thing (handle multiple
    # instances, etc.)
    nm_restart_command_args_list = ["python", "nmmain.py"]

    if run_nodemanager_in_foreground:
        nm_restart_command_args_list.append('--foreground')

    junkprocessobject = portable_popen.Popen(nm_restart_command_args_list)
示例#13
0
def main():
    global LOGGING

    if "-v" in sys.argv or "--verbose" in sys.argv:
        LOGGING = True

    usage = """
Lind Fuse File System.

""" + Fuse.fusage

    lind.load_fs()
    
    gotlock = runonce.getprocesslock('lind_fuse')
    if gotlock == True:
      pass
    else:
      if gotlock:
        print "\n\n#########################################################"
        print "[Warning] Another Process (pid: " + str(gotlock) + ") already in use."
        print "#########################################################\n\n"
      else:
        print "[Warning] Another Process is running"

    server = LindFuseFS(version="%prog " + fuse.__version__,
                 usage=usage,
                 dash_s_do='setsingle')

    server.multithreaded = False  # if this is true, better add some locks!

    server.parser.add_option("-v", "--verbose",
                             action="store_true",
                             dest="verbose",
                             default=False,
                             help="print extra information about which system"
                             " calls are being called.")

    server.parser.add_option(mountopt="root", metavar="PATH", default='/',
                             help="mirror filesystem from under PATH "
                             "[default: %default]")
    server.parse(values=server, errex=1)

    server.main()
    lind.persist_metadata("lind.metadata")
def restart_client(filenamelist):
    """
  <Purpose>
    Restarts the node manager.

  <Arguments>
    filenamelist - Currently not used, but is included for possible future use.

  <Exceptions>
    None

  <Side Effects>
    The current node manager is killed, and a new one is started.

  <Returns>
    None.
  """
    # kill nmmain if it is currently running
    retval = runonce.getprocesslock("seattlenodemanager")
    if retval == True:
        safe_log("[restart_client] Obtained the lock 'seattlenodemanager', it wasn't running.")
        # I got the lock, it wasn't running...
        # we want to start a new one, so lets release
        runonce.releaseprocesslock("seattlenodemanager")
    elif retval == False:
        # Someone has the lock, but I can't do anything...
        safe_log(
            "[restart_client] The lock 'seattlenodemanager' is held by an unknown process. Will try to start it anyways."
        )
    else:
        safe_log("[restart_client] Stopping the nodemanager.")
        # I know the process ID!   Let's stop the process...
        harshexit.portablekill(retval)

    safe_log("[restart_client] Starting the nodemanager.")

    # run the node manager.   I rely on it to do the smart thing (handle multiple
    # instances, etc.)
    nm_restart_command_args_list = ["python", "nmmain.py"]

    if run_nodemanager_in_foreground:
        nm_restart_command_args_list.append("--foreground")

    junkprocessobject = portable_popen.Popen(nm_restart_command_args_list)
示例#15
0
def main():
    global LOGGING

    if "-v" in sys.argv or "--verbose" in sys.argv:
        LOGGING = True

    usage = """
Lind Fuse File System.

""" + Fuse.fusage

    lind.load_fs()
    
    gotlock = runonce.getprocesslock('lind_fuse')
    if gotlock == True:
      pass
    else:
      if gotlock:
        print "\n\n#########################################################"
        print "[Warning] Another Process (pid: " + str(gotlock) + ") already in use."
        print "#########################################################\n\n"
      else:
        print "[Warning] Another Process is running"

    server = LindFuseFS(version="%prog " + fuse.__version__,
                 usage=usage,
                 dash_s_do='setsingle')

    server.multithreaded = False  # if this is true, better add some locks!

    server.parser.add_option("-v", "--verbose",
                             action="store_true",
                             dest="verbose",
                             default=False,
                             help="print extra information about which system"
                             " calls are being called.")

    server.parser.add_option(mountopt="root", metavar="PATH", default='/',
                             help="mirror filesystem from under PATH "
                             "[default: %default]")
    server.parse(values=server, errex=1)

    server.main()
    lind.persist_metadata("lind.metadata")
示例#16
0
def main():
  global configuration

  if not FOREGROUND:
    # Background ourselves.
    daemon.daemonize()


  # Check if we are running in testmode.
  if TEST_NM:
    nodemanager_pid = os.getpid()
    servicelogger.log("[INFO]: Running nodemanager in test mode on port <nodemanager_port>, "+
                      "pid %s." % str(nodemanager_pid))
    nodeman_pid_file = open(os.path.join(os.getcwd(), 'nodemanager.pid'), 'w')
    
    # Write out the pid of the nodemanager process that we started to a file.
    # This is only done if the nodemanager was started in test mode.
    try:
      nodeman_pid_file.write(str(nodemanager_pid))
    finally:
      nodeman_pid_file.close()

  else:
    # ensure that only one instance is running at a time...
    gotlock = runonce.getprocesslock("seattlenodemanager")

    if gotlock == True:
      # I got the lock.   All is well...
      pass
    else:
      if gotlock:
        servicelogger.log("[ERROR]:Another node manager process (pid: " + str(gotlock) + 
                        ") is running")
      else:
        servicelogger.log("[ERROR]:Another node manager process is running")
      return



  # Feature add for #1031: Log information about the system in the nm log...
  servicelogger.log('[INFO]:platform.python_version(): "' + 
    str(platform.python_version())+'"')
  servicelogger.log('[INFO]:platform.platform(): "' + 
    str(platform.platform())+'"')

  # uname on Android only yields 'Linux', let's be more specific.
  try:
    import android
    servicelogger.log('[INFO]:platform.uname(): Android / "' + 
      str(platform.uname())+'"')
  except ImportError:
    servicelogger.log('[INFO]:platform.uname(): "'+str(platform.uname())+'"')

  # I'll grab the necessary information first...
  servicelogger.log("[INFO]:Loading config")
  # BUG: Do this better?   Is this the right way to engineer this?
  configuration = persist.restore_object("nodeman.cfg")
  
  
  # Armon: initialize the network restrictions
  initialize_ip_interface_restrictions(configuration)
  
  
  
  # ZACK BOKA: For Linux and Darwin systems, check to make sure that the new
  #            seattle crontab entry has been installed in the crontab.
  #            Do this here because the "nodeman.cfg" needs to have been read
  #            into configuration via the persist module.
  if nonportable.ostype == 'Linux' or nonportable.ostype == 'Darwin':
    if 'crontab_updated_for_2009_installer' not in configuration or \
          configuration['crontab_updated_for_2009_installer'] == False:
      try:
        # crontab may not exist on Android, therefore let's not check
        # if we are running on Android. See #1302 and #1254.
        try:
          import android
        except ImportError:
          import update_crontab_entry
          modified_crontab_entry = \
              update_crontab_entry.modify_seattle_crontab_entry()
          # If updating the seattle crontab entry succeeded, then update the
          # 'crontab_updated_for_2009_installer' so the nodemanager no longer
          # tries to update the crontab entry when it starts up.
          if modified_crontab_entry:
            configuration['crontab_updated_for_2009_installer'] = True
            persist.commit_object(configuration,"nodeman.cfg")

      except Exception,e:
        exception_traceback_string = traceback.format_exc()
        servicelogger.log("[ERROR]: The following error occured when " \
                            + "modifying the crontab for the new 2009 " \
                            + "seattle crontab entry: " \
                            + exception_traceback_string)
示例#17
0
def main():
    global configuration

    if not FOREGROUND:
        # Background ourselves.
        daemon.daemonize()

    # Check if we are running in testmode.
    if TEST_NM:
        nodemanager_pid = os.getpid()
        servicelogger.log(
            "[INFO]: Running nodemanager in test mode on port 1224, " +
            "pid %s." % str(nodemanager_pid))
        nodeman_pid_file = open(os.path.join(os.getcwd(), 'nodemanager.pid'),
                                'w')

        # Write out the pid of the nodemanager process that we started to a file.
        # This is only done if the nodemanager was started in test mode.
        try:
            nodeman_pid_file.write(str(nodemanager_pid))
        finally:
            nodeman_pid_file.close()

    else:
        # ensure that only one instance is running at a time...
        gotlock = runonce.getprocesslock("seattlenodemanager")

        if gotlock == True:
            # I got the lock.   All is well...
            pass
        else:
            if gotlock:
                servicelogger.log(
                    "[ERROR]:Another node manager process (pid: " +
                    str(gotlock) + ") is running")
            else:
                servicelogger.log(
                    "[ERROR]:Another node manager process is running")
            return

    servicelogger.log('[INFO]: This is Seattle release "' + version + "'")

    # Feature add for #1031: Log information about the system in the nm log...
    servicelogger.log('[INFO]:platform.python_version(): "' +
                      str(platform.python_version()) + '"')
    servicelogger.log('[INFO]:platform.platform(): "' +
                      str(platform.platform()) + '"')

    # uname on Android only yields 'Linux', let's be more specific.
    try:
        import android
        servicelogger.log('[INFO]:platform.uname(): Android / "' +
                          str(platform.uname()) + '"')
    except ImportError:
        servicelogger.log('[INFO]:platform.uname(): "' +
                          str(platform.uname()) + '"')

    # I'll grab the necessary information first...
    servicelogger.log("[INFO]:Loading config")
    # BUG: Do this better?   Is this the right way to engineer this?
    configuration = persist.restore_object("nodeman.cfg")

    # Armon: initialize the network restrictions
    initialize_ip_interface_restrictions(configuration)

    # ZACK BOKA: For Linux and Darwin systems, check to make sure that the new
    #            seattle crontab entry has been installed in the crontab.
    #            Do this here because the "nodeman.cfg" needs to have been read
    #            into configuration via the persist module.
    if nonportable.ostype == 'Linux' or nonportable.ostype == 'Darwin':
        if 'crontab_updated_for_2009_installer' not in configuration or \
              configuration['crontab_updated_for_2009_installer'] == False:
            try:
                # crontab may not exist on Android, therefore let's not check
                # if we are running on Android. See #1302 and #1254.
                try:
                    import android
                except ImportError:
                    import update_crontab_entry
                    modified_crontab_entry = \
                        update_crontab_entry.modify_seattle_crontab_entry()
                    # If updating the seattle crontab entry succeeded, then update the
                    # 'crontab_updated_for_2009_installer' so the nodemanager no longer
                    # tries to update the crontab entry when it starts up.
                    if modified_crontab_entry:
                        configuration[
                            'crontab_updated_for_2009_installer'] = True
                        persist.commit_object(configuration, "nodeman.cfg")

            except Exception, e:
                exception_traceback_string = traceback.format_exc()
                servicelogger.log("[ERROR]: The following error occured when " \
                                    + "modifying the crontab for the new 2009 " \
                                    + "seattle crontab entry: " \
                                    + exception_traceback_string)
示例#18
0
def software_updater_start(mutexname):
  """
  <Purpose>
    When restarting the software updater, this method is called in the new 
    one.  It will write an OK file to let the original know it has started,
    then will wait for the original to acknowledge by either removing the OK
    file, meaning we should carry on, or by writing a stop file, meaning we
    should exit.  Carrying on means getting the softwareupdater.old lock, and
    releasing the softwareupdater.new lock, then returning.
  
  <Arguments>
    mutexname - The new software updater was started with a given mutex name,
                which is used to uniquely identify the stop and OK files as
                coming from this softwareupdater.  This way the old one can
                know that the softwareupdater it started is the one that is
                continueing on.

  <Exceptions>
    Possible Exception creating the OK file.

  <Side Effects>
    Acquires the softwareupdater.old lock and releases the softwareupdater.new
    lock.

  <Return>
    None
  """

  safe_log("[software_updater_start] This is a new software updater process started by an existing one.")

  # if "stop" file exists, then exit
  if os.path.exists("softwareupdater.stop."+mutexname):
    safe_log("[software_updater_start] There's a stop file. Exiting.")
    sys.exit(2)

  # write "OK" file
  file("softwareupdater.OK."+mutexname,"w").close()
  
  # while "OK" file exists
  while os.path.exists("softwareupdater.OK."+mutexname):
    safe_log("[software_updater_start] Waiting for the file softwareupdater.OK."+mutexname+" to be removed.")
    sleep(1.0)
    # if "stop" file exists, then exit
    if os.path.exists("softwareupdater.stop."+mutexname):
      sys.exit(3)

  # Get the process lock for the main part of the program.
  gotlock = runonce.getprocesslock("softwareupdater.old")
  # Release the lock on the initialization part of the program
  runonce.releaseprocesslock('softwareupdater.new')
  if gotlock == True:
    # I got the lock.   All is well...
    pass
  else:
    if gotlock:
      safe_log("[software_updater_start] Another software updater old process (pid: "+str(gotlock)+") is running")
      sys.exit(55)
    else:
      safe_log("[software_updater_start] Another software updater old process is running")
      sys.exit(55)
 
  safe_log("[software_updater_start] This software updater process is now taking over.")
 
  # start normal operation
  return
示例#19
0
def main():
  global configuration

  if not FOREGROUND:
    # Background ourselves.
    daemon.daemonize()


  # Check if we are running in testmode.
  if TEST_NM:
    nodemanager_pid = os.getpid()
    servicelogger.log("[INFO]: Running nodemanager in test mode on port 1224, "+
                      "pid %s." % str(nodemanager_pid))
    nodeman_pid_file = open(os.path.join(os.getcwd(), 'nodemanager.pid'), 'w')
    
    # Write out the pid of the nodemanager process that we started to a file.
    # This is only done if the nodemanager was started in test mode.
    try:
      nodeman_pid_file.write(str(nodemanager_pid))
    finally:
      nodeman_pid_file.close()

  else:
    # ensure that only one instance is running at a time...
    gotlock = runonce.getprocesslock("seattlenodemanager")

    if gotlock == True:
      # I got the lock.   All is well...
      pass
    else:
      if gotlock:
        servicelogger.log("[ERROR]:Another node manager process (pid: " + str(gotlock) + 
                        ") is running")
      else:
        servicelogger.log("[ERROR]:Another node manager process is running")
      return


  servicelogger.log('[INFO]: This is Seattle release "' + version + "'") 

  # Feature add for #1031: Log information about the system in the nm log...
  servicelogger.log('[INFO]:platform.python_version(): "' + 
    str(platform.python_version())+'"')
  servicelogger.log('[INFO]:platform.platform(): "' + 
    str(platform.platform())+'"')

  # uname on Android only yields 'Linux', let's be more specific.
  try:
    import android
    servicelogger.log('[INFO]:platform.uname(): Android / "' + 
      str(platform.uname())+'"')
  except ImportError:
    servicelogger.log('[INFO]:platform.uname(): "'+str(platform.uname())+'"')

  # I'll grab the necessary information first...
  servicelogger.log("[INFO]:Loading config")
  # BUG: Do this better?   Is this the right way to engineer this?
  configuration = persist.restore_object("nodeman.cfg")

  # If Seattle is not installed, the nodemanager will have no vesseldict
  # and an incomplete config. Log this problem and exit.
  try:
    if configuration["seattle_installed"] is not True:
      servicelogger.log("[ERROR]:Seattle is not installed. Run the Seattle installer to create the required configuration files before starting the nodemanager. Exiting.")
      harshexit.harshexit(10)
  except KeyError:
    # There isn't even a "seattle_installed" entry in this dict!?
    servicelogger.log("[ERROR]:The nodemanager configuration, nodeman.cfg, is corrupt. Exiting.")
    harshexit.harshexit(11)
  
  
  # Armon: initialize the network restrictions
  initialize_ip_interface_restrictions(configuration)
  
  
  # Enable Affix and overload various Repy network API calls 
  # with Affix-enabled calls.
  # Use the node's publickey to generate a name for our node.
  mypubkey = rsa_publickey_to_string(configuration['publickey']).replace(" ", "")
  affix_stack_name = sha_hexhash(mypubkey)

  enable_affix('(CoordinationAffix)(MakeMeHearAffix)(NamingAndResolverAffix,' + 
      affix_stack_name + ')')

  # get the external IP address...
  myip = None
  while True:
    try:
      # Try to find our external IP.
      myip = emulcomm.getmyip()
    except Exception, e: # Replace with InternetConnectivityError ?
      # If we aren't connected to the internet, emulcomm.getmyip() raises this:
      if len(e.args) >= 1 and e.args[0] == "Cannot detect a connection to the Internet.":
        # So we try again.
        pass
      else:
        # It wasn't emulcomm.getmyip()'s exception. re-raise.
        raise
    else:
      # We succeeded in getting our external IP. Leave the loop.
      break
    time.sleep(0.1)
示例#20
0
def software_updater_start(mutexname):
  """
  <Purpose>
    When restarting the software updater, this method is called in the new 
    one.  It will write an OK file to let the original know it has started,
    then will wait for the original to acknowledge by either removing the OK
    file, meaning we should carry on, or by writing a stop file, meaning we
    should exit.  Carrying on means getting the softwareupdater.old lock, and
    releasing the softwareupdater.new lock, then returning.
  
  <Arguments>
    mutexname - The new software updater was started with a given mutex name,
                which is used to uniquely identify the stop and OK files as
                coming from this softwareupdater.  This way the old one can
                know that the softwareupdater it started is the one that is
                continueing on.

  <Exceptions>
    Possible Exception creating the OK file.

  <Side Effects>
    Acquires the softwareupdater.old lock and releases the softwareupdater.new
    lock.

  <Return>
    None
  """

  safe_log("[software_updater_start] This is a new software updater process started by an existing one.")

  # if "stop" file exists, then exit
  if os.path.exists("softwareupdater.stop."+mutexname):
    safe_log("[software_updater_start] There's a stop file. Exiting.")
    sys.exit(2)

  # write "OK" file
  file("softwareupdater.OK."+mutexname,"w").close()
  
  # while "OK" file exists
  while os.path.exists("softwareupdater.OK."+mutexname):
    safe_log("[software_updater_start] Waiting for the file softwareupdater.OK."+mutexname+" to be removed.")
    misc.do_sleep(1.0)
    # if "stop" file exists, then exit
    if os.path.exists("softwareupdater.stop."+mutexname):
      sys.exit(3)

  # Get the process lock for the main part of the program.
  gotlock = runonce.getprocesslock("softwareupdater.old")
  # Release the lock on the initialization part of the program
  runonce.releaseprocesslock('softwareupdater.new')
  if gotlock == True:
    # I got the lock.   All is well...
    pass
  else:
    if gotlock:
      safe_log("[software_updater_start] Another software updater old process (pid: "+str(gotlock)+") is running")
      sys.exit(55)
    else:
      safe_log("[software_updater_start] Another software updater old process is running")
      sys.exit(55)
 
  safe_log("[software_updater_start] This software updater process is now taking over.")
 
  # start normal operation
  return
示例#21
0
import runonce
import time
import os
import random

lockname = "seattletestlock"

runonce.getprocesslock(str(os.getpid()))

print "my process id is:" + str(os.getpid())
retval = runonce.getprocesslock(lockname)

if retval == True:
    print "I have the mutex"
elif retval == False:
    print "Another process has the mutex (owned by another user most likely)"
else:
    print "Process " + str(retval) + " has the mutex!"

while True:
    for num in range(random.randint(0, 5)):
        time.sleep(2)
        if runonce.stillhaveprocesslock(lockname):
            print "I have the mutex"
        else:
            print "I do not have the mutex"
        if runonce.stillhaveprocesslock(str(os.getpid())):
            print "I have my mutex"
        else:
            print "I do not have my mutex"
示例#22
0
import runonce
import time
import os
import random

lockname = "seattletestlock"

runonce.getprocesslock(str(os.getpid()))

print "my process id is:"+str(os.getpid())
retval = runonce.getprocesslock(lockname)


if retval == True:
  print "I have the mutex"
elif retval == False:
  print "Another process has the mutex (owned by another user most likely)"
else:
  print "Process "+str(retval)+" has the mutex!"

while True:
  for num in range(random.randint(0,5)):
    time.sleep(2)
    if runonce.stillhaveprocesslock(lockname):
      print "I have the mutex"
    else:
      print "I do not have the mutex"
    if runonce.stillhaveprocesslock(str(os.getpid())):
      print "I have my mutex"
    else:
      print "I do not have my mutex"