3 # Useful information can be found at https://svn.planet-lab.org/wiki/NodeManager
6 # Faiyaz Ahmed <faiyaza at cs dot princeton dot edu>
7 # Copyright (C) 2008 The Trustees of Princeton University
26 from config import Config
27 from plcapi import PLCAPI
32 PLUGIN_PATH = "/usr/share/NodeManager/plugins"
34 DB_FILE = "/var/lib/nodemanager/getslivers.pickle"
36 # the modules in this directory that need to be run
37 # NOTE: modules listed here will also be loaded in this order
38 # once loaded, they get re-ordered after their priority (lower comes first)
39 # for determining the runtime order
40 core_modules=['net', 'conf_files', 'slivermanager', 'bwmon']
48 parser = optparse.OptionParser()
49 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', default=False,
50 help='run daemonized')
51 parser.add_option('-f', '--config', action='store', dest='config', default='/etc/planetlab/plc_config',
52 help='PLC configuration file')
53 parser.add_option('-k', '--session', action='store', dest='session', default='/etc/planetlab/session',
54 help='API session key (or file)')
55 parser.add_option('-p', '--period', action='store', dest='period', default=NodeManager.default_period,
56 help='Polling interval (sec) - default %d'%NodeManager.default_period)
57 parser.add_option('-r', '--random', action='store', dest='random', default=NodeManager.default_random,
58 help='Range for additional random polling interval (sec) -- default %d'%NodeManager.default_random)
59 parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False,
60 help='more verbose log')
61 parser.add_option('-P', '--path', action='store', dest='path', default=NodeManager.PLUGIN_PATH,
62 help='Path to plugins directory')
64 # NOTE: BUG the 'help' for this parser.add_option() wont list plugins from the --path argument
65 parser.add_option('-m', '--module', action='store', dest='user_module', default='', help='run a single module')
66 (self.options, args) = parser.parse_args()
72 # determine the modules to be run
73 self.modules = NodeManager.core_modules
74 # Deal with plugins directory
75 if os.path.exists(self.options.path):
76 sys.path.append(self.options.path)
77 plugins = [ os.path.split(os.path.splitext(x)[0])[1] for x in glob.glob( os.path.join(self.options.path,'*.py') ) ]
78 self.modules += plugins
79 if self.options.user_module:
80 assert self.options.user_module in self.modules
81 self.modules=[self.options.user_module]
82 logger.verbose('nodemanager: Running single module %s'%self.options.user_module)
85 def GetSlivers(self, config, plc):
86 """Retrieves GetSlivers at PLC and triggers callbacks defined in modules/plugins"""
88 logger.log("nodemanager: Syncing w/ PLC")
89 # retrieve GetSlivers from PLC
90 data = plc.GetSlivers()
91 # use the magic 'default' slice to retrieve system-wide defaults
92 self.getPLCDefaults(data, config)
93 # tweak the 'vref' attribute from GetSliceFamily
94 self.setSliversVref (data)
95 # dump it too, so it can be retrieved later in case of comm. failure
96 self.dumpSlivers(data)
97 # log it for debug purposes, no matter what verbose is
98 logger.log_slivers(data)
99 logger.verbose("nodemanager: Sync w/ PLC done")
102 logger.log_exc("nodemanager: failed in GetSlivers")
103 # XXX So some modules can at least boostrap.
104 logger.log("nodemanager: Can't contact PLC to GetSlivers(). Continuing.")
106 # for modules that request it though the 'persistent_data' property
107 last_data=self.loadSlivers()
108 # Invoke GetSlivers() functions from the callback modules
109 for module in self.loaded_modules:
110 logger.verbose('nodemanager: triggering %s.GetSlivers'%module.__name__)
112 callback = getattr(module, 'GetSlivers')
114 if getattr(module,'persistent_data',False):
115 module_data=last_data
116 callback(data, config, plc)
118 logger.log_exc("nodemanager: GetSlivers failed to run callback for module %r"%module)
121 def getPLCDefaults(self, data, config):
123 Get PLC wide defaults from _default system slice. Adds them to config class.
125 for slice in data.get('slivers'):
126 if slice['name'] == config.PLC_SLICE_PREFIX+"_default":
128 for attr in slice.get('attributes'): attr_dict[attr['tagname']] = attr['value']
130 logger.verbose("nodemanager: Found default slice overrides.\n %s" % attr_dict)
131 config.OVERRIDES = attr_dict
133 # NOTE: if an _default slice existed, it would have been found above and
134 # the routine would return. Thus, if we've gotten here, then no default
135 # slice is bound to this node.
136 if 'OVERRIDES' in dir(config): del config.OVERRIDES
139 def setSliversVref (self, data):
141 Tweak the 'vref' attribute in all slivers based on the 'GetSliceFamily' key
143 # GetSlivers exposes the result of GetSliceFamily() as an separate key in data
144 # It is safe to override the attributes with this, as this method has the right logic
145 for sliver in data.get('slivers'):
147 slicefamily=sliver.get('GetSliceFamily')
148 for att in sliver['attributes']:
149 if att['tagname']=='vref':
150 att['value']=slicefamily
152 sliver['attributes'].append({ 'tagname':'vref','value':slicefamily})
154 logger.log_exc("nodemanager: Could not overwrite 'vref' attribute from 'GetSliceFamily'",name=sliver['name'])
156 def dumpSlivers (self, slivers):
157 f = open(NodeManager.DB_FILE, "w")
158 logger.log ("nodemanager: saving successfully fetched GetSlivers in %s" % NodeManager.DB_FILE)
159 pickle.dump(slivers, f)
162 def loadSlivers (self):
164 f = open(NodeManager.DB_FILE, "r+")
165 logger.log("nodemanager: restoring latest known GetSlivers from %s" % NodeManager.DB_FILE)
166 slivers = pickle.load(f)
170 logger.log("Could not restore GetSlivers from %s" % NodeManager.DB_FILE)
175 if self.options.daemon: tools.daemon()
178 if (self.options.verbose):
179 logger.set_level(logger.LOG_VERBOSE)
181 # Load /etc/planetlab/plc_config
182 config = Config(self.options.config)
185 other_pid = tools.pid_file()
186 if other_pid != None:
187 print """There might be another instance of the node manager running as pid %d.
188 If this is not the case, please remove the pid file %s. -- exiting""" % (other_pid, tools.PID_FILE)
191 print "Warning while writing PID file:", err
194 self.loaded_modules = []
195 for module in self.modules:
197 m = __import__(module)
198 logger.verbose("nodemanager: triggering %s.start"%m.__name__)
200 self.loaded_modules.append(m)
201 except ImportError, err:
202 logger.log_exc ("ERROR while loading module %s - skipping:" % module)
203 # if we fail to load any of these, it's really no need to go on any further
204 if module in NodeManager.core_modules:
205 logger.log("FATAL : failed to load core module %s"%module)
207 # sort on priority (lower first)
208 def sort_module_priority (m1,m2):
209 return getattr(m1,'priority',NodeManager.default_priority) - getattr(m2,'priority',NodeManager.default_priority)
210 self.loaded_modules.sort(sort_module_priority)
212 logger.log('ordered modules:')
213 for module in self.loaded_modules:
214 logger.log ('%s: %s'%(getattr(module,'priority',NodeManager.default_priority),module.__name__))
216 # Load /etc/planetlab/session
217 if os.path.exists(self.options.session):
218 session = file(self.options.session).read().strip()
224 iperiod=int(self.options.period)
225 irandom=int(self.options.random)
227 # Initialize XML-RPC client
228 plc = PLCAPI(config.plc_api_uri, config.cacert, session, timeout=iperiod/2)
231 logger.log("nodemanager: Checking Auth.")
232 while plc.check_authentication() != True:
235 logger.log("nodemanager: Authentication Failure. Retrying")
237 logger.log("nodemanager: Retry Failed. (%r); Waiting.."%e)
239 logger.log("nodemanager: Authentication Succeeded!")
243 # Main nodemanager Loop
245 logger.log('nodemanager: mainloop - calling GetSlivers - period=%d random=%d'%(iperiod,irandom))
246 self.GetSlivers(config, plc)
247 delay=iperiod + random.randrange(0,irandom)
249 work_duration=int(work_end-work_beg)
250 logger.log('nodemanager: mainloop has worked for %s s - sleeping for %d s'%(work_duration,delay))
252 except: logger.log_exc("nodemanager: failed in run")
255 logger.log("======================================== Entering nodemanager.py")
258 if __name__ == '__main__':
261 # This is for debugging purposes. Open a copy of Python and import nodemanager
262 tools.as_daemon_thread(run)