* BWmon is now event driven and handles reboots. Also got rid of ALL legacy code.
[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     # NOTE: this table is further populated with resource names and
43     # default amounts via the start() function below.  This probably
44     # should be changeg and these values should be obtained via the
45     # API to myplc.
46     }
47
48 start_requested = False  # set to True in order to request that all slivers be started
49
50
51 def whitelistfilter():
52     """creates a regex (re) object based on the slice definitions
53        in /etc/planetlab/whitelist"""
54
55     whitelist = []
56     whitelist_re = re.compile("([a-zA-Z0-9\*]+)_([a-zA-Z0-9\*]+)")
57     linecount = 0
58     try:
59         f = open('/etc/planetlab/whitelist')
60         for line in f.readlines():
61             linecount = linecount+1
62             line = line.strip()
63             # skip comments
64             if len(line)>0 and line[0]=='#':
65                 continue
66             m = whitelist_re.search(line)
67             if m == None:
68                 logger.log("skipping line #%d in /etc/planetlab/whitelist" % linecount)
69                 continue
70             else:
71                 whitelist.append(m.group())
72         f.close()
73     except IOError,e:
74         logger.log("IOError -> %s" % e)
75         logger.log("No whitelist file found; setting slice white list to *_*")
76         whitelist = ["*_*"]
77
78     white_re_list = None
79     for w in whitelist:
80         w = string.replace(w,'*','([a-zA-Z0-9]+)')
81         if white_re_list == None:
82             white_re_list = w
83         else:
84             white_re_list = "(%s)|(%s)" % (white_re_list,w)
85
86     if white_re_list == None:
87         white_re_list = "([a-zA-Z0-9]+)_([a-zA-Z0-9]+)"
88
89     logger.log("whitelist regex = %s" % white_re_list)
90     whitelist_re = re.compile(white_re_list)
91     return whitelist_re
92
93 @database.synchronized
94 def GetSlivers(data, fullupdate=True):
95     """This function has two purposes.  One, convert GetSlivers() data
96     into a more convenient format.  Two, even if no updates are coming
97     in, use the GetSlivers() heartbeat as a cue to scan for expired
98     slivers."""
99
100     node_id = None
101     try:
102         f = open('/etc/planetlab/node_id')
103         try: node_id = int(f.read())
104         finally: f.close()
105     except: logger.log_exc()
106
107     if data.has_key('node_id') and data['node_id'] != node_id: return
108
109     if data.has_key('networks'):
110         for network in data['networks']:
111             if network['is_primary'] and network['bwlimit'] is not None:
112                 DEFAULT_ALLOCATION['net_max_rate'] = network['bwlimit'] / 1000
113
114 ### Emulab-specific hack begins here
115 #    emulabdelegate = {
116 #        'instantiation': 'plc-instantiated',
117 #        'keys': '''ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA5Rimz6osRvlAUcaxe0YNfGsLL4XYBN6H30V3l/0alZOSXbGOgWNdEEdohwbh9E8oYgnpdEs41215UFHpj7EiRudu8Nm9mBI51ARHA6qF6RN+hQxMCB/Pxy08jDDBOGPefINq3VI2DRzxL1QyiTX0jESovrJzHGLxFTB3Zs+Y6CgmXcnI9i9t/zVq6XUAeUWeeXA9ADrKJdav0SxcWSg+B6F1uUcfUd5AHg7RoaccTldy146iF8xvnZw0CfGRCq2+95AU9rbMYS6Vid8Sm+NS+VLaAyJaslzfW+CAVBcywCOlQNbLuvNmL82exzgtl6fVzutRFYLlFDwEM2D2yvg4BQ== root@boss.emulab.net''',
118  #       'name': 'utah_elab_delegate',
119  #       'timestamp': data['timestamp'],
120  #       'type': 'delegate',
121  #       'vref': None
122  #       }
123  #   database.db.deliver_record(emulabdelegate)
124 ### Emulab-specific hack ends here
125
126
127     initscripts_by_id = {}
128     for is_rec in data['initscripts']:
129         initscripts_by_id[str(is_rec['initscript_id'])] = is_rec['script']
130
131     # remove slivers not on the whitelist
132     whitelist_regex = whitelistfilter()
133     
134     for sliver in data['slivers']:
135         rec = sliver.copy()
136         rec.setdefault('timestamp', data['timestamp'])
137
138         # convert attributes field to a proper dict
139         attr_dict = {}
140         for attr in rec.pop('attributes'): attr_dict[attr['name']] = attr['value']
141
142         # squash keys
143         keys = rec.pop('keys')
144         rec.setdefault('keys', '\n'.join([key_struct['key'] for key_struct in keys]))
145
146         # Handle nm controller here
147                 rec.setdefault('type', attr_dict.get('type', 'sliver.VServer'))
148                 if rec['instantiation'] == 'nm-controller':
149                 # type isn't returned by GetSlivers() for whatever reason.  We're overloading
150                 # instantiation here, but i suppose its the ssame thing when you think about it. -FA
151                         rec['type'] = 'delegate'
152
153         rec.setdefault('vref', attr_dict.get('vref', 'default'))
154         is_id = attr_dict.get('plc_initscript_id')
155         if is_id is not None and is_id in initscripts_by_id:
156             rec['initscript'] = initscripts_by_id[is_id]
157         else:
158             rec['initscript'] = ''
159         rec.setdefault('delegations', [])
160
161         # extract the implied rspec
162         rspec = {}
163         rec['rspec'] = rspec
164         for resname, default_amt in DEFAULT_ALLOCATION.iteritems():
165             try: amt = int(attr_dict[resname])
166             except (KeyError, ValueError): amt = default_amt
167             rspec[resname] = amt
168
169         # disable sliver
170         m = whitelist_regex.search(sliver['name'])
171         if m == None:
172             rspec['whitelist'] = 0
173             rspec['enabled'] = 0
174
175         database.db.deliver_record(rec)
176     if fullupdate: database.db.set_min_timestamp(data['timestamp'])
177     database.db.sync()
178
179     # handle requested startup
180     global start_requested
181     if start_requested:
182         start_requested = False
183         cumulative_delay = 0
184         for name in database.db.iterkeys():
185             accounts.get(name).start(delay=cumulative_delay)
186             cumulative_delay += 3
187
188 def deliver_ticket(data): return GetSlivers(data, fullupdate=False)
189
190
191 def start(options, config):
192     for resname, default_amt in sliver_vs.DEFAULT_ALLOCATION.iteritems():
193         DEFAULT_ALLOCATION[resname]=default_amt
194         
195     accounts.register_class(sliver_vs.Sliver_VS)
196     accounts.register_class(delegate.Delegate)
197     global start_requested
198     start_requested = options.startup
199     database.start()
200     api.deliver_ticket = deliver_ticket
201     api.start()