Use codemux condrestart.
[nodemanager.git] / nm.py
1 #!/usr/bin/python
2
3 #
4 # Useful information can be found at https://svn.planet-lab.org/wiki/NodeManager
5 #
6
7 # Faiyaz Ahmed <faiyaza at cs dot princeton dot edu>
8 # Copyright (C) 2008 The Trustees of Princeton University
9
10
11 """Node Manager"""
12
13 import optparse
14 import time
15 import xmlrpclib
16 import socket
17 import os
18 import sys
19 import resource
20
21 import logger
22 import tools
23
24 from config import Config
25 from plcapi import PLCAPI 
26 import random
27 import net
28
29 id="$Id$"
30 savedargv = sys.argv[:]
31
32 known_modules=['conf_files', 'sm', 'bwmon', 'vsys', 'codemux']
33
34 parser = optparse.OptionParser()
35 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', default=False, help='run daemonized')
36 parser.add_option('-s', '--startup', action='store_true', dest='startup', default=False, help='run all sliver startup scripts')
37 parser.add_option('-f', '--config', action='store', dest='config', default='/etc/planetlab/plc_config', help='PLC configuration file')
38 parser.add_option('-k', '--session', action='store', dest='session', default='/etc/planetlab/session', help='API session key (or file)')
39 parser.add_option('-p', '--period', action='store', dest='period', default=600, help='Polling interval (sec)')
40 parser.add_option('-r', '--random', action='store', dest='random', default=301, help='Range for additional random polling interval (sec)')
41 parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='more verbose log')
42 parser.add_option('-P', '--path', action='store', dest='path', default='/usr/share/NodeManager/plugins', help='Path to plugins directory')
43 parser.add_option('-m', '--module', action='store', dest='module', default='', help='run a single module among '+' '.join(known_modules))
44 (options, args) = parser.parse_args()
45
46 # Deal with plugins directory
47 if os.path.exists(options.path):
48     sys.path.append(options.path)
49     known_modules += [i[:-3] for i in os.listdir(options.path) if i.endswith(".py") and (i[:-3] not in known_modules)]
50
51 modules = []
52
53 def GetSlivers(plc):
54     '''Run call backs defined in modules'''
55     try: 
56         logger.log("Syncing w/ PLC")
57         data = plc.GetSlivers()
58     except: 
59         logger.log_exc()
60         #  XXX So some modules can at least boostrap.
61         data = {}
62     if (options.verbose):
63         logger.log_slivers(data)
64     # Set i2 ip list for nodes in I2 nodegroup.
65     try: net.GetSlivers(plc, data)
66     except: logger.log_exc()
67     #  All other callback modules
68     for module in modules:
69         try:        
70             callback = getattr(module, 'GetSlivers')
71             callback(data)
72         except: logger.log_exc()
73
74 def run():
75     try:
76         if options.daemon: tools.daemon()
77
78         # set log level
79         if (options.verbose):
80             logger.set_level(logger.LOG_VERBOSE)
81
82         # Load /etc/planetlab/plc_config
83         config = Config(options.config)
84
85         try:
86             other_pid = tools.pid_file()
87             if other_pid != None:
88                 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)
89                 return
90         except OSError, err:
91             print "Warning while writing PID file:", err
92
93         # Load and start modules
94         if options.module:
95             assert options.module in known_modules
96             running_modules=[options.module]
97             logger.verbose('Running single module %s'%options.module)
98         else:
99             running_modules=known_modules
100         for module in running_modules:
101             try:
102                 m = __import__(module)
103                 m.start(options, config)
104                 modules.append(m)
105             except ImportError, err:
106                 print "Warning while loading module %s:" % module, err
107
108         # Load /etc/planetlab/session
109         if os.path.exists(options.session):
110             session = file(options.session).read().strip()
111         else:
112             session = options.session
113
114         # Initialize XML-RPC client
115         iperiod=int(options.period)
116         irandom=int(options.random)
117         plc = PLCAPI(config.plc_api_uri, config.cacert, session, timeout=iperiod/2)
118
119         while True:
120         # Main NM Loop
121             logger.verbose('mainloop - nm:getSlivers - period=%d random=%d'%(iperiod,irandom))
122             GetSlivers(plc)
123             delay=iperiod + random.randrange(0,irandom)
124             logger.verbose('mainloop - sleeping for %d s'%delay)
125             time.sleep(delay)
126     except: logger.log_exc()
127
128
129 if __name__ == '__main__':
130     logger.log("Entering nm.py "+id)
131     stacklim = 512*1024  # 0.5 MiB
132     curlim = resource.getrlimit(resource.RLIMIT_STACK)[0]  # soft limit
133     if curlim > stacklim:
134         resource.setrlimit(resource.RLIMIT_STACK, (stacklim, stacklim))
135         # for some reason, doesn't take effect properly without the exec()
136         python = '/usr/bin/python'
137         os.execv(python, [python] + savedargv)
138     run()
139 else:
140     # This is for debugging purposes.  Open a copy of Python and import nm
141     tools.as_daemon_thread(run)