Increase disk limit.
[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
28 id="$Id$"
29 savedargv = sys.argv[:]
30
31 # NOTE: modules listed here should also be loaded in this order
32 known_modules=['net','conf_files', 'sm', 'bwmon']
33
34 plugin_path = "/usr/share/NodeManager/plugins"
35
36 parser = optparse.OptionParser()
37 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', default=False, help='run daemonized')
38 parser.add_option('-s', '--startup', action='store_true', dest='startup', default=False, help='run all sliver startup scripts')
39 parser.add_option('-f', '--config', action='store', dest='config', default='/etc/planetlab/plc_config', help='PLC configuration file')
40 parser.add_option('-k', '--session', action='store', dest='session', default='/etc/planetlab/session', help='API session key (or file)')
41 parser.add_option('-p', '--period', action='store', dest='period', default=600, help='Polling interval (sec)')
42 parser.add_option('-r', '--random', action='store', dest='random', default=301, help='Range for additional random polling interval (sec)')
43 parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False, help='more verbose log')
44 parser.add_option('-P', '--path', action='store', dest='path', default=plugin_path, help='Path to plugins directory')
45
46 # NOTE: BUG the 'help' for this parser.add_option() wont list plugins from the --path argument
47 parser.add_option('-m', '--module', action='store', dest='module', default='', help='run a single module among '+' '.join(known_modules))
48 (options, args) = parser.parse_args()
49
50 # Deal with plugins directory
51 if os.path.exists(options.path):
52     sys.path.append(options.path)
53     known_modules += [i[:-3] for i in os.listdir(options.path) if i.endswith(".py") and (i[:-3] not in known_modules)]
54
55 modules = []
56
57 def GetSlivers(config, plc):
58     '''Run call backs defined in modules'''
59     try: 
60         logger.log("Syncing w/ PLC")
61         data = plc.GetSlivers()
62         if (options.verbose): logger.log_slivers(data)
63         getPLCDefaults(data, config)
64     except: 
65         logger.log_exc()
66         #  XXX So some modules can at least boostrap.
67         logger.log("nm:  Can't contact PLC to GetSlivers().  Continuing.")
68         data = {}
69     #  Invoke GetSlivers() functions from the callback modules
70     for module in modules:
71         try:        
72             callback = getattr(module, 'GetSlivers')
73             callback(data, config, plc)
74         except: logger.log_exc()
75
76
77 def getPLCDefaults(data, config):
78     '''
79     Get PLC wide defaults from _default system slice.  Adds them to config class.
80     '''
81     for slice in data.get('slivers'): 
82         if slice['name'] == config.PLC_SLICE_PREFIX+"_default":
83             attr_dict = {}
84             for attr in slice.get('attributes'): attr_dict[attr['tagname']] = attr['value'] 
85             if len(attr_dict):
86                 logger.verbose("Found default slice overrides.\n %s" % attr_dict)
87                 config.OVERRIDES = attr_dict
88         elif 'OVERRIDES' in dir(config): del config.OVERRIDES
89
90
91 def run():
92     try:
93         if options.daemon: tools.daemon()
94
95         # set log level
96         if (options.verbose):
97             logger.set_level(logger.LOG_VERBOSE)
98
99         # Load /etc/planetlab/plc_config
100         config = Config(options.config)
101
102         try:
103             other_pid = tools.pid_file()
104             if other_pid != None:
105                 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)
106                 return
107         except OSError, err:
108             print "Warning while writing PID file:", err
109
110         # Load and start modules
111         if options.module:
112             assert options.module in known_modules
113             running_modules=[options.module]
114             logger.verbose('Running single module %s'%options.module)
115         else:
116             running_modules=known_modules
117         for module in running_modules:
118             try:
119                 m = __import__(module)
120                 m.start(options, config)
121                 modules.append(m)
122             except ImportError, err:
123                 print "Warning while loading module %s:" % module, err
124
125         # Load /etc/planetlab/session
126         if os.path.exists(options.session):
127             session = file(options.session).read().strip()
128         else:
129             session = None
130
131         # Initialize XML-RPC client
132         iperiod=int(options.period)
133         irandom=int(options.random)
134         plc = PLCAPI(config.plc_api_uri, config.cacert, session, timeout=iperiod/2)
135
136         #check auth
137         logger.log("Checking Auth.")
138         while plc.check_authentication() != True:
139             try:
140                 plc.update_session()
141                 logger.log("Authentication Failure.  Retrying")
142             except:
143                 logger.log("Retry Failed.  Waiting")
144             time.sleep(iperiod)
145         logger.log("Authentication Succeeded!")
146
147
148         while True:
149         # Main NM Loop
150             logger.verbose('mainloop - nm:getSlivers - period=%d random=%d'%(iperiod,irandom))
151             GetSlivers(config, plc)
152             delay=iperiod + random.randrange(0,irandom)
153             logger.verbose('mainloop - sleeping for %d s'%delay)
154             time.sleep(delay)
155     except: logger.log_exc()
156
157
158 if __name__ == '__main__':
159     logger.log("Entering nm.py "+id)
160     run()
161 else:
162     # This is for debugging purposes.  Open a copy of Python and import nm
163     tools.as_daemon_thread(run)