6 # Useful information can be found at https://svn.planet-lab.org/wiki/NodeManager
9 # Faiyaz Ahmed <faiyaza at cs dot princeton dot edu>
10 # Copyright (C) 2008 The Trustees of Princeton University
26 from config import Config
27 from plcapi import PLCAPI
31 savedargv = sys.argv[:]
33 # NOTE: modules listed here should also be loaded in this order
34 known_modules=['net','conf_files', 'sm', 'bwmon']
36 plugin_path = "/usr/share/NodeManager/plugins"
41 parser = optparse.OptionParser()
42 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', default=False, help='run daemonized')
43 parser.add_option('-s', '--startup', action='store_true', dest='startup', default=False, help='run all sliver startup scripts')
44 parser.add_option('-f', '--config', action='store', dest='config', default='/etc/planetlab/plc_config', help='PLC configuration file')
45 parser.add_option('-k', '--session', action='store', dest='session', default='/etc/planetlab/session', help='API session key (or file)')
46 parser.add_option('-p', '--period', action='store', dest='period', default=default_period,
47 help='Polling interval (sec) - default %d'%default_period)
48 parser.add_option('-r', '--random', action='store', dest='random', default=default_random,
49 help='Range for additional random polling interval (sec) -- default %d'%default_random)
50 parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='more verbose log')
51 parser.add_option('-P', '--path', action='store', dest='path', default=plugin_path, help='Path to plugins directory')
53 # NOTE: BUG the 'help' for this parser.add_option() wont list plugins from the --path argument
54 parser.add_option('-m', '--module', action='store', dest='module', default='', help='run a single module among '+' '.join(known_modules))
55 (options, args) = parser.parse_args()
57 # Deal with plugins directory
58 if os.path.exists(options.path):
59 sys.path.append(options.path)
60 known_modules += [i[:-3] for i in os.listdir(options.path) if i.endswith(".py") and (i[:-3] not in known_modules)]
64 def GetSlivers(config, plc):
65 '''Run call backs defined in modules'''
67 logger.log("Syncing w/ PLC")
68 # retrieve GetSlivers from PLC
69 data = plc.GetSlivers()
70 # use the magic 'default' slice to retrieve system-wide defaults
71 getPLCDefaults(data, config)
72 # tweak the 'vref' attribute from GetSliceFamily
74 # always dump it for debug purposes
75 # used to be done only in verbose; very helpful though, and tedious to obtain,
76 # so let's dump this unconditionnally
77 logger.log_slivers(data)
78 logger.verbose("Sync w/ PLC done (3)")
80 logger.log_exc("failed in nm.GetSlivers")
81 # XXX So some modules can at least boostrap.
82 logger.log("nm: Can't contact PLC to GetSlivers(). Continuing.")
84 # Invoke GetSlivers() functions from the callback modules
85 for module in modules:
87 callback = getattr(module, 'GetSlivers')
88 callback(data, config, plc)
89 except: logger.log_exc("nm.GetSlivers failed to run callback for module %r"%module)
92 def getPLCDefaults(data, config):
94 Get PLC wide defaults from _default system slice. Adds them to config class.
96 for slice in data.get('slivers'):
97 if slice['name'] == config.PLC_SLICE_PREFIX+"_default":
99 for attr in slice.get('attributes'): attr_dict[attr['tagname']] = attr['value']
101 logger.verbose("Found default slice overrides.\n %s" % attr_dict)
102 config.OVERRIDES = attr_dict
104 # NOTE: if an _default slice existed, it would have been found above and
105 # the routine would return. Thus, if we've gotten here, then no default
106 # slice is bound to this node.
107 if 'OVERRIDES' in dir(config): del config.OVERRIDES
110 def setSliversVref (data):
112 Tweak the 'vref' attribute in all slivers based on the 'GetSliceFamily' key
114 # GetSlivers exposes the result of GetSliceFamily() as an separate key in data
115 # It is safe to override the attributes with this, as this method has the right logic
116 for sliver in data.get('slivers'):
118 slicefamily=sliver.get('GetSliceFamily')
119 for att in sliver['attributes']:
120 if att['tagname']=='vref':
121 att['value']=slicefamily
123 sliver['attributes'].append({ 'tagname':'vref','value':slicefamily})
125 logger.log_exc("Could not overwrite 'vref' attribute from 'GetSliceFamily'",name=sliver['name'])
130 if options.daemon: tools.daemon()
133 if (options.verbose):
134 logger.set_level(logger.LOG_VERBOSE)
136 # Load /etc/planetlab/plc_config
137 config = Config(options.config)
140 other_pid = tools.pid_file()
141 if other_pid != None:
142 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)
145 print "Warning while writing PID file:", err
147 # Load and start modules
149 assert options.module in known_modules
150 running_modules=[options.module]
151 logger.verbose('Running single module %s'%options.module)
153 running_modules=known_modules
154 for module in running_modules:
156 m = __import__(module)
157 m.start(options, config)
159 except ImportError, err:
160 print "Warning while loading module %s:" % module, err
162 # Load /etc/planetlab/session
163 if os.path.exists(options.session):
164 session = file(options.session).read().strip()
168 # Initialize XML-RPC client
169 iperiod=int(options.period)
170 irandom=int(options.random)
171 plc = PLCAPI(config.plc_api_uri, config.cacert, session, timeout=iperiod/2)
174 logger.log("Checking Auth.")
175 while plc.check_authentication() != True:
178 logger.log("Authentication Failure. Retrying")
180 logger.log("Retry Failed. Waiting")
182 logger.log("Authentication Succeeded!")
187 logger.verbose('mainloop - nm:getSlivers - period=%d random=%d'%(iperiod,irandom))
188 GetSlivers(config, plc)
189 delay=iperiod + random.randrange(0,irandom)
190 logger.verbose('mainloop - sleeping for %d s'%delay)
192 except: logger.log_exc("failed in nm.run")
195 if __name__ == '__main__':
196 logger.log("======================================== Entering nm.py "+id)
199 # This is for debugging purposes. Open a copy of Python and import nm
200 tools.as_daemon_thread(run)