e44f78f5383f54998ce37de49f86446082817925
[nodemanager.git] / nm.py
1 #!/usr/bin/python
2
3 """Node Manager"""
4
5 import optparse
6 import time
7 import xmlrpclib
8 import socket
9 import os
10
11 import logger
12 import tools
13
14 from config import Config
15 from plcapi import PLCAPI
16
17 parser = optparse.OptionParser()
18 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', default=False, help='run daemonized')
19 parser.add_option('-s', '--startup', action='store_true', dest='startup', default=False, help='run all sliver startup scripts')
20 parser.add_option('-f', '--config', action='store', dest='config', default='/etc/planetlab/plc_config', help='PLC configuration file')
21 parser.add_option('-k', '--session', action='store', dest='session', default='/etc/planetlab/session', help='API session key (or file)')
22 parser.add_option('-p', '--period', action='store', dest='period', default=600, help='Polling interval (sec)')
23 (options, args) = parser.parse_args()
24
25 modules = []
26
27 def GetSlivers(plc):
28     data = plc.GetSlivers()
29     for module in modules:
30         callback = getattr(module, 'GetSlivers')
31         callback(data)
32
33 def run():
34     try:
35         if options.daemon: tools.daemon()
36
37         # Load /etc/planetlab/plc_config
38         config = Config(options.config)
39
40         try:
41             other_pid = tools.pid_file()
42             if other_pid != None:
43                 print """There might be another instance of the node manager running as pid %d.  If this is not the case, please remove the pid file %s""" % (other_pid, tools.PID_FILE)
44                 return
45         except OSError, err:
46             print "Warning while writing PID file:", err
47
48         # Load and start modules
49         for module in ['net', 'sm', 'conf_files']:
50             try:
51                 m = __import__(module)
52                 m.start(options, config)
53                 modules.append(m)
54             except ImportError, err:
55                 print "Warning while loading module %s:" % module, err
56
57         # Load /etc/planetlab/session
58         if os.path.exists(options.session):
59             session = file(options.session).read().strip()
60         else:
61             session = options.session
62
63         # Initialize XML-RPC client
64         plc = PLCAPI(config.plc_api_uri, config.cacert, session, timeout=options.period/2)
65
66         while True:
67             try: GetSlivers(plc)
68             except: logger.log_exc()
69             time.sleep(options.period)
70     except: logger.log_exc()
71
72
73 if __name__ == '__main__': run()
74 else:
75     # This is for debugging purposes.  Open a copy of Python and import nm
76     tools.as_daemon_thread(run)