Added support for white listing slices.
[nodemanager.git] / sm.py
1 """Sliver manager.
2
3 The sliver manager has several functions.  It is responsible for
4 creating, resource limiting, starting, stopping, and destroying
5 slivers.  It provides an API for users to access these functions and
6 also to make inter-sliver resource loans.  The sliver manager is also
7 responsible for handling delegation accounts.
8 """
9
10 try: from bwlimit import bwmin, bwmax
11 except ImportError: bwmin, bwmax = 8, 1000*1000*1000
12 import accounts
13 import api
14 import database
15 import delegate
16 import logger
17 import sliver_vs
18 import string,re
19
20
21 DEFAULT_ALLOCATION = {
22     'enabled': 1,
23     'whitelist': 1,
24     # CPU parameters
25     'cpu_min': 0, # ms/s
26     'cpu_share': 32, # proportional share
27     # bandwidth parameters
28     'net_min_rate': bwmin / 1000, # kbps
29     'net_max_rate': bwmax / 1000, # kbps
30     'net_share': 1, # proportional share
31     # bandwidth parameters over routes exempt from node bandwidth limits
32     'net_i2_min_rate': bwmin / 1000, # kbps
33     'net_i2_max_rate': bwmax / 1000, # kbps
34     'net_i2_share': 1, # proportional share
35     'net_max_kbyte' : 5662310, #Kbyte
36     'net_thresh_kbyte': 4529848, #Kbyte
37     'net_i2_max_kbyte': 17196646,
38     'net_i2_thresh_kbyte': 13757316,
39     # disk space limit
40     'disk_max': 5000000, # bytes
41
42     # VSERVER specific limits
43     # resident set size (memory) limits
44     'rss_min': sliver_vs.KEEP_LIMIT,
45     'rss_soft': sliver_vs.KEEP_LIMIT,
46     'rss_hard': sliver_vs.KEEP_LIMIT,
47     # address space limits
48     'as_min': sliver_vs.KEEP_LIMIT,
49     'as_soft': sliver_vs.KEEP_LIMIT,
50     'as_hard': sliver_vs.KEEP_LIMIT,
51     # number of process limit
52     'nproc_min': sliver_vs.KEEP_LIMIT,
53     'nproc_soft': sliver_vs.KEEP_LIMIT,
54     'nproc_hard': sliver_vs.KEEP_LIMIT,
55     # number of file descriptor limit
56     'openfd_min': sliver_vs.KEEP_LIMIT,
57     'openfd_soft': sliver_vs.KEEP_LIMIT,
58     'openfd_hard': sliver_vs.KEEP_LIMIT,
59     }
60
61 start_requested = False  # set to True in order to request that all slivers be started
62
63
64 def whitelistfilter():
65     """creates a regex (re) object based on the slice definitions
66        in /etc/planetlab/whitelist"""
67
68     whitelist = []
69     whitelist_re = re.compile("([a-zA-Z0-9\*]+)_([a-zA-Z0-9\*]+)")
70     linecount = 0
71     try:
72         f = open('/etc/planetlab/whitelist')
73         for line in f.readlines():
74             linecount = linecount+1
75             line = line.strip()
76             # skip comments
77             if len(line)>0 and line[0]=='#':
78                 continue
79             m = whitelist_re.search(line)
80             if m == None:
81                 logger.log("skipping line #%d in /etc/planetlab/whitelist" % linecount)
82                 continue
83             else:
84                 whitelist.append(m.group())
85         f.close()
86     except IOError,e:
87         logger.log("IOError -> %s" % e)
88         logger.log("No whitelist file found; setting slice white list to *_*")
89         whitelist = ["*_*"]
90
91     white_re_list = None
92     for w in whitelist:
93         w = string.replace(w,'*','([a-zA-Z0-9]+)')
94         if white_re_list == None:
95             white_re_list = w
96         else:
97             white_re_list = "(%s)|(%s)" % (white_re_list,w)
98
99     if white_re_list == None:
100         white_re_list = "([a-zA-Z0-9]+)_([a-zA-Z0-9]+)"
101
102     logger.log("whitelist regex = %s" % white_re_list)
103     whitelist_re = re.compile(white_re_list)
104     return whitelist_re
105
106 @database.synchronized
107 def GetSlivers(data, fullupdate=True):
108     """This function has two purposes.  One, convert GetSlivers() data
109     into a more convenient format.  Two, even if no updates are coming
110     in, use the GetSlivers() heartbeat as a cue to scan for expired
111     slivers."""
112
113     node_id = None
114     try:
115         f = open('/etc/planetlab/node_id')
116         try: node_id = int(f.read())
117         finally: f.close()
118     except: logger.log_exc()
119
120     if data.has_key('node_id') and data['node_id'] != node_id: return
121
122     if data.has_key('networks'):
123         for network in data['networks']:
124             if network['is_primary'] and network['bwlimit'] is not None:
125                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
126
127 ### Emulab-specific hack begins here
128     emulabdelegate = {
129         'instantiation': 'plc-instantiated',
130         'keys': '''ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5Rimz6osRvlAUcaxe0YNfGsLL4XYBN6H30V3l/0alZOSXbGOgWNdEEdohwbh9E8oYgnpdEs41215UFHpj7EiRudu8Nm9mBI51ARHA6qF6RN+hQxMCB/Pxy08jDDBOGPefINq3VI2DRzxL1QyiTX0jESovrJzHGLxFTB3Zs+Y6CgmXcnI9i9t/zVq6XUAeUWeeXA9ADrKJdav0SxcWSg+B6F1uUcfUd5AHg7RoaccTldy146iF8xvnZw0CfGRCq2+95AU9rbMYS6Vid8Sm+NS+VLaAyJaslzfW+CAVBcywCOlQNbLuvNmL82exzgtl6fVzutRFYLlFDwEM2D2yvg4BQ== root@boss.emulab.net''',
131         'name': 'utah_elab_delegate',
132         'timestamp': data['timestamp'],
133         'type': 'delegate',
134         'vref': None
135         }
136     database.db.deliver_record(emulabdelegate)
137 ### Emulab-specific hack ends here
138
139
140     initscripts_by_id = {}
141     for is_rec in data['initscripts']:
142         initscripts_by_id[str(is_rec['initscript_id'])] = is_rec['script']
143
144     # remove slivers not on the whitelist
145     whitelist_regex = whitelistfilter()
146     
147     for sliver in data['slivers']:
148         rec = sliver.copy()
149         rec.setdefault('timestamp', data['timestamp'])
150
151         # convert attributes field to a proper dict
152         attr_dict = {}
153         for attr in rec.pop('attributes'): attr_dict[attr['name']] = attr['value']
154
155         # squash keys
156         keys = rec.pop('keys')
157         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
158
159         rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
160         rec.setdefault('vref', attr_dict.get('vref', 'default'))
161         is_id = attr_dict.get('plc_initscript_id')
162         if is_id is not None and is_id in initscripts_by_id:
163             rec['initscript'] = initscripts_by_id[is_id]
164         else:
165             rec['initscript'] = ''
166         rec.setdefault('delegations', [])  # XXX - delegation not yet supported
167
168         # extract the implied rspec
169         rspec = {}
170         rec['rspec'] = rspec
171         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
172             try: amt = int(attr_dict[resname])
173             except (KeyError, ValueError): amt = default_amt
174             rspec[resname] = amt
175
176         # disable sliver
177         m = whitelist_regex.search(sliver['name'])
178         if m == None:
179             rspec['whitelist'] = 0
180             rspec['enabled'] = 0
181
182         database.db.deliver_record(rec)
183     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
184     database.db.sync()
185
186     # handle requested startup
187     global start_requested
188     if start_requested:
189         start_requested = False
190         cumulative_delay = 0
191         for name in database.db.iterkeys():
192             accounts.get(name).start(delay=cumulative_delay)
193             cumulative_delay += 3
194
195 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
196
197
198 def start(options, config):
199     accounts.register_class(sliver_vs.Sliver_VS)
200     accounts.register_class(delegate.Delegate)
201     global start_requested
202     start_requested = options.startup
203     database.start()
204     api.deliver_ticket = deliver_ticket
205     api.start()